fullcalendar.js 273 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732
  1. /*!
  2. * FullCalendar v2.2.5
  3. * Docs & License: http://arshaw.com/fullcalendar/
  4. * (c) 2013 Adam Shaw
  5. */
  6. (function(factory) {
  7. if (typeof define === 'function' && define.amd) {
  8. define([ 'jquery', 'moment' ], factory);
  9. }
  10. else {
  11. factory(jQuery, moment);
  12. }
  13. })(function($, moment) {
  14. var defaults = {
  15. titleRangeSeparator: ' \u2014 ', // emphasized dash
  16. monthYearFormat: 'MMMM YYYY', // required for en. other languages rely on datepicker computable option
  17. defaultTimedEventDuration: '02:00:00',
  18. defaultAllDayEventDuration: { days: 1 },
  19. forceEventDuration: false,
  20. nextDayThreshold: '09:00:00', // 9am
  21. // display
  22. defaultView: 'month',
  23. aspectRatio: 1.35,
  24. header: {
  25. left: 'title',
  26. center: '',
  27. right: 'today prev,next'
  28. },
  29. weekends: true,
  30. weekNumbers: false,
  31. weekNumberTitle: 'W',
  32. weekNumberCalculation: 'local',
  33. //editable: false,
  34. // event ajax
  35. lazyFetching: true,
  36. startParam: 'start',
  37. endParam: 'end',
  38. timezoneParam: 'timezone',
  39. timezone: false,
  40. //allDayDefault: undefined,
  41. // locale
  42. isRTL: false,
  43. defaultButtonText: {
  44. prev: "prev",
  45. next: "next",
  46. prevYear: "prev year",
  47. nextYear: "next year",
  48. today: 'today',
  49. month: 'month',
  50. week: 'week',
  51. day: 'day'
  52. },
  53. buttonIcons: {
  54. prev: 'left-single-arrow',
  55. next: 'right-single-arrow',
  56. prevYear: 'left-double-arrow',
  57. nextYear: 'right-double-arrow'
  58. },
  59. // jquery-ui theming
  60. theme: false,
  61. themeButtonIcons: {
  62. prev: 'circle-triangle-w',
  63. next: 'circle-triangle-e',
  64. prevYear: 'seek-prev',
  65. nextYear: 'seek-next'
  66. },
  67. dragOpacity: .75,
  68. dragRevertDuration: 500,
  69. dragScroll: true,
  70. //selectable: false,
  71. unselectAuto: true,
  72. dropAccept: '*',
  73. eventLimit: false,
  74. eventLimitText: 'more',
  75. eventLimitClick: 'popover',
  76. dayPopoverFormat: 'LL',
  77. handleWindowResize: true,
  78. windowResizeDelay: 200 // milliseconds before an updateSize happens
  79. };
  80. var englishDefaults = {
  81. dayPopoverFormat: 'dddd, MMMM D'
  82. };
  83. // right-to-left defaults
  84. var rtlDefaults = {
  85. header: {
  86. left: 'next,prev today',
  87. center: '',
  88. right: 'title'
  89. },
  90. buttonIcons: {
  91. prev: 'right-single-arrow',
  92. next: 'left-single-arrow',
  93. prevYear: 'right-double-arrow',
  94. nextYear: 'left-double-arrow'
  95. },
  96. themeButtonIcons: {
  97. prev: 'circle-triangle-e',
  98. next: 'circle-triangle-w',
  99. nextYear: 'seek-prev',
  100. prevYear: 'seek-next'
  101. }
  102. };
  103. var fc = $.fullCalendar = { version: "2.2.5" };
  104. var fcViews = fc.views = {};
  105. $.fn.fullCalendar = function(options) {
  106. var args = Array.prototype.slice.call(arguments, 1); // for a possible method call
  107. var res = this; // what this function will return (this jQuery object by default)
  108. this.each(function(i, _element) { // loop each DOM element involved
  109. var element = $(_element);
  110. var calendar = element.data('fullCalendar'); // get the existing calendar object (if any)
  111. var singleRes; // the returned value of this single method call
  112. // a method call
  113. if (typeof options === 'string') {
  114. if (calendar && $.isFunction(calendar[options])) {
  115. singleRes = calendar[options].apply(calendar, args);
  116. if (!i) {
  117. res = singleRes; // record the first method call result
  118. }
  119. if (options === 'destroy') { // for the destroy method, must remove Calendar object data
  120. element.removeData('fullCalendar');
  121. }
  122. }
  123. }
  124. // a new calendar initialization
  125. else if (!calendar) { // don't initialize twice
  126. calendar = new Calendar(element, options);
  127. element.data('fullCalendar', calendar);
  128. calendar.render();
  129. }
  130. });
  131. return res;
  132. };
  133. // function for adding/overriding defaults
  134. function setDefaults(d) {
  135. mergeOptions(defaults, d);
  136. }
  137. // Recursively combines option hash-objects.
  138. // Better than `$.extend(true, ...)` because arrays are not traversed/copied.
  139. //
  140. // called like:
  141. // mergeOptions(target, obj1, obj2, ...)
  142. //
  143. function mergeOptions(target) {
  144. function mergeIntoTarget(name, value) {
  145. if ($.isPlainObject(value) && $.isPlainObject(target[name]) && !isForcedAtomicOption(name)) {
  146. // merge into a new object to avoid destruction
  147. target[name] = mergeOptions({}, target[name], value); // combine. `value` object takes precedence
  148. }
  149. else if (value !== undefined) { // only use values that are set and not undefined
  150. target[name] = value;
  151. }
  152. }
  153. for (var i=1; i<arguments.length; i++) {
  154. $.each(arguments[i], mergeIntoTarget);
  155. }
  156. return target;
  157. }
  158. // overcome sucky view-option-hash and option-merging behavior messing with options it shouldn't
  159. function isForcedAtomicOption(name) {
  160. // Any option that ends in "Time" or "Duration" is probably a Duration,
  161. // and these will commonly be specified as plain objects, which we don't want to mess up.
  162. return /(Time|Duration)$/.test(name);
  163. }
  164. // FIX: find a different solution for view-option-hashes and have a whitelist
  165. // for options that can be recursively merged.
  166. var langOptionHash = fc.langs = {}; // initialize and expose
  167. // TODO: document the structure and ordering of a FullCalendar lang file
  168. // TODO: rename everything "lang" to "locale", like what the moment project did
  169. // Initialize jQuery UI datepicker translations while using some of the translations
  170. // Will set this as the default language for datepicker.
  171. fc.datepickerLang = function(langCode, dpLangCode, dpOptions) {
  172. // get the FullCalendar internal option hash for this language. create if necessary
  173. var fcOptions = langOptionHash[langCode] || (langOptionHash[langCode] = {});
  174. // transfer some simple options from datepicker to fc
  175. fcOptions.isRTL = dpOptions.isRTL;
  176. fcOptions.weekNumberTitle = dpOptions.weekHeader;
  177. // compute some more complex options from datepicker
  178. $.each(dpComputableOptions, function(name, func) {
  179. fcOptions[name] = func(dpOptions);
  180. });
  181. // is jQuery UI Datepicker is on the page?
  182. if ($.datepicker) {
  183. // Register the language data.
  184. // FullCalendar and MomentJS use language codes like "pt-br" but Datepicker
  185. // does it like "pt-BR" or if it doesn't have the language, maybe just "pt".
  186. // Make an alias so the language can be referenced either way.
  187. $.datepicker.regional[dpLangCode] =
  188. $.datepicker.regional[langCode] = // alias
  189. dpOptions;
  190. // Alias 'en' to the default language data. Do this every time.
  191. $.datepicker.regional.en = $.datepicker.regional[''];
  192. // Set as Datepicker's global defaults.
  193. $.datepicker.setDefaults(dpOptions);
  194. }
  195. };
  196. // Sets FullCalendar-specific translations. Will set the language as the global default.
  197. fc.lang = function(langCode, newFcOptions) {
  198. var fcOptions;
  199. var momOptions;
  200. // get the FullCalendar internal option hash for this language. create if necessary
  201. fcOptions = langOptionHash[langCode] || (langOptionHash[langCode] = {});
  202. // provided new options for this language? merge them in
  203. if (newFcOptions) {
  204. mergeOptions(fcOptions, newFcOptions);
  205. }
  206. // compute language options that weren't defined.
  207. // always do this. newFcOptions can be undefined when initializing from i18n file,
  208. // so no way to tell if this is an initialization or a default-setting.
  209. momOptions = getMomentLocaleData(langCode); // will fall back to en
  210. $.each(momComputableOptions, function(name, func) {
  211. if (fcOptions[name] === undefined) {
  212. fcOptions[name] = func(momOptions, fcOptions);
  213. }
  214. });
  215. // set it as the default language for FullCalendar
  216. defaults.lang = langCode;
  217. };
  218. // NOTE: can't guarantee any of these computations will run because not every language has datepicker
  219. // configs, so make sure there are English fallbacks for these in the defaults file.
  220. var dpComputableOptions = {
  221. defaultButtonText: function(dpOptions) {
  222. return {
  223. // the translations sometimes wrongly contain HTML entities
  224. prev: stripHtmlEntities(dpOptions.prevText),
  225. next: stripHtmlEntities(dpOptions.nextText),
  226. today: stripHtmlEntities(dpOptions.currentText)
  227. };
  228. },
  229. // Produces format strings like "MMMM YYYY" -> "September 2014"
  230. monthYearFormat: function(dpOptions) {
  231. return dpOptions.showMonthAfterYear ?
  232. 'YYYY[' + dpOptions.yearSuffix + '] MMMM' :
  233. 'MMMM YYYY[' + dpOptions.yearSuffix + ']';
  234. }
  235. };
  236. var momComputableOptions = {
  237. // Produces format strings like "ddd MM/DD" -> "Fri 12/10"
  238. dayOfMonthFormat: function(momOptions, fcOptions) {
  239. var format = momOptions.longDateFormat('l'); // for the format like "M/D/YYYY"
  240. // strip the year off the edge, as well as other misc non-whitespace chars
  241. format = format.replace(/^Y+[^\w\s]*|[^\w\s]*Y+$/g, '');
  242. if (fcOptions.isRTL) {
  243. format += ' ddd'; // for RTL, add day-of-week to end
  244. }
  245. else {
  246. format = 'ddd ' + format; // for LTR, add day-of-week to beginning
  247. }
  248. return format;
  249. },
  250. // Produces format strings like "H(:mm)a" -> "6pm" or "6:30pm"
  251. smallTimeFormat: function(momOptions) {
  252. return momOptions.longDateFormat('LT')
  253. .replace(':mm', '(:mm)')
  254. .replace(/(\Wmm)$/, '($1)') // like above, but for foreign langs
  255. .replace(/\s*a$/i, 'a'); // convert AM/PM/am/pm to lowercase. remove any spaces beforehand
  256. },
  257. // Produces format strings like "H(:mm)t" -> "6p" or "6:30p"
  258. extraSmallTimeFormat: function(momOptions) {
  259. return momOptions.longDateFormat('LT')
  260. .replace(':mm', '(:mm)')
  261. .replace(/(\Wmm)$/, '($1)') // like above, but for foreign langs
  262. .replace(/\s*a$/i, 't'); // convert to AM/PM/am/pm to lowercase one-letter. remove any spaces beforehand
  263. },
  264. // Produces format strings like "H:mm" -> "6:30" (with no AM/PM)
  265. noMeridiemTimeFormat: function(momOptions) {
  266. return momOptions.longDateFormat('LT')
  267. .replace(/\s*a$/i, ''); // remove trailing AM/PM
  268. }
  269. };
  270. // Returns moment's internal locale data. If doesn't exist, returns English.
  271. // Works with moment-pre-2.8
  272. function getMomentLocaleData(langCode) {
  273. var func = moment.localeData || moment.langData;
  274. return func.call(moment, langCode) ||
  275. func.call(moment, 'en'); // the newer localData could return null, so fall back to en
  276. }
  277. // Initialize English by forcing computation of moment-derived options.
  278. // Also, sets it as the default.
  279. fc.lang('en', englishDefaults);
  280. // exports
  281. fc.intersectionToSeg = intersectionToSeg;
  282. fc.applyAll = applyAll;
  283. fc.debounce = debounce;
  284. /* FullCalendar-specific DOM Utilities
  285. ----------------------------------------------------------------------------------------------------------------------*/
  286. // Given the scrollbar widths of some other container, create borders/margins on rowEls in order to match the left
  287. // and right space that was offset by the scrollbars. A 1-pixel border first, then margin beyond that.
  288. function compensateScroll(rowEls, scrollbarWidths) {
  289. if (scrollbarWidths.left) {
  290. rowEls.css({
  291. 'border-left-width': 1,
  292. 'margin-left': scrollbarWidths.left - 1
  293. });
  294. }
  295. if (scrollbarWidths.right) {
  296. rowEls.css({
  297. 'border-right-width': 1,
  298. 'margin-right': scrollbarWidths.right - 1
  299. });
  300. }
  301. }
  302. // Undoes compensateScroll and restores all borders/margins
  303. function uncompensateScroll(rowEls) {
  304. rowEls.css({
  305. 'margin-left': '',
  306. 'margin-right': '',
  307. 'border-left-width': '',
  308. 'border-right-width': ''
  309. });
  310. }
  311. // Make the mouse cursor express that an event is not allowed in the current area
  312. function disableCursor() {
  313. $('body').addClass('fc-not-allowed');
  314. }
  315. // Returns the mouse cursor to its original look
  316. function enableCursor() {
  317. $('body').removeClass('fc-not-allowed');
  318. }
  319. // Given a total available height to fill, have `els` (essentially child rows) expand to accomodate.
  320. // By default, all elements that are shorter than the recommended height are expanded uniformly, not considering
  321. // any other els that are already too tall. if `shouldRedistribute` is on, it considers these tall rows and
  322. // reduces the available height.
  323. function distributeHeight(els, availableHeight, shouldRedistribute) {
  324. // *FLOORING NOTE*: we floor in certain places because zoom can give inaccurate floating-point dimensions,
  325. // and it is better to be shorter than taller, to avoid creating unnecessary scrollbars.
  326. var minOffset1 = Math.floor(availableHeight / els.length); // for non-last element
  327. var minOffset2 = Math.floor(availableHeight - minOffset1 * (els.length - 1)); // for last element *FLOORING NOTE*
  328. var flexEls = []; // elements that are allowed to expand. array of DOM nodes
  329. var flexOffsets = []; // amount of vertical space it takes up
  330. var flexHeights = []; // actual css height
  331. var usedHeight = 0;
  332. undistributeHeight(els); // give all elements their natural height
  333. // find elements that are below the recommended height (expandable).
  334. // important to query for heights in a single first pass (to avoid reflow oscillation).
  335. els.each(function(i, el) {
  336. var minOffset = i === els.length - 1 ? minOffset2 : minOffset1;
  337. var naturalOffset = $(el).outerHeight(true);
  338. if (naturalOffset < minOffset) {
  339. flexEls.push(el);
  340. flexOffsets.push(naturalOffset);
  341. flexHeights.push($(el).height());
  342. }
  343. else {
  344. // this element stretches past recommended height (non-expandable). mark the space as occupied.
  345. usedHeight += naturalOffset;
  346. }
  347. });
  348. // readjust the recommended height to only consider the height available to non-maxed-out rows.
  349. if (shouldRedistribute) {
  350. availableHeight -= usedHeight;
  351. minOffset1 = Math.floor(availableHeight / flexEls.length);
  352. minOffset2 = Math.floor(availableHeight - minOffset1 * (flexEls.length - 1)); // *FLOORING NOTE*
  353. }
  354. // assign heights to all expandable elements
  355. $(flexEls).each(function(i, el) {
  356. var minOffset = i === flexEls.length - 1 ? minOffset2 : minOffset1;
  357. var naturalOffset = flexOffsets[i];
  358. var naturalHeight = flexHeights[i];
  359. var newHeight = minOffset - (naturalOffset - naturalHeight); // subtract the margin/padding
  360. if (naturalOffset < minOffset) { // we check this again because redistribution might have changed things
  361. $(el).height(newHeight);
  362. }
  363. });
  364. }
  365. // Undoes distrubuteHeight, restoring all els to their natural height
  366. function undistributeHeight(els) {
  367. els.height('');
  368. }
  369. // Given `els`, a jQuery set of <td> cells, find the cell with the largest natural width and set the widths of all the
  370. // cells to be that width.
  371. // PREREQUISITE: if you want a cell to take up width, it needs to have a single inner element w/ display:inline
  372. function matchCellWidths(els) {
  373. var maxInnerWidth = 0;
  374. els.find('> *').each(function(i, innerEl) {
  375. var innerWidth = $(innerEl).outerWidth();
  376. if (innerWidth > maxInnerWidth) {
  377. maxInnerWidth = innerWidth;
  378. }
  379. });
  380. maxInnerWidth++; // sometimes not accurate of width the text needs to stay on one line. insurance
  381. els.width(maxInnerWidth);
  382. return maxInnerWidth;
  383. }
  384. // Turns a container element into a scroller if its contents is taller than the allotted height.
  385. // Returns true if the element is now a scroller, false otherwise.
  386. // NOTE: this method is best because it takes weird zooming dimensions into account
  387. function setPotentialScroller(containerEl, height) {
  388. containerEl.height(height).addClass('fc-scroller');
  389. // are scrollbars needed?
  390. if (containerEl[0].scrollHeight - 1 > containerEl[0].clientHeight) { // !!! -1 because IE is often off-by-one :(
  391. return true;
  392. }
  393. unsetScroller(containerEl); // undo
  394. return false;
  395. }
  396. // Takes an element that might have been a scroller, and turns it back into a normal element.
  397. function unsetScroller(containerEl) {
  398. containerEl.height('').removeClass('fc-scroller');
  399. }
  400. /* General DOM Utilities
  401. ----------------------------------------------------------------------------------------------------------------------*/
  402. // borrowed from https://github.com/jquery/jquery-ui/blob/1.11.0/ui/core.js#L51
  403. function getScrollParent(el) {
  404. var position = el.css('position'),
  405. scrollParent = el.parents().filter(function() {
  406. var parent = $(this);
  407. return (/(auto|scroll)/).test(
  408. parent.css('overflow') + parent.css('overflow-y') + parent.css('overflow-x')
  409. );
  410. }).eq(0);
  411. return position === 'fixed' || !scrollParent.length ? $(el[0].ownerDocument || document) : scrollParent;
  412. }
  413. // Given a container element, return an object with the pixel values of the left/right scrollbars.
  414. // Left scrollbars might occur on RTL browsers (IE maybe?) but I have not tested.
  415. // PREREQUISITE: container element must have a single child with display:block
  416. function getScrollbarWidths(container) {
  417. var containerLeft = container.offset().left;
  418. var containerRight = containerLeft + container.width();
  419. var inner = container.children();
  420. var innerLeft = inner.offset().left;
  421. var innerRight = innerLeft + inner.outerWidth();
  422. return {
  423. left: innerLeft - containerLeft,
  424. right: containerRight - innerRight
  425. };
  426. }
  427. // Returns a boolean whether this was a left mouse click and no ctrl key (which means right click on Mac)
  428. function isPrimaryMouseButton(ev) {
  429. return ev.which == 1 && !ev.ctrlKey;
  430. }
  431. /* FullCalendar-specific Misc Utilities
  432. ----------------------------------------------------------------------------------------------------------------------*/
  433. // Creates a basic segment with the intersection of the two ranges. Returns undefined if no intersection.
  434. // Expects all dates to be normalized to the same timezone beforehand.
  435. // TODO: move to date section?
  436. function intersectionToSeg(subjectRange, constraintRange) {
  437. var subjectStart = subjectRange.start;
  438. var subjectEnd = subjectRange.end;
  439. var constraintStart = constraintRange.start;
  440. var constraintEnd = constraintRange.end;
  441. var segStart, segEnd;
  442. var isStart, isEnd;
  443. if (subjectEnd > constraintStart && subjectStart < constraintEnd) { // in bounds at all?
  444. if (subjectStart >= constraintStart) {
  445. segStart = subjectStart.clone();
  446. isStart = true;
  447. }
  448. else {
  449. segStart = constraintStart.clone();
  450. isStart = false;
  451. }
  452. if (subjectEnd <= constraintEnd) {
  453. segEnd = subjectEnd.clone();
  454. isEnd = true;
  455. }
  456. else {
  457. segEnd = constraintEnd.clone();
  458. isEnd = false;
  459. }
  460. return {
  461. start: segStart,
  462. end: segEnd,
  463. isStart: isStart,
  464. isEnd: isEnd
  465. };
  466. }
  467. }
  468. function smartProperty(obj, name) { // get a camel-cased/namespaced property of an object
  469. obj = obj || {};
  470. if (obj[name] !== undefined) {
  471. return obj[name];
  472. }
  473. var parts = name.split(/(?=[A-Z])/),
  474. i = parts.length - 1, res;
  475. for (; i>=0; i--) {
  476. res = obj[parts[i].toLowerCase()];
  477. if (res !== undefined) {
  478. return res;
  479. }
  480. }
  481. return obj['default'];
  482. }
  483. /* Date Utilities
  484. ----------------------------------------------------------------------------------------------------------------------*/
  485. var dayIDs = [ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ];
  486. var intervalUnits = [ 'year', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond' ];
  487. // Diffs the two moments into a Duration where full-days are recorded first, then the remaining time.
  488. // Moments will have their timezones normalized.
  489. function diffDayTime(a, b) {
  490. return moment.duration({
  491. days: a.clone().stripTime().diff(b.clone().stripTime(), 'days'),
  492. ms: a.time() - b.time() // time-of-day from day start. disregards timezone
  493. });
  494. }
  495. // Diffs the two moments via their start-of-day (regardless of timezone). Produces whole-day durations.
  496. function diffDay(a, b) {
  497. return moment.duration({
  498. days: a.clone().stripTime().diff(b.clone().stripTime(), 'days')
  499. });
  500. }
  501. // Computes the larges whole-unit period of time, as a duration object.
  502. // For example, 48 hours will be {days:2} whereas 49 hours will be {hours:49}.
  503. // Accepts start/end, a range object, or an original duration object.
  504. /* (never used)
  505. function computeIntervalDuration(start, end) {
  506. var durationInput = {};
  507. var i, unit;
  508. var val;
  509. for (i = 0; i < intervalUnits.length; i++) {
  510. unit = intervalUnits[i];
  511. val = computeIntervalAs(unit, start, end);
  512. if (val) {
  513. break;
  514. }
  515. }
  516. durationInput[unit] = val;
  517. return moment.duration(durationInput);
  518. }
  519. */
  520. // Computes the unit name of the largest whole-unit period of time.
  521. // For example, 48 hours will be "days" wherewas 49 hours will be "hours".
  522. // Accepts start/end, a range object, or an original duration object.
  523. function computeIntervalUnit(start, end) {
  524. var i, unit;
  525. for (i = 0; i < intervalUnits.length; i++) {
  526. unit = intervalUnits[i];
  527. if (computeIntervalAs(unit, start, end)) {
  528. break;
  529. }
  530. }
  531. return unit; // will be "milliseconds" if nothing else matches
  532. }
  533. // Computes the number of units the interval is cleanly comprised of.
  534. // If the given unit does not cleanly divide the interval a whole number of times, `false` is returned.
  535. // Accepts start/end, a range object, or an original duration object.
  536. function computeIntervalAs(unit, start, end) {
  537. var val;
  538. if (end != null) { // given start, end
  539. val = end.diff(start, unit, true);
  540. }
  541. else if (moment.isDuration(start)) { // given duration
  542. val = start.as(unit);
  543. }
  544. else { // given { start, end } range object
  545. val = start.end.diff(start.start, unit, true);
  546. }
  547. if (val >= 1 && isInt(val)) {
  548. return val;
  549. }
  550. return false;
  551. }
  552. function isNativeDate(input) {
  553. return Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date;
  554. }
  555. // Returns a boolean about whether the given input is a time string, like "06:40:00" or "06:00"
  556. function isTimeString(str) {
  557. return /^\d+\:\d+(?:\:\d+\.?(?:\d{3})?)?$/.test(str);
  558. }
  559. /* General Utilities
  560. ----------------------------------------------------------------------------------------------------------------------*/
  561. var hasOwnPropMethod = {}.hasOwnProperty;
  562. // Create an object that has the given prototype. Just like Object.create
  563. function createObject(proto) {
  564. var f = function() {};
  565. f.prototype = proto;
  566. return new f();
  567. }
  568. function copyOwnProps(src, dest) {
  569. for (var name in src) {
  570. if (hasOwnProp(src, name)) {
  571. dest[name] = src[name];
  572. }
  573. }
  574. }
  575. function hasOwnProp(obj, name) {
  576. return hasOwnPropMethod.call(obj, name);
  577. }
  578. // Is the given value a non-object non-function value?
  579. function isAtomic(val) {
  580. return /undefined|null|boolean|number|string/.test($.type(val));
  581. }
  582. function applyAll(functions, thisObj, args) {
  583. if ($.isFunction(functions)) {
  584. functions = [ functions ];
  585. }
  586. if (functions) {
  587. var i;
  588. var ret;
  589. for (i=0; i<functions.length; i++) {
  590. ret = functions[i].apply(thisObj, args) || ret;
  591. }
  592. return ret;
  593. }
  594. }
  595. function firstDefined() {
  596. for (var i=0; i<arguments.length; i++) {
  597. if (arguments[i] !== undefined) {
  598. return arguments[i];
  599. }
  600. }
  601. }
  602. function htmlEscape(s) {
  603. return (s + '').replace(/&/g, '&amp;')
  604. .replace(/</g, '&lt;')
  605. .replace(/>/g, '&gt;')
  606. .replace(/'/g, '&#039;')
  607. .replace(/"/g, '&quot;')
  608. .replace(/\n/g, '<br />');
  609. }
  610. function stripHtmlEntities(text) {
  611. return text.replace(/&.*?;/g, '');
  612. }
  613. function capitaliseFirstLetter(str) {
  614. return str.charAt(0).toUpperCase() + str.slice(1);
  615. }
  616. function compareNumbers(a, b) { // for .sort()
  617. return a - b;
  618. }
  619. function isInt(n) {
  620. return n % 1 === 0;
  621. }
  622. // Returns a function, that, as long as it continues to be invoked, will not
  623. // be triggered. The function will be called after it stops being called for
  624. // N milliseconds.
  625. // https://github.com/jashkenas/underscore/blob/1.6.0/underscore.js#L714
  626. function debounce(func, wait) {
  627. var timeoutId;
  628. var args;
  629. var context;
  630. var timestamp; // of most recent call
  631. var later = function() {
  632. var last = +new Date() - timestamp;
  633. if (last < wait && last > 0) {
  634. timeoutId = setTimeout(later, wait - last);
  635. }
  636. else {
  637. timeoutId = null;
  638. func.apply(context, args);
  639. if (!timeoutId) {
  640. context = args = null;
  641. }
  642. }
  643. };
  644. return function() {
  645. context = this;
  646. args = arguments;
  647. timestamp = +new Date();
  648. if (!timeoutId) {
  649. timeoutId = setTimeout(later, wait);
  650. }
  651. };
  652. }
  653. var ambigDateOfMonthRegex = /^\s*\d{4}-\d\d$/;
  654. var ambigTimeOrZoneRegex =
  655. /^\s*\d{4}-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?)?$/;
  656. var newMomentProto = moment.fn; // where we will attach our new methods
  657. var oldMomentProto = $.extend({}, newMomentProto); // copy of original moment methods
  658. var allowValueOptimization;
  659. var setUTCValues; // function defined below
  660. var setLocalValues; // function defined below
  661. // Creating
  662. // -------------------------------------------------------------------------------------------------
  663. // Creates a new moment, similar to the vanilla moment(...) constructor, but with
  664. // extra features (ambiguous time, enhanced formatting). When given an existing moment,
  665. // it will function as a clone (and retain the zone of the moment). Anything else will
  666. // result in a moment in the local zone.
  667. fc.moment = function() {
  668. return makeMoment(arguments);
  669. };
  670. // Sames as fc.moment, but forces the resulting moment to be in the UTC timezone.
  671. fc.moment.utc = function() {
  672. var mom = makeMoment(arguments, true);
  673. // Force it into UTC because makeMoment doesn't guarantee it
  674. // (if given a pre-existing moment for example)
  675. if (mom.hasTime()) { // don't give ambiguously-timed moments a UTC zone
  676. mom.utc();
  677. }
  678. return mom;
  679. };
  680. // Same as fc.moment, but when given an ISO8601 string, the timezone offset is preserved.
  681. // ISO8601 strings with no timezone offset will become ambiguously zoned.
  682. fc.moment.parseZone = function() {
  683. return makeMoment(arguments, true, true);
  684. };
  685. // Builds an enhanced moment from args. When given an existing moment, it clones. When given a
  686. // native Date, or called with no arguments (the current time), the resulting moment will be local.
  687. // Anything else needs to be "parsed" (a string or an array), and will be affected by:
  688. // parseAsUTC - if there is no zone information, should we parse the input in UTC?
  689. // parseZone - if there is zone information, should we force the zone of the moment?
  690. function makeMoment(args, parseAsUTC, parseZone) {
  691. var input = args[0];
  692. var isSingleString = args.length == 1 && typeof input === 'string';
  693. var isAmbigTime;
  694. var isAmbigZone;
  695. var ambigMatch;
  696. var mom;
  697. if (moment.isMoment(input)) {
  698. mom = moment.apply(null, args); // clone it
  699. transferAmbigs(input, mom); // the ambig flags weren't transfered with the clone
  700. }
  701. else if (isNativeDate(input) || input === undefined) {
  702. mom = moment.apply(null, args); // will be local
  703. }
  704. else { // "parsing" is required
  705. isAmbigTime = false;
  706. isAmbigZone = false;
  707. if (isSingleString) {
  708. if (ambigDateOfMonthRegex.test(input)) {
  709. // accept strings like '2014-05', but convert to the first of the month
  710. input += '-01';
  711. args = [ input ]; // for when we pass it on to moment's constructor
  712. isAmbigTime = true;
  713. isAmbigZone = true;
  714. }
  715. else if ((ambigMatch = ambigTimeOrZoneRegex.exec(input))) {
  716. isAmbigTime = !ambigMatch[5]; // no time part?
  717. isAmbigZone = true;
  718. }
  719. }
  720. else if ($.isArray(input)) {
  721. // arrays have no timezone information, so assume ambiguous zone
  722. isAmbigZone = true;
  723. }
  724. // otherwise, probably a string with a format
  725. if (parseAsUTC || isAmbigTime) {
  726. mom = moment.utc.apply(moment, args);
  727. }
  728. else {
  729. mom = moment.apply(null, args);
  730. }
  731. if (isAmbigTime) {
  732. mom._ambigTime = true;
  733. mom._ambigZone = true; // ambiguous time always means ambiguous zone
  734. }
  735. else if (parseZone) { // let's record the inputted zone somehow
  736. if (isAmbigZone) {
  737. mom._ambigZone = true;
  738. }
  739. else if (isSingleString) {
  740. mom.zone(input); // if not a valid zone, will assign UTC
  741. }
  742. }
  743. }
  744. mom._fullCalendar = true; // flag for extended functionality
  745. return mom;
  746. }
  747. // A clone method that works with the flags related to our enhanced functionality.
  748. // In the future, use moment.momentProperties
  749. newMomentProto.clone = function() {
  750. var mom = oldMomentProto.clone.apply(this, arguments);
  751. // these flags weren't transfered with the clone
  752. transferAmbigs(this, mom);
  753. if (this._fullCalendar) {
  754. mom._fullCalendar = true;
  755. }
  756. return mom;
  757. };
  758. // Time-of-day
  759. // -------------------------------------------------------------------------------------------------
  760. // GETTER
  761. // Returns a Duration with the hours/minutes/seconds/ms values of the moment.
  762. // If the moment has an ambiguous time, a duration of 00:00 will be returned.
  763. //
  764. // SETTER
  765. // You can supply a Duration, a Moment, or a Duration-like argument.
  766. // When setting the time, and the moment has an ambiguous time, it then becomes unambiguous.
  767. newMomentProto.time = function(time) {
  768. // Fallback to the original method (if there is one) if this moment wasn't created via FullCalendar.
  769. // `time` is a generic enough method name where this precaution is necessary to avoid collisions w/ other plugins.
  770. if (!this._fullCalendar) {
  771. return oldMomentProto.time.apply(this, arguments);
  772. }
  773. if (time == null) { // getter
  774. return moment.duration({
  775. hours: this.hours(),
  776. minutes: this.minutes(),
  777. seconds: this.seconds(),
  778. milliseconds: this.milliseconds()
  779. });
  780. }
  781. else { // setter
  782. this._ambigTime = false; // mark that the moment now has a time
  783. if (!moment.isDuration(time) && !moment.isMoment(time)) {
  784. time = moment.duration(time);
  785. }
  786. // The day value should cause overflow (so 24 hours becomes 00:00:00 of next day).
  787. // Only for Duration times, not Moment times.
  788. var dayHours = 0;
  789. if (moment.isDuration(time)) {
  790. dayHours = Math.floor(time.asDays()) * 24;
  791. }
  792. // We need to set the individual fields.
  793. // Can't use startOf('day') then add duration. In case of DST at start of day.
  794. return this.hours(dayHours + time.hours())
  795. .minutes(time.minutes())
  796. .seconds(time.seconds())
  797. .milliseconds(time.milliseconds());
  798. }
  799. };
  800. // Converts the moment to UTC, stripping out its time-of-day and timezone offset,
  801. // but preserving its YMD. A moment with a stripped time will display no time
  802. // nor timezone offset when .format() is called.
  803. newMomentProto.stripTime = function() {
  804. var a;
  805. if (!this._ambigTime) {
  806. // get the values before any conversion happens
  807. a = this.toArray(); // array of y/m/d/h/m/s/ms
  808. this.utc(); // set the internal UTC flag (will clear the ambig flags)
  809. setUTCValues(this, a.slice(0, 3)); // set the year/month/date. time will be zero
  810. // Mark the time as ambiguous. This needs to happen after the .utc() call, which calls .zone(),
  811. // which clears all ambig flags. Same with setUTCValues with moment-timezone.
  812. this._ambigTime = true;
  813. this._ambigZone = true; // if ambiguous time, also ambiguous timezone offset
  814. }
  815. return this; // for chaining
  816. };
  817. // Returns if the moment has a non-ambiguous time (boolean)
  818. newMomentProto.hasTime = function() {
  819. return !this._ambigTime;
  820. };
  821. // Timezone
  822. // -------------------------------------------------------------------------------------------------
  823. // Converts the moment to UTC, stripping out its timezone offset, but preserving its
  824. // YMD and time-of-day. A moment with a stripped timezone offset will display no
  825. // timezone offset when .format() is called.
  826. newMomentProto.stripZone = function() {
  827. var a, wasAmbigTime;
  828. if (!this._ambigZone) {
  829. // get the values before any conversion happens
  830. a = this.toArray(); // array of y/m/d/h/m/s/ms
  831. wasAmbigTime = this._ambigTime;
  832. this.utc(); // set the internal UTC flag (will clear the ambig flags)
  833. setUTCValues(this, a); // will set the year/month/date/hours/minutes/seconds/ms
  834. if (wasAmbigTime) {
  835. // the above call to .utc()/.zone() unfortunately clears the ambig flags, so reassign
  836. this._ambigTime = true;
  837. }
  838. // Mark the zone as ambiguous. This needs to happen after the .utc() call, which calls .zone(),
  839. // which clears all ambig flags. Same with setUTCValues with moment-timezone.
  840. this._ambigZone = true;
  841. }
  842. return this; // for chaining
  843. };
  844. // Returns of the moment has a non-ambiguous timezone offset (boolean)
  845. newMomentProto.hasZone = function() {
  846. return !this._ambigZone;
  847. };
  848. // this method implicitly marks a zone (will get called upon .utc() and .local())
  849. newMomentProto.zone = function(tzo) {
  850. if (tzo != null) { // setter
  851. // these assignments needs to happen before the original zone method is called.
  852. // I forget why, something to do with a browser crash.
  853. this._ambigTime = false;
  854. this._ambigZone = false;
  855. }
  856. return oldMomentProto.zone.apply(this, arguments);
  857. };
  858. // this method implicitly marks a zone
  859. newMomentProto.local = function() {
  860. var a = this.toArray(); // year,month,date,hours,minutes,seconds,ms as an array
  861. var wasAmbigZone = this._ambigZone;
  862. oldMomentProto.local.apply(this, arguments); // will clear ambig flags
  863. if (wasAmbigZone) {
  864. // If the moment was ambiguously zoned, the date fields were stored as UTC.
  865. // We want to preserve these, but in local time.
  866. setLocalValues(this, a);
  867. }
  868. return this; // for chaining
  869. };
  870. // Formatting
  871. // -------------------------------------------------------------------------------------------------
  872. newMomentProto.format = function() {
  873. if (this._fullCalendar && arguments[0]) { // an enhanced moment? and a format string provided?
  874. return formatDate(this, arguments[0]); // our extended formatting
  875. }
  876. if (this._ambigTime) {
  877. return oldMomentFormat(this, 'YYYY-MM-DD');
  878. }
  879. if (this._ambigZone) {
  880. return oldMomentFormat(this, 'YYYY-MM-DD[T]HH:mm:ss');
  881. }
  882. return oldMomentProto.format.apply(this, arguments);
  883. };
  884. newMomentProto.toISOString = function() {
  885. if (this._ambigTime) {
  886. return oldMomentFormat(this, 'YYYY-MM-DD');
  887. }
  888. if (this._ambigZone) {
  889. return oldMomentFormat(this, 'YYYY-MM-DD[T]HH:mm:ss');
  890. }
  891. return oldMomentProto.toISOString.apply(this, arguments);
  892. };
  893. // Querying
  894. // -------------------------------------------------------------------------------------------------
  895. // Is the moment within the specified range? `end` is exclusive.
  896. // FYI, this method is not a standard Moment method, so always do our enhanced logic.
  897. newMomentProto.isWithin = function(start, end) {
  898. var a = commonlyAmbiguate([ this, start, end ]);
  899. return a[0] >= a[1] && a[0] < a[2];
  900. };
  901. // When isSame is called with units, timezone ambiguity is normalized before the comparison happens.
  902. // If no units specified, the two moments must be identically the same, with matching ambig flags.
  903. newMomentProto.isSame = function(input, units) {
  904. var a;
  905. // only do custom logic if this is an enhanced moment
  906. if (!this._fullCalendar) {
  907. return oldMomentProto.isSame.apply(this, arguments);
  908. }
  909. if (units) {
  910. a = commonlyAmbiguate([ this, input ], true); // normalize timezones but don't erase times
  911. return oldMomentProto.isSame.call(a[0], a[1], units);
  912. }
  913. else {
  914. input = fc.moment.parseZone(input); // normalize input
  915. return oldMomentProto.isSame.call(this, input) &&
  916. Boolean(this._ambigTime) === Boolean(input._ambigTime) &&
  917. Boolean(this._ambigZone) === Boolean(input._ambigZone);
  918. }
  919. };
  920. // Make these query methods work with ambiguous moments
  921. $.each([
  922. 'isBefore',
  923. 'isAfter'
  924. ], function(i, methodName) {
  925. newMomentProto[methodName] = function(input, units) {
  926. var a;
  927. // only do custom logic if this is an enhanced moment
  928. if (!this._fullCalendar) {
  929. return oldMomentProto[methodName].apply(this, arguments);
  930. }
  931. a = commonlyAmbiguate([ this, input ]);
  932. return oldMomentProto[methodName].call(a[0], a[1], units);
  933. };
  934. });
  935. // Misc Internals
  936. // -------------------------------------------------------------------------------------------------
  937. // given an array of moment-like inputs, return a parallel array w/ moments similarly ambiguated.
  938. // for example, of one moment has ambig time, but not others, all moments will have their time stripped.
  939. // set `preserveTime` to `true` to keep times, but only normalize zone ambiguity.
  940. // returns the original moments if no modifications are necessary.
  941. function commonlyAmbiguate(inputs, preserveTime) {
  942. var anyAmbigTime = false;
  943. var anyAmbigZone = false;
  944. var len = inputs.length;
  945. var moms = [];
  946. var i, mom;
  947. // parse inputs into real moments and query their ambig flags
  948. for (i = 0; i < len; i++) {
  949. mom = inputs[i];
  950. if (!moment.isMoment(mom)) {
  951. mom = fc.moment.parseZone(mom);
  952. }
  953. anyAmbigTime = anyAmbigTime || mom._ambigTime;
  954. anyAmbigZone = anyAmbigZone || mom._ambigZone;
  955. moms.push(mom);
  956. }
  957. // strip each moment down to lowest common ambiguity
  958. // use clones to avoid modifying the original moments
  959. for (i = 0; i < len; i++) {
  960. mom = moms[i];
  961. if (!preserveTime && anyAmbigTime && !mom._ambigTime) {
  962. moms[i] = mom.clone().stripTime();
  963. }
  964. else if (anyAmbigZone && !mom._ambigZone) {
  965. moms[i] = mom.clone().stripZone();
  966. }
  967. }
  968. return moms;
  969. }
  970. // Transfers all the flags related to ambiguous time/zone from the `src` moment to the `dest` moment
  971. function transferAmbigs(src, dest) {
  972. if (src._ambigTime) {
  973. dest._ambigTime = true;
  974. }
  975. else if (dest._ambigTime) {
  976. dest._ambigTime = false;
  977. }
  978. if (src._ambigZone) {
  979. dest._ambigZone = true;
  980. }
  981. else if (dest._ambigZone) {
  982. dest._ambigZone = false;
  983. }
  984. }
  985. // Sets the year/month/date/etc values of the moment from the given array.
  986. // Inefficient because it calls each individual setter.
  987. function setMomentValues(mom, a) {
  988. mom.year(a[0] || 0)
  989. .month(a[1] || 0)
  990. .date(a[2] || 0)
  991. .hours(a[3] || 0)
  992. .minutes(a[4] || 0)
  993. .seconds(a[5] || 0)
  994. .milliseconds(a[6] || 0);
  995. }
  996. // Can we set the moment's internal date directly?
  997. allowValueOptimization = '_d' in moment() && 'updateOffset' in moment;
  998. // Utility function. Accepts a moment and an array of the UTC year/month/date/etc values to set.
  999. // Assumes the given moment is already in UTC mode.
  1000. setUTCValues = allowValueOptimization ? function(mom, a) {
  1001. // simlate what moment's accessors do
  1002. mom._d.setTime(Date.UTC.apply(Date, a));
  1003. moment.updateOffset(mom, false); // keepTime=false
  1004. } : setMomentValues;
  1005. // Utility function. Accepts a moment and an array of the local year/month/date/etc values to set.
  1006. // Assumes the given moment is already in local mode.
  1007. setLocalValues = allowValueOptimization ? function(mom, a) {
  1008. // simlate what moment's accessors do
  1009. mom._d.setTime(+new Date( // FYI, there is now way to apply an array of args to a constructor
  1010. a[0] || 0,
  1011. a[1] || 0,
  1012. a[2] || 0,
  1013. a[3] || 0,
  1014. a[4] || 0,
  1015. a[5] || 0,
  1016. a[6] || 0
  1017. ));
  1018. moment.updateOffset(mom, false); // keepTime=false
  1019. } : setMomentValues;
  1020. // Single Date Formatting
  1021. // -------------------------------------------------------------------------------------------------
  1022. // call this if you want Moment's original format method to be used
  1023. function oldMomentFormat(mom, formatStr) {
  1024. return oldMomentProto.format.call(mom, formatStr); // oldMomentProto defined in moment-ext.js
  1025. }
  1026. // Formats `date` with a Moment formatting string, but allow our non-zero areas and
  1027. // additional token.
  1028. function formatDate(date, formatStr) {
  1029. return formatDateWithChunks(date, getFormatStringChunks(formatStr));
  1030. }
  1031. function formatDateWithChunks(date, chunks) {
  1032. var s = '';
  1033. var i;
  1034. for (i=0; i<chunks.length; i++) {
  1035. s += formatDateWithChunk(date, chunks[i]);
  1036. }
  1037. return s;
  1038. }
  1039. // addition formatting tokens we want recognized
  1040. var tokenOverrides = {
  1041. t: function(date) { // "a" or "p"
  1042. return oldMomentFormat(date, 'a').charAt(0);
  1043. },
  1044. T: function(date) { // "A" or "P"
  1045. return oldMomentFormat(date, 'A').charAt(0);
  1046. }
  1047. };
  1048. function formatDateWithChunk(date, chunk) {
  1049. var token;
  1050. var maybeStr;
  1051. if (typeof chunk === 'string') { // a literal string
  1052. return chunk;
  1053. }
  1054. else if ((token = chunk.token)) { // a token, like "YYYY"
  1055. if (tokenOverrides[token]) {
  1056. return tokenOverrides[token](date); // use our custom token
  1057. }
  1058. return oldMomentFormat(date, token);
  1059. }
  1060. else if (chunk.maybe) { // a grouping of other chunks that must be non-zero
  1061. maybeStr = formatDateWithChunks(date, chunk.maybe);
  1062. if (maybeStr.match(/[1-9]/)) {
  1063. return maybeStr;
  1064. }
  1065. }
  1066. return '';
  1067. }
  1068. // Date Range Formatting
  1069. // -------------------------------------------------------------------------------------------------
  1070. // TODO: make it work with timezone offset
  1071. // Using a formatting string meant for a single date, generate a range string, like
  1072. // "Sep 2 - 9 2013", that intelligently inserts a separator where the dates differ.
  1073. // If the dates are the same as far as the format string is concerned, just return a single
  1074. // rendering of one date, without any separator.
  1075. function formatRange(date1, date2, formatStr, separator, isRTL) {
  1076. var localeData;
  1077. date1 = fc.moment.parseZone(date1);
  1078. date2 = fc.moment.parseZone(date2);
  1079. localeData = (date1.localeData || date1.lang).call(date1); // works with moment-pre-2.8
  1080. // Expand localized format strings, like "LL" -> "MMMM D YYYY"
  1081. formatStr = localeData.longDateFormat(formatStr) || formatStr;
  1082. // BTW, this is not important for `formatDate` because it is impossible to put custom tokens
  1083. // or non-zero areas in Moment's localized format strings.
  1084. separator = separator || ' - ';
  1085. return formatRangeWithChunks(
  1086. date1,
  1087. date2,
  1088. getFormatStringChunks(formatStr),
  1089. separator,
  1090. isRTL
  1091. );
  1092. }
  1093. fc.formatRange = formatRange; // expose
  1094. function formatRangeWithChunks(date1, date2, chunks, separator, isRTL) {
  1095. var chunkStr; // the rendering of the chunk
  1096. var leftI;
  1097. var leftStr = '';
  1098. var rightI;
  1099. var rightStr = '';
  1100. var middleI;
  1101. var middleStr1 = '';
  1102. var middleStr2 = '';
  1103. var middleStr = '';
  1104. // Start at the leftmost side of the formatting string and continue until you hit a token
  1105. // that is not the same between dates.
  1106. for (leftI=0; leftI<chunks.length; leftI++) {
  1107. chunkStr = formatSimilarChunk(date1, date2, chunks[leftI]);
  1108. if (chunkStr === false) {
  1109. break;
  1110. }
  1111. leftStr += chunkStr;
  1112. }
  1113. // Similarly, start at the rightmost side of the formatting string and move left
  1114. for (rightI=chunks.length-1; rightI>leftI; rightI--) {
  1115. chunkStr = formatSimilarChunk(date1, date2, chunks[rightI]);
  1116. if (chunkStr === false) {
  1117. break;
  1118. }
  1119. rightStr = chunkStr + rightStr;
  1120. }
  1121. // The area in the middle is different for both of the dates.
  1122. // Collect them distinctly so we can jam them together later.
  1123. for (middleI=leftI; middleI<=rightI; middleI++) {
  1124. middleStr1 += formatDateWithChunk(date1, chunks[middleI]);
  1125. middleStr2 += formatDateWithChunk(date2, chunks[middleI]);
  1126. }
  1127. if (middleStr1 || middleStr2) {
  1128. if (isRTL) {
  1129. middleStr = middleStr2 + separator + middleStr1;
  1130. }
  1131. else {
  1132. middleStr = middleStr1 + separator + middleStr2;
  1133. }
  1134. }
  1135. return leftStr + middleStr + rightStr;
  1136. }
  1137. var similarUnitMap = {
  1138. Y: 'year',
  1139. M: 'month',
  1140. D: 'day', // day of month
  1141. d: 'day', // day of week
  1142. // prevents a separator between anything time-related...
  1143. A: 'second', // AM/PM
  1144. a: 'second', // am/pm
  1145. T: 'second', // A/P
  1146. t: 'second', // a/p
  1147. H: 'second', // hour (24)
  1148. h: 'second', // hour (12)
  1149. m: 'second', // minute
  1150. s: 'second' // second
  1151. };
  1152. // TODO: week maybe?
  1153. // Given a formatting chunk, and given that both dates are similar in the regard the
  1154. // formatting chunk is concerned, format date1 against `chunk`. Otherwise, return `false`.
  1155. function formatSimilarChunk(date1, date2, chunk) {
  1156. var token;
  1157. var unit;
  1158. if (typeof chunk === 'string') { // a literal string
  1159. return chunk;
  1160. }
  1161. else if ((token = chunk.token)) {
  1162. unit = similarUnitMap[token.charAt(0)];
  1163. // are the dates the same for this unit of measurement?
  1164. if (unit && date1.isSame(date2, unit)) {
  1165. return oldMomentFormat(date1, token); // would be the same if we used `date2`
  1166. // BTW, don't support custom tokens
  1167. }
  1168. }
  1169. return false; // the chunk is NOT the same for the two dates
  1170. // BTW, don't support splitting on non-zero areas
  1171. }
  1172. // Chunking Utils
  1173. // -------------------------------------------------------------------------------------------------
  1174. var formatStringChunkCache = {};
  1175. function getFormatStringChunks(formatStr) {
  1176. if (formatStr in formatStringChunkCache) {
  1177. return formatStringChunkCache[formatStr];
  1178. }
  1179. return (formatStringChunkCache[formatStr] = chunkFormatString(formatStr));
  1180. }
  1181. // Break the formatting string into an array of chunks
  1182. function chunkFormatString(formatStr) {
  1183. var chunks = [];
  1184. var chunker = /\[([^\]]*)\]|\(([^\)]*)\)|(LT|(\w)\4*o?)|([^\w\[\(]+)/g; // TODO: more descrimination
  1185. var match;
  1186. while ((match = chunker.exec(formatStr))) {
  1187. if (match[1]) { // a literal string inside [ ... ]
  1188. chunks.push(match[1]);
  1189. }
  1190. else if (match[2]) { // non-zero formatting inside ( ... )
  1191. chunks.push({ maybe: chunkFormatString(match[2]) });
  1192. }
  1193. else if (match[3]) { // a formatting token
  1194. chunks.push({ token: match[3] });
  1195. }
  1196. else if (match[5]) { // an unenclosed literal string
  1197. chunks.push(match[5]);
  1198. }
  1199. }
  1200. return chunks;
  1201. }
  1202. fc.Class = Class; // export
  1203. // class that all other classes will inherit from
  1204. function Class() { }
  1205. // called upon a class to create a subclass
  1206. Class.extend = function(members) {
  1207. var superClass = this;
  1208. var subClass;
  1209. members = members || {};
  1210. // ensure a constructor for the subclass, forwarding all arguments to the super-constructor if it doesn't exist
  1211. if (hasOwnProp(members, 'constructor')) {
  1212. subClass = members.constructor;
  1213. }
  1214. if (typeof subClass !== 'function') {
  1215. subClass = members.constructor = function() {
  1216. superClass.apply(this, arguments);
  1217. };
  1218. }
  1219. // build the base prototype for the subclass, which is an new object chained to the superclass's prototype
  1220. subClass.prototype = createObject(superClass.prototype);
  1221. // copy each member variable/method onto the the subclass's prototype
  1222. copyOwnProps(members, subClass.prototype);
  1223. // copy over all class variables/methods to the subclass, such as `extend` and `mixin`
  1224. copyOwnProps(superClass, subClass);
  1225. return subClass;
  1226. };
  1227. // adds new member variables/methods to the class's prototype.
  1228. // can be called with another class, or a plain object hash containing new members.
  1229. Class.mixin = function(members) {
  1230. copyOwnProps(members.prototype || members, this.prototype);
  1231. };
  1232. /* A rectangular panel that is absolutely positioned over other content
  1233. ------------------------------------------------------------------------------------------------------------------------
  1234. Options:
  1235. - className (string)
  1236. - content (HTML string or jQuery element set)
  1237. - parentEl
  1238. - top
  1239. - left
  1240. - right (the x coord of where the right edge should be. not a "CSS" right)
  1241. - autoHide (boolean)
  1242. - show (callback)
  1243. - hide (callback)
  1244. */
  1245. var Popover = Class.extend({
  1246. isHidden: true,
  1247. options: null,
  1248. el: null, // the container element for the popover. generated by this object
  1249. documentMousedownProxy: null, // document mousedown handler bound to `this`
  1250. margin: 10, // the space required between the popover and the edges of the scroll container
  1251. constructor: function(options) {
  1252. this.options = options || {};
  1253. },
  1254. // Shows the popover on the specified position. Renders it if not already
  1255. show: function() {
  1256. if (this.isHidden) {
  1257. if (!this.el) {
  1258. this.render();
  1259. }
  1260. this.el.show();
  1261. this.position();
  1262. this.isHidden = false;
  1263. this.trigger('show');
  1264. }
  1265. },
  1266. // Hides the popover, through CSS, but does not remove it from the DOM
  1267. hide: function() {
  1268. if (!this.isHidden) {
  1269. this.el.hide();
  1270. this.isHidden = true;
  1271. this.trigger('hide');
  1272. }
  1273. },
  1274. // Creates `this.el` and renders content inside of it
  1275. render: function() {
  1276. var _this = this;
  1277. var options = this.options;
  1278. this.el = $('<div class="fc-popover"/>')
  1279. .addClass(options.className || '')
  1280. .css({
  1281. // position initially to the top left to avoid creating scrollbars
  1282. top: 0,
  1283. left: 0
  1284. })
  1285. .append(options.content)
  1286. .appendTo(options.parentEl);
  1287. // when a click happens on anything inside with a 'fc-close' className, hide the popover
  1288. this.el.on('click', '.fc-close', function() {
  1289. _this.hide();
  1290. });
  1291. if (options.autoHide) {
  1292. $(document).on('mousedown', this.documentMousedownProxy = $.proxy(this, 'documentMousedown'));
  1293. }
  1294. },
  1295. // Triggered when the user clicks *anywhere* in the document, for the autoHide feature
  1296. documentMousedown: function(ev) {
  1297. // only hide the popover if the click happened outside the popover
  1298. if (this.el && !$(ev.target).closest(this.el).length) {
  1299. this.hide();
  1300. }
  1301. },
  1302. // Hides and unregisters any handlers
  1303. destroy: function() {
  1304. this.hide();
  1305. if (this.el) {
  1306. this.el.remove();
  1307. this.el = null;
  1308. }
  1309. $(document).off('mousedown', this.documentMousedownProxy);
  1310. },
  1311. // Positions the popover optimally, using the top/left/right options
  1312. position: function() {
  1313. var options = this.options;
  1314. var origin = this.el.offsetParent().offset();
  1315. var width = this.el.outerWidth();
  1316. var height = this.el.outerHeight();
  1317. var windowEl = $(window);
  1318. var viewportEl = getScrollParent(this.el);
  1319. var viewportTop;
  1320. var viewportLeft;
  1321. var viewportOffset;
  1322. var top; // the "position" (not "offset") values for the popover
  1323. var left; //
  1324. // compute top and left
  1325. top = options.top || 0;
  1326. if (options.left !== undefined) {
  1327. left = options.left;
  1328. }
  1329. else if (options.right !== undefined) {
  1330. left = options.right - width; // derive the left value from the right value
  1331. }
  1332. else {
  1333. left = 0;
  1334. }
  1335. if (viewportEl.is(window) || viewportEl.is(document)) { // normalize getScrollParent's result
  1336. viewportEl = windowEl;
  1337. viewportTop = 0; // the window is always at the top left
  1338. viewportLeft = 0; // (and .offset() won't work if called here)
  1339. }
  1340. else {
  1341. viewportOffset = viewportEl.offset();
  1342. viewportTop = viewportOffset.top;
  1343. viewportLeft = viewportOffset.left;
  1344. }
  1345. // if the window is scrolled, it causes the visible area to be further down
  1346. viewportTop += windowEl.scrollTop();
  1347. viewportLeft += windowEl.scrollLeft();
  1348. // constrain to the view port. if constrained by two edges, give precedence to top/left
  1349. if (options.viewportConstrain !== false) {
  1350. top = Math.min(top, viewportTop + viewportEl.outerHeight() - height - this.margin);
  1351. top = Math.max(top, viewportTop + this.margin);
  1352. left = Math.min(left, viewportLeft + viewportEl.outerWidth() - width - this.margin);
  1353. left = Math.max(left, viewportLeft + this.margin);
  1354. }
  1355. this.el.css({
  1356. top: top - origin.top,
  1357. left: left - origin.left
  1358. });
  1359. },
  1360. // Triggers a callback. Calls a function in the option hash of the same name.
  1361. // Arguments beyond the first `name` are forwarded on.
  1362. // TODO: better code reuse for this. Repeat code
  1363. trigger: function(name) {
  1364. if (this.options[name]) {
  1365. this.options[name].apply(this, Array.prototype.slice.call(arguments, 1));
  1366. }
  1367. }
  1368. });
  1369. /* A "coordinate map" converts pixel coordinates into an associated cell, which has an associated date
  1370. ------------------------------------------------------------------------------------------------------------------------
  1371. Common interface:
  1372. CoordMap.prototype = {
  1373. build: function() {},
  1374. getCell: function(x, y) {}
  1375. };
  1376. */
  1377. /* Coordinate map for a grid component
  1378. ----------------------------------------------------------------------------------------------------------------------*/
  1379. var GridCoordMap = Class.extend({
  1380. grid: null, // reference to the Grid
  1381. rowCoords: null, // array of {top,bottom} objects
  1382. colCoords: null, // array of {left,right} objects
  1383. containerEl: null, // container element that all coordinates are constrained to. optionally assigned
  1384. minX: null,
  1385. maxX: null, // exclusive
  1386. minY: null,
  1387. maxY: null, // exclusive
  1388. constructor: function(grid) {
  1389. this.grid = grid;
  1390. },
  1391. // Queries the grid for the coordinates of all the cells
  1392. build: function() {
  1393. this.rowCoords = this.grid.computeRowCoords();
  1394. this.colCoords = this.grid.computeColCoords();
  1395. this.computeBounds();
  1396. },
  1397. // Clears the coordinates data to free up memory
  1398. clear: function() {
  1399. this.rowCoords = null;
  1400. this.colCoords = null;
  1401. },
  1402. // Given a coordinate of the document, gets the associated cell. If no cell is underneath, returns null
  1403. getCell: function(x, y) {
  1404. var rowCoords = this.rowCoords;
  1405. var colCoords = this.colCoords;
  1406. var hitRow = null;
  1407. var hitCol = null;
  1408. var i, coords;
  1409. var cell;
  1410. if (this.inBounds(x, y)) {
  1411. for (i = 0; i < rowCoords.length; i++) {
  1412. coords = rowCoords[i];
  1413. if (y >= coords.top && y < coords.bottom) {
  1414. hitRow = i;
  1415. break;
  1416. }
  1417. }
  1418. for (i = 0; i < colCoords.length; i++) {
  1419. coords = colCoords[i];
  1420. if (x >= coords.left && x < coords.right) {
  1421. hitCol = i;
  1422. break;
  1423. }
  1424. }
  1425. if (hitRow !== null && hitCol !== null) {
  1426. cell = this.grid.getCell(hitRow, hitCol);
  1427. cell.grid = this.grid; // for DragListener's isCellsEqual. dragging between grids
  1428. return cell;
  1429. }
  1430. }
  1431. return null;
  1432. },
  1433. // If there is a containerEl, compute the bounds into min/max values
  1434. computeBounds: function() {
  1435. var containerOffset;
  1436. if (this.containerEl) {
  1437. containerOffset = this.containerEl.offset();
  1438. this.minX = containerOffset.left;
  1439. this.maxX = containerOffset.left + this.containerEl.outerWidth();
  1440. this.minY = containerOffset.top;
  1441. this.maxY = containerOffset.top + this.containerEl.outerHeight();
  1442. }
  1443. },
  1444. // Determines if the given coordinates are in bounds. If no `containerEl`, always true
  1445. inBounds: function(x, y) {
  1446. if (this.containerEl) {
  1447. return x >= this.minX && x < this.maxX && y >= this.minY && y < this.maxY;
  1448. }
  1449. return true;
  1450. }
  1451. });
  1452. /* Coordinate map that is a combination of multiple other coordinate maps
  1453. ----------------------------------------------------------------------------------------------------------------------*/
  1454. var ComboCoordMap = Class.extend({
  1455. coordMaps: null, // an array of CoordMaps
  1456. constructor: function(coordMaps) {
  1457. this.coordMaps = coordMaps;
  1458. },
  1459. // Builds all coordMaps
  1460. build: function() {
  1461. var coordMaps = this.coordMaps;
  1462. var i;
  1463. for (i = 0; i < coordMaps.length; i++) {
  1464. coordMaps[i].build();
  1465. }
  1466. },
  1467. // Queries all coordMaps for the cell underneath the given coordinates, returning the first result
  1468. getCell: function(x, y) {
  1469. var coordMaps = this.coordMaps;
  1470. var cell = null;
  1471. var i;
  1472. for (i = 0; i < coordMaps.length && !cell; i++) {
  1473. cell = coordMaps[i].getCell(x, y);
  1474. }
  1475. return cell;
  1476. },
  1477. // Clears all coordMaps
  1478. clear: function() {
  1479. var coordMaps = this.coordMaps;
  1480. var i;
  1481. for (i = 0; i < coordMaps.length; i++) {
  1482. coordMaps[i].clear();
  1483. }
  1484. }
  1485. });
  1486. /* Tracks mouse movements over a CoordMap and raises events about which cell the mouse is over.
  1487. ----------------------------------------------------------------------------------------------------------------------*/
  1488. // TODO: very useful to have a handler that gets called upon cellOut OR when dragging stops (for cleanup)
  1489. var DragListener = Class.extend({
  1490. coordMap: null,
  1491. options: null,
  1492. isListening: false,
  1493. isDragging: false,
  1494. // the cell the mouse was over when listening started
  1495. origCell: null,
  1496. // the cell the mouse is over
  1497. cell: null,
  1498. // coordinates of the initial mousedown
  1499. mouseX0: null,
  1500. mouseY0: null,
  1501. // handler attached to the document, bound to the DragListener's `this`
  1502. mousemoveProxy: null,
  1503. mouseupProxy: null,
  1504. scrollEl: null,
  1505. scrollBounds: null, // { top, bottom, left, right }
  1506. scrollTopVel: null, // pixels per second
  1507. scrollLeftVel: null, // pixels per second
  1508. scrollIntervalId: null, // ID of setTimeout for scrolling animation loop
  1509. scrollHandlerProxy: null, // this-scoped function for handling when scrollEl is scrolled
  1510. scrollSensitivity: 30, // pixels from edge for scrolling to start
  1511. scrollSpeed: 200, // pixels per second, at maximum speed
  1512. scrollIntervalMs: 50, // millisecond wait between scroll increment
  1513. constructor: function(coordMap, options) {
  1514. this.coordMap = coordMap;
  1515. this.options = options || {};
  1516. },
  1517. // Call this when the user does a mousedown. Will probably lead to startListening
  1518. mousedown: function(ev) {
  1519. if (isPrimaryMouseButton(ev)) {
  1520. ev.preventDefault(); // prevents native selection in most browsers
  1521. this.startListening(ev);
  1522. // start the drag immediately if there is no minimum distance for a drag start
  1523. if (!this.options.distance) {
  1524. this.startDrag(ev);
  1525. }
  1526. }
  1527. },
  1528. // Call this to start tracking mouse movements
  1529. startListening: function(ev) {
  1530. var scrollParent;
  1531. var cell;
  1532. if (!this.isListening) {
  1533. // grab scroll container and attach handler
  1534. if (ev && this.options.scroll) {
  1535. scrollParent = getScrollParent($(ev.target));
  1536. if (!scrollParent.is(window) && !scrollParent.is(document)) {
  1537. this.scrollEl = scrollParent;
  1538. // scope to `this`, and use `debounce` to make sure rapid calls don't happen
  1539. this.scrollHandlerProxy = debounce($.proxy(this, 'scrollHandler'), 100);
  1540. this.scrollEl.on('scroll', this.scrollHandlerProxy);
  1541. }
  1542. }
  1543. this.computeCoords(); // relies on `scrollEl`
  1544. // get info on the initial cell and its coordinates
  1545. if (ev) {
  1546. cell = this.getCell(ev);
  1547. this.origCell = cell;
  1548. this.mouseX0 = ev.pageX;
  1549. this.mouseY0 = ev.pageY;
  1550. }
  1551. $(document)
  1552. .on('mousemove', this.mousemoveProxy = $.proxy(this, 'mousemove'))
  1553. .on('mouseup', this.mouseupProxy = $.proxy(this, 'mouseup'))
  1554. .on('selectstart', this.preventDefault); // prevents native selection in IE<=8
  1555. this.isListening = true;
  1556. this.trigger('listenStart', ev);
  1557. }
  1558. },
  1559. // Recomputes the drag-critical positions of elements
  1560. computeCoords: function() {
  1561. this.coordMap.build();
  1562. this.computeScrollBounds();
  1563. },
  1564. // Called when the user moves the mouse
  1565. mousemove: function(ev) {
  1566. var minDistance;
  1567. var distanceSq; // current distance from mouseX0/mouseY0, squared
  1568. if (!this.isDragging) { // if not already dragging...
  1569. // then start the drag if the minimum distance criteria is met
  1570. minDistance = this.options.distance || 1;
  1571. distanceSq = Math.pow(ev.pageX - this.mouseX0, 2) + Math.pow(ev.pageY - this.mouseY0, 2);
  1572. if (distanceSq >= minDistance * minDistance) { // use pythagorean theorem
  1573. this.startDrag(ev);
  1574. }
  1575. }
  1576. if (this.isDragging) {
  1577. this.drag(ev); // report a drag, even if this mousemove initiated the drag
  1578. }
  1579. },
  1580. // Call this to initiate a legitimate drag.
  1581. // This function is called internally from this class, but can also be called explicitly from outside
  1582. startDrag: function(ev) {
  1583. var cell;
  1584. if (!this.isListening) { // startDrag must have manually initiated
  1585. this.startListening();
  1586. }
  1587. if (!this.isDragging) {
  1588. this.isDragging = true;
  1589. this.trigger('dragStart', ev);
  1590. // report the initial cell the mouse is over
  1591. // especially important if no min-distance and drag starts immediately
  1592. cell = this.getCell(ev); // this might be different from this.origCell if the min-distance is large
  1593. if (cell) {
  1594. this.cellOver(cell);
  1595. }
  1596. }
  1597. },
  1598. // Called while the mouse is being moved and when we know a legitimate drag is taking place
  1599. drag: function(ev) {
  1600. var cell;
  1601. if (this.isDragging) {
  1602. cell = this.getCell(ev);
  1603. if (!isCellsEqual(cell, this.cell)) { // a different cell than before?
  1604. if (this.cell) {
  1605. this.cellOut();
  1606. }
  1607. if (cell) {
  1608. this.cellOver(cell);
  1609. }
  1610. }
  1611. this.dragScroll(ev); // will possibly cause scrolling
  1612. }
  1613. },
  1614. // Called when a the mouse has just moved over a new cell
  1615. cellOver: function(cell) {
  1616. this.cell = cell;
  1617. this.trigger('cellOver', cell, isCellsEqual(cell, this.origCell));
  1618. },
  1619. // Called when the mouse has just moved out of a cell
  1620. cellOut: function() {
  1621. if (this.cell) {
  1622. this.trigger('cellOut', this.cell);
  1623. this.cell = null;
  1624. }
  1625. },
  1626. // Called when the user does a mouseup
  1627. mouseup: function(ev) {
  1628. this.stopDrag(ev);
  1629. this.stopListening(ev);
  1630. },
  1631. // Called when the drag is over. Will not cause listening to stop however.
  1632. // A concluding 'cellOut' event will NOT be triggered.
  1633. stopDrag: function(ev) {
  1634. if (this.isDragging) {
  1635. this.stopScrolling();
  1636. this.trigger('dragStop', ev);
  1637. this.isDragging = false;
  1638. }
  1639. },
  1640. // Call this to stop listening to the user's mouse events
  1641. stopListening: function(ev) {
  1642. if (this.isListening) {
  1643. // remove the scroll handler if there is a scrollEl
  1644. if (this.scrollEl) {
  1645. this.scrollEl.off('scroll', this.scrollHandlerProxy);
  1646. this.scrollHandlerProxy = null;
  1647. }
  1648. $(document)
  1649. .off('mousemove', this.mousemoveProxy)
  1650. .off('mouseup', this.mouseupProxy)
  1651. .off('selectstart', this.preventDefault);
  1652. this.mousemoveProxy = null;
  1653. this.mouseupProxy = null;
  1654. this.isListening = false;
  1655. this.trigger('listenStop', ev);
  1656. this.origCell = this.cell = null;
  1657. this.coordMap.clear();
  1658. }
  1659. },
  1660. // Gets the cell underneath the coordinates for the given mouse event
  1661. getCell: function(ev) {
  1662. return this.coordMap.getCell(ev.pageX, ev.pageY);
  1663. },
  1664. // Triggers a callback. Calls a function in the option hash of the same name.
  1665. // Arguments beyond the first `name` are forwarded on.
  1666. trigger: function(name) {
  1667. if (this.options[name]) {
  1668. this.options[name].apply(this, Array.prototype.slice.call(arguments, 1));
  1669. }
  1670. },
  1671. // Stops a given mouse event from doing it's native browser action. In our case, text selection.
  1672. preventDefault: function(ev) {
  1673. ev.preventDefault();
  1674. },
  1675. /* Scrolling
  1676. ------------------------------------------------------------------------------------------------------------------*/
  1677. // Computes and stores the bounding rectangle of scrollEl
  1678. computeScrollBounds: function() {
  1679. var el = this.scrollEl;
  1680. var offset;
  1681. if (el) {
  1682. offset = el.offset();
  1683. this.scrollBounds = {
  1684. top: offset.top,
  1685. left: offset.left,
  1686. bottom: offset.top + el.outerHeight(),
  1687. right: offset.left + el.outerWidth()
  1688. };
  1689. }
  1690. },
  1691. // Called when the dragging is in progress and scrolling should be updated
  1692. dragScroll: function(ev) {
  1693. var sensitivity = this.scrollSensitivity;
  1694. var bounds = this.scrollBounds;
  1695. var topCloseness, bottomCloseness;
  1696. var leftCloseness, rightCloseness;
  1697. var topVel = 0;
  1698. var leftVel = 0;
  1699. if (bounds) { // only scroll if scrollEl exists
  1700. // compute closeness to edges. valid range is from 0.0 - 1.0
  1701. topCloseness = (sensitivity - (ev.pageY - bounds.top)) / sensitivity;
  1702. bottomCloseness = (sensitivity - (bounds.bottom - ev.pageY)) / sensitivity;
  1703. leftCloseness = (sensitivity - (ev.pageX - bounds.left)) / sensitivity;
  1704. rightCloseness = (sensitivity - (bounds.right - ev.pageX)) / sensitivity;
  1705. // translate vertical closeness into velocity.
  1706. // mouse must be completely in bounds for velocity to happen.
  1707. if (topCloseness >= 0 && topCloseness <= 1) {
  1708. topVel = topCloseness * this.scrollSpeed * -1; // negative. for scrolling up
  1709. }
  1710. else if (bottomCloseness >= 0 && bottomCloseness <= 1) {
  1711. topVel = bottomCloseness * this.scrollSpeed;
  1712. }
  1713. // translate horizontal closeness into velocity
  1714. if (leftCloseness >= 0 && leftCloseness <= 1) {
  1715. leftVel = leftCloseness * this.scrollSpeed * -1; // negative. for scrolling left
  1716. }
  1717. else if (rightCloseness >= 0 && rightCloseness <= 1) {
  1718. leftVel = rightCloseness * this.scrollSpeed;
  1719. }
  1720. }
  1721. this.setScrollVel(topVel, leftVel);
  1722. },
  1723. // Sets the speed-of-scrolling for the scrollEl
  1724. setScrollVel: function(topVel, leftVel) {
  1725. this.scrollTopVel = topVel;
  1726. this.scrollLeftVel = leftVel;
  1727. this.constrainScrollVel(); // massages into realistic values
  1728. // if there is non-zero velocity, and an animation loop hasn't already started, then START
  1729. if ((this.scrollTopVel || this.scrollLeftVel) && !this.scrollIntervalId) {
  1730. this.scrollIntervalId = setInterval(
  1731. $.proxy(this, 'scrollIntervalFunc'), // scope to `this`
  1732. this.scrollIntervalMs
  1733. );
  1734. }
  1735. },
  1736. // Forces scrollTopVel and scrollLeftVel to be zero if scrolling has already gone all the way
  1737. constrainScrollVel: function() {
  1738. var el = this.scrollEl;
  1739. if (this.scrollTopVel < 0) { // scrolling up?
  1740. if (el.scrollTop() <= 0) { // already scrolled all the way up?
  1741. this.scrollTopVel = 0;
  1742. }
  1743. }
  1744. else if (this.scrollTopVel > 0) { // scrolling down?
  1745. if (el.scrollTop() + el[0].clientHeight >= el[0].scrollHeight) { // already scrolled all the way down?
  1746. this.scrollTopVel = 0;
  1747. }
  1748. }
  1749. if (this.scrollLeftVel < 0) { // scrolling left?
  1750. if (el.scrollLeft() <= 0) { // already scrolled all the left?
  1751. this.scrollLeftVel = 0;
  1752. }
  1753. }
  1754. else if (this.scrollLeftVel > 0) { // scrolling right?
  1755. if (el.scrollLeft() + el[0].clientWidth >= el[0].scrollWidth) { // already scrolled all the way right?
  1756. this.scrollLeftVel = 0;
  1757. }
  1758. }
  1759. },
  1760. // This function gets called during every iteration of the scrolling animation loop
  1761. scrollIntervalFunc: function() {
  1762. var el = this.scrollEl;
  1763. var frac = this.scrollIntervalMs / 1000; // considering animation frequency, what the vel should be mult'd by
  1764. // change the value of scrollEl's scroll
  1765. if (this.scrollTopVel) {
  1766. el.scrollTop(el.scrollTop() + this.scrollTopVel * frac);
  1767. }
  1768. if (this.scrollLeftVel) {
  1769. el.scrollLeft(el.scrollLeft() + this.scrollLeftVel * frac);
  1770. }
  1771. this.constrainScrollVel(); // since the scroll values changed, recompute the velocities
  1772. // if scrolled all the way, which causes the vels to be zero, stop the animation loop
  1773. if (!this.scrollTopVel && !this.scrollLeftVel) {
  1774. this.stopScrolling();
  1775. }
  1776. },
  1777. // Kills any existing scrolling animation loop
  1778. stopScrolling: function() {
  1779. if (this.scrollIntervalId) {
  1780. clearInterval(this.scrollIntervalId);
  1781. this.scrollIntervalId = null;
  1782. // when all done with scrolling, recompute positions since they probably changed
  1783. this.computeCoords();
  1784. }
  1785. },
  1786. // Get called when the scrollEl is scrolled (NOTE: this is delayed via debounce)
  1787. scrollHandler: function() {
  1788. // recompute all coordinates, but *only* if this is *not* part of our scrolling animation
  1789. if (!this.scrollIntervalId) {
  1790. this.computeCoords();
  1791. }
  1792. }
  1793. });
  1794. // Returns `true` if the cells are identically equal. `false` otherwise.
  1795. // They must have the same row, col, and be from the same grid.
  1796. // Two null values will be considered equal, as two "out of the grid" states are the same.
  1797. function isCellsEqual(cell1, cell2) {
  1798. if (!cell1 && !cell2) {
  1799. return true;
  1800. }
  1801. if (cell1 && cell2) {
  1802. return cell1.grid === cell2.grid &&
  1803. cell1.row === cell2.row &&
  1804. cell1.col === cell2.col;
  1805. }
  1806. return false;
  1807. }
  1808. /* Creates a clone of an element and lets it track the mouse as it moves
  1809. ----------------------------------------------------------------------------------------------------------------------*/
  1810. var MouseFollower = Class.extend({
  1811. options: null,
  1812. sourceEl: null, // the element that will be cloned and made to look like it is dragging
  1813. el: null, // the clone of `sourceEl` that will track the mouse
  1814. parentEl: null, // the element that `el` (the clone) will be attached to
  1815. // the initial position of el, relative to the offset parent. made to match the initial offset of sourceEl
  1816. top0: null,
  1817. left0: null,
  1818. // the initial position of the mouse
  1819. mouseY0: null,
  1820. mouseX0: null,
  1821. // the number of pixels the mouse has moved from its initial position
  1822. topDelta: null,
  1823. leftDelta: null,
  1824. mousemoveProxy: null, // document mousemove handler, bound to the MouseFollower's `this`
  1825. isFollowing: false,
  1826. isHidden: false,
  1827. isAnimating: false, // doing the revert animation?
  1828. constructor: function(sourceEl, options) {
  1829. this.options = options = options || {};
  1830. this.sourceEl = sourceEl;
  1831. this.parentEl = options.parentEl ? $(options.parentEl) : sourceEl.parent(); // default to sourceEl's parent
  1832. },
  1833. // Causes the element to start following the mouse
  1834. start: function(ev) {
  1835. if (!this.isFollowing) {
  1836. this.isFollowing = true;
  1837. this.mouseY0 = ev.pageY;
  1838. this.mouseX0 = ev.pageX;
  1839. this.topDelta = 0;
  1840. this.leftDelta = 0;
  1841. if (!this.isHidden) {
  1842. this.updatePosition();
  1843. }
  1844. $(document).on('mousemove', this.mousemoveProxy = $.proxy(this, 'mousemove'));
  1845. }
  1846. },
  1847. // Causes the element to stop following the mouse. If shouldRevert is true, will animate back to original position.
  1848. // `callback` gets invoked when the animation is complete. If no animation, it is invoked immediately.
  1849. stop: function(shouldRevert, callback) {
  1850. var _this = this;
  1851. var revertDuration = this.options.revertDuration;
  1852. function complete() {
  1853. this.isAnimating = false;
  1854. _this.destroyEl();
  1855. this.top0 = this.left0 = null; // reset state for future updatePosition calls
  1856. if (callback) {
  1857. callback();
  1858. }
  1859. }
  1860. if (this.isFollowing && !this.isAnimating) { // disallow more than one stop animation at a time
  1861. this.isFollowing = false;
  1862. $(document).off('mousemove', this.mousemoveProxy);
  1863. if (shouldRevert && revertDuration && !this.isHidden) { // do a revert animation?
  1864. this.isAnimating = true;
  1865. this.el.animate({
  1866. top: this.top0,
  1867. left: this.left0
  1868. }, {
  1869. duration: revertDuration,
  1870. complete: complete
  1871. });
  1872. }
  1873. else {
  1874. complete();
  1875. }
  1876. }
  1877. },
  1878. // Gets the tracking element. Create it if necessary
  1879. getEl: function() {
  1880. var el = this.el;
  1881. if (!el) {
  1882. this.sourceEl.width(); // hack to force IE8 to compute correct bounding box
  1883. el = this.el = this.sourceEl.clone()
  1884. .css({
  1885. position: 'absolute',
  1886. visibility: '', // in case original element was hidden (commonly through hideEvents())
  1887. display: this.isHidden ? 'none' : '', // for when initially hidden
  1888. margin: 0,
  1889. right: 'auto', // erase and set width instead
  1890. bottom: 'auto', // erase and set height instead
  1891. width: this.sourceEl.width(), // explicit height in case there was a 'right' value
  1892. height: this.sourceEl.height(), // explicit width in case there was a 'bottom' value
  1893. opacity: this.options.opacity || '',
  1894. zIndex: this.options.zIndex
  1895. })
  1896. .appendTo(this.parentEl);
  1897. }
  1898. return el;
  1899. },
  1900. // Removes the tracking element if it has already been created
  1901. destroyEl: function() {
  1902. if (this.el) {
  1903. this.el.remove();
  1904. this.el = null;
  1905. }
  1906. },
  1907. // Update the CSS position of the tracking element
  1908. updatePosition: function() {
  1909. var sourceOffset;
  1910. var origin;
  1911. this.getEl(); // ensure this.el
  1912. // make sure origin info was computed
  1913. if (this.top0 === null) {
  1914. this.sourceEl.width(); // hack to force IE8 to compute correct bounding box
  1915. sourceOffset = this.sourceEl.offset();
  1916. origin = this.el.offsetParent().offset();
  1917. this.top0 = sourceOffset.top - origin.top;
  1918. this.left0 = sourceOffset.left - origin.left;
  1919. }
  1920. this.el.css({
  1921. top: this.top0 + this.topDelta,
  1922. left: this.left0 + this.leftDelta
  1923. });
  1924. },
  1925. // Gets called when the user moves the mouse
  1926. mousemove: function(ev) {
  1927. this.topDelta = ev.pageY - this.mouseY0;
  1928. this.leftDelta = ev.pageX - this.mouseX0;
  1929. if (!this.isHidden) {
  1930. this.updatePosition();
  1931. }
  1932. },
  1933. // Temporarily makes the tracking element invisible. Can be called before following starts
  1934. hide: function() {
  1935. if (!this.isHidden) {
  1936. this.isHidden = true;
  1937. if (this.el) {
  1938. this.el.hide();
  1939. }
  1940. }
  1941. },
  1942. // Show the tracking element after it has been temporarily hidden
  1943. show: function() {
  1944. if (this.isHidden) {
  1945. this.isHidden = false;
  1946. this.updatePosition();
  1947. this.getEl().show();
  1948. }
  1949. }
  1950. });
  1951. /* A utility class for rendering <tr> rows.
  1952. ----------------------------------------------------------------------------------------------------------------------*/
  1953. // It leverages methods of the subclass and the View to determine custom rendering behavior for each row "type"
  1954. // (such as highlight rows, day rows, helper rows, etc).
  1955. var RowRenderer = Class.extend({
  1956. view: null, // a View object
  1957. isRTL: null, // shortcut to the view's isRTL option
  1958. cellHtml: '<td/>', // plain default HTML used for a cell when no other is available
  1959. constructor: function(view) {
  1960. this.view = view;
  1961. this.isRTL = view.opt('isRTL');
  1962. },
  1963. // Renders the HTML for a row, leveraging custom cell-HTML-renderers based on the `rowType`.
  1964. // Also applies the "intro" and "outro" cells, which are specified by the subclass and views.
  1965. // `row` is an optional row number.
  1966. rowHtml: function(rowType, row) {
  1967. var renderCell = this.getHtmlRenderer('cell', rowType);
  1968. var rowCellHtml = '';
  1969. var col;
  1970. var cell;
  1971. row = row || 0;
  1972. for (col = 0; col < this.colCnt; col++) {
  1973. cell = this.getCell(row, col);
  1974. rowCellHtml += renderCell(cell);
  1975. }
  1976. rowCellHtml = this.bookendCells(rowCellHtml, rowType, row); // apply intro and outro
  1977. return '<tr>' + rowCellHtml + '</tr>';
  1978. },
  1979. // Applies the "intro" and "outro" HTML to the given cells.
  1980. // Intro means the leftmost cell when the calendar is LTR and the rightmost cell when RTL. Vice-versa for outro.
  1981. // `cells` can be an HTML string of <td>'s or a jQuery <tr> element
  1982. // `row` is an optional row number.
  1983. bookendCells: function(cells, rowType, row) {
  1984. var intro = this.getHtmlRenderer('intro', rowType)(row || 0);
  1985. var outro = this.getHtmlRenderer('outro', rowType)(row || 0);
  1986. var prependHtml = this.isRTL ? outro : intro;
  1987. var appendHtml = this.isRTL ? intro : outro;
  1988. if (typeof cells === 'string') {
  1989. return prependHtml + cells + appendHtml;
  1990. }
  1991. else { // a jQuery <tr> element
  1992. return cells.prepend(prependHtml).append(appendHtml);
  1993. }
  1994. },
  1995. // Returns an HTML-rendering function given a specific `rendererName` (like cell, intro, or outro) and a specific
  1996. // `rowType` (like day, eventSkeleton, helperSkeleton), which is optional.
  1997. // If a renderer for the specific rowType doesn't exist, it will fall back to a generic renderer.
  1998. // We will query the View object first for any custom rendering functions, then the methods of the subclass.
  1999. getHtmlRenderer: function(rendererName, rowType) {
  2000. var view = this.view;
  2001. var generalName; // like "cellHtml"
  2002. var specificName; // like "dayCellHtml". based on rowType
  2003. var provider; // either the View or the RowRenderer subclass, whichever provided the method
  2004. var renderer;
  2005. generalName = rendererName + 'Html';
  2006. if (rowType) {
  2007. specificName = rowType + capitaliseFirstLetter(rendererName) + 'Html';
  2008. }
  2009. if (specificName && (renderer = view[specificName])) {
  2010. provider = view;
  2011. }
  2012. else if (specificName && (renderer = this[specificName])) {
  2013. provider = this;
  2014. }
  2015. else if ((renderer = view[generalName])) {
  2016. provider = view;
  2017. }
  2018. else if ((renderer = this[generalName])) {
  2019. provider = this;
  2020. }
  2021. if (typeof renderer === 'function') {
  2022. return function() {
  2023. return renderer.apply(provider, arguments) || ''; // use correct `this` and always return a string
  2024. };
  2025. }
  2026. // the rendered can be a plain string as well. if not specified, always an empty string.
  2027. return function() {
  2028. return renderer || '';
  2029. };
  2030. }
  2031. });
  2032. /* An abstract class comprised of a "grid" of cells that each represent a specific datetime
  2033. ----------------------------------------------------------------------------------------------------------------------*/
  2034. var Grid = fc.Grid = RowRenderer.extend({
  2035. start: null, // the date of the first cell
  2036. end: null, // the date after the last cell
  2037. rowCnt: 0, // number of rows
  2038. colCnt: 0, // number of cols
  2039. rowData: null, // array of objects, holding misc data for each row
  2040. colData: null, // array of objects, holding misc data for each column
  2041. el: null, // the containing element
  2042. coordMap: null, // a GridCoordMap that converts pixel values to datetimes
  2043. elsByFill: null, // a hash of jQuery element sets used for rendering each fill. Keyed by fill name.
  2044. documentDragStartProxy: null, // binds the Grid's scope to documentDragStart (in DayGrid.events)
  2045. // derived from options
  2046. colHeadFormat: null, // TODO: move to another class. not applicable to all Grids
  2047. eventTimeFormat: null,
  2048. displayEventEnd: null,
  2049. constructor: function() {
  2050. RowRenderer.apply(this, arguments); // call the super-constructor
  2051. this.coordMap = new GridCoordMap(this);
  2052. this.elsByFill = {};
  2053. this.documentDragStartProxy = $.proxy(this, 'documentDragStart');
  2054. },
  2055. // Renders the grid into the `el` element.
  2056. // Subclasses should override and call this super-method when done.
  2057. render: function() {
  2058. this.bindHandlers();
  2059. },
  2060. // Called when the grid's resources need to be cleaned up
  2061. destroy: function() {
  2062. this.unbindHandlers();
  2063. },
  2064. /* Options
  2065. ------------------------------------------------------------------------------------------------------------------*/
  2066. // Generates the format string used for the text in column headers, if not explicitly defined by 'columnFormat'
  2067. // TODO: move to another class. not applicable to all Grids
  2068. computeColHeadFormat: function() {
  2069. // subclasses must implement if they want to use headHtml()
  2070. },
  2071. // Generates the format string used for event time text, if not explicitly defined by 'timeFormat'
  2072. computeEventTimeFormat: function() {
  2073. return this.view.opt('smallTimeFormat');
  2074. },
  2075. // Determines whether events should have their end times displayed, if not explicitly defined by 'displayEventEnd'
  2076. computeDisplayEventEnd: function() {
  2077. return false;
  2078. },
  2079. /* Dates
  2080. ------------------------------------------------------------------------------------------------------------------*/
  2081. // Tells the grid about what period of time to display. Grid will subsequently compute dates for cell system.
  2082. setRange: function(range) {
  2083. var view = this.view;
  2084. this.start = range.start.clone();
  2085. this.end = range.end.clone();
  2086. this.rowData = [];
  2087. this.colData = [];
  2088. this.updateCells();
  2089. // Populate option-derived settings. Look for override first, then compute if necessary.
  2090. this.colHeadFormat = view.opt('columnFormat') || this.computeColHeadFormat();
  2091. this.eventTimeFormat = view.opt('timeFormat') || this.computeEventTimeFormat();
  2092. this.displayEventEnd = view.opt('displayEventEnd');
  2093. if (this.displayEventEnd == null) {
  2094. this.displayEventEnd = this.computeDisplayEventEnd();
  2095. }
  2096. },
  2097. // Responsible for setting rowCnt/colCnt and any other row/col data
  2098. updateCells: function() {
  2099. // subclasses must implement
  2100. },
  2101. // Converts a range with an inclusive `start` and an exclusive `end` into an array of segment objects
  2102. rangeToSegs: function(range) {
  2103. // subclasses must implement
  2104. },
  2105. /* Cells
  2106. ------------------------------------------------------------------------------------------------------------------*/
  2107. // NOTE: columns are ordered left-to-right
  2108. // Gets an object containing row/col number, misc data, and range information about the cell.
  2109. // Accepts row/col values, an object with row/col properties, or a single-number offset from the first cell.
  2110. getCell: function(row, col) {
  2111. var cell;
  2112. if (col == null) {
  2113. if (typeof row === 'number') { // a single-number offset
  2114. col = row % this.colCnt;
  2115. row = Math.floor(row / this.colCnt);
  2116. }
  2117. else { // an object with row/col properties
  2118. col = row.col;
  2119. row = row.row;
  2120. }
  2121. }
  2122. cell = { row: row, col: col };
  2123. $.extend(cell, this.getRowData(row), this.getColData(col));
  2124. $.extend(cell, this.computeCellRange(cell));
  2125. return cell;
  2126. },
  2127. // Given a cell object with index and misc data, generates a range object
  2128. computeCellRange: function(cell) {
  2129. // subclasses must implement
  2130. },
  2131. // Retrieves misc data about the given row
  2132. getRowData: function(row) {
  2133. return this.rowData[row] || {};
  2134. },
  2135. // Retrieves misc data baout the given column
  2136. getColData: function(col) {
  2137. return this.colData[col] || {};
  2138. },
  2139. // Retrieves the element representing the given row
  2140. getRowEl: function(row) {
  2141. // subclasses should implement if leveraging the default getCellDayEl() or computeRowCoords()
  2142. },
  2143. // Retrieves the element representing the given column
  2144. getColEl: function(col) {
  2145. // subclasses should implement if leveraging the default getCellDayEl() or computeColCoords()
  2146. },
  2147. // Given a cell object, returns the element that represents the cell's whole-day
  2148. getCellDayEl: function(cell) {
  2149. return this.getColEl(cell.col) || this.getRowEl(cell.row);
  2150. },
  2151. /* Cell Coordinates
  2152. ------------------------------------------------------------------------------------------------------------------*/
  2153. // Computes the top/bottom coordinates of all rows.
  2154. // By default, queries the dimensions of the element provided by getRowEl().
  2155. computeRowCoords: function() {
  2156. var items = [];
  2157. var i, el;
  2158. var item;
  2159. for (i = 0; i < this.rowCnt; i++) {
  2160. el = this.getRowEl(i);
  2161. item = {
  2162. top: el.offset().top
  2163. };
  2164. if (i > 0) {
  2165. items[i - 1].bottom = item.top;
  2166. }
  2167. items.push(item);
  2168. }
  2169. item.bottom = item.top + el.outerHeight();
  2170. return items;
  2171. },
  2172. // Computes the left/right coordinates of all rows.
  2173. // By default, queries the dimensions of the element provided by getColEl().
  2174. computeColCoords: function() {
  2175. var items = [];
  2176. var i, el;
  2177. var item;
  2178. for (i = 0; i < this.colCnt; i++) {
  2179. el = this.getColEl(i);
  2180. item = {
  2181. left: el.offset().left
  2182. };
  2183. if (i > 0) {
  2184. items[i - 1].right = item.left;
  2185. }
  2186. items.push(item);
  2187. }
  2188. item.right = item.left + el.outerWidth();
  2189. return items;
  2190. },
  2191. /* Handlers
  2192. ------------------------------------------------------------------------------------------------------------------*/
  2193. // Attaches handlers to DOM
  2194. bindHandlers: function() {
  2195. var _this = this;
  2196. // attach a handler to the grid's root element.
  2197. // we don't need to clean up in unbindHandlers or destroy, because when jQuery removes the element from the
  2198. // DOM it automatically unregisters the handlers.
  2199. this.el.on('mousedown', function(ev) {
  2200. if (
  2201. !$(ev.target).is('.fc-event-container *, .fc-more') && // not an an event element, or "more.." link
  2202. !$(ev.target).closest('.fc-popover').length // not on a popover (like the "more.." events one)
  2203. ) {
  2204. _this.dayMousedown(ev);
  2205. }
  2206. });
  2207. // attach event-element-related handlers. in Grid.events
  2208. // same garbage collection note as above.
  2209. this.bindSegHandlers();
  2210. $(document).on('dragstart', this.documentDragStartProxy); // jqui drag
  2211. },
  2212. // Unattaches handlers from the DOM
  2213. unbindHandlers: function() {
  2214. $(document).off('dragstart', this.documentDragStartProxy); // jqui drag
  2215. },
  2216. // Process a mousedown on an element that represents a day. For day clicking and selecting.
  2217. dayMousedown: function(ev) {
  2218. var _this = this;
  2219. var view = this.view;
  2220. var isSelectable = view.opt('selectable');
  2221. var dayClickCell; // null if invalid dayClick
  2222. var selectionRange; // null if invalid selection
  2223. // this listener tracks a mousedown on a day element, and a subsequent drag.
  2224. // if the drag ends on the same day, it is a 'dayClick'.
  2225. // if 'selectable' is enabled, this listener also detects selections.
  2226. var dragListener = new DragListener(this.coordMap, {
  2227. //distance: 5, // needs more work if we want dayClick to fire correctly
  2228. scroll: view.opt('dragScroll'),
  2229. dragStart: function() {
  2230. view.unselect(); // since we could be rendering a new selection, we want to clear any old one
  2231. },
  2232. cellOver: function(cell, isOrig) {
  2233. var origCell = dragListener.origCell;
  2234. if (origCell) { // click needs to have started on a cell
  2235. dayClickCell = isOrig ? cell : null; // single-cell selection is a day click
  2236. if (isSelectable) {
  2237. selectionRange = _this.computeSelection(origCell, cell);
  2238. if (selectionRange) {
  2239. _this.renderSelection(selectionRange);
  2240. }
  2241. else {
  2242. disableCursor();
  2243. }
  2244. }
  2245. }
  2246. },
  2247. cellOut: function(cell) {
  2248. dayClickCell = null;
  2249. selectionRange = null;
  2250. _this.destroySelection();
  2251. enableCursor();
  2252. },
  2253. listenStop: function(ev) {
  2254. if (dayClickCell) {
  2255. view.trigger('dayClick', _this.getCellDayEl(dayClickCell), dayClickCell.start, ev);
  2256. }
  2257. if (selectionRange) {
  2258. // the selection will already have been rendered. just report it
  2259. view.reportSelection(selectionRange, ev);
  2260. }
  2261. enableCursor();
  2262. }
  2263. });
  2264. dragListener.mousedown(ev); // start listening, which will eventually initiate a dragStart
  2265. },
  2266. /* Event Helper
  2267. ------------------------------------------------------------------------------------------------------------------*/
  2268. // TODO: should probably move this to Grid.events, like we did event dragging / resizing
  2269. // Renders a mock event over the given range.
  2270. // The range's end can be null, in which case the mock event that is rendered will have a null end time.
  2271. // `sourceSeg` is the internal segment object involved in the drag. If null, something external is dragging.
  2272. renderRangeHelper: function(range, sourceSeg) {
  2273. var fakeEvent;
  2274. fakeEvent = sourceSeg ? createObject(sourceSeg.event) : {}; // mask the original event object if possible
  2275. fakeEvent.start = range.start.clone();
  2276. fakeEvent.end = range.end ? range.end.clone() : null;
  2277. fakeEvent.allDay = null; // force it to be freshly computed by normalizeEventDateProps
  2278. this.view.calendar.normalizeEventDateProps(fakeEvent);
  2279. // this extra className will be useful for differentiating real events from mock events in CSS
  2280. fakeEvent.className = (fakeEvent.className || []).concat('fc-helper');
  2281. // if something external is being dragged in, don't render a resizer
  2282. if (!sourceSeg) {
  2283. fakeEvent.editable = false;
  2284. }
  2285. this.renderHelper(fakeEvent, sourceSeg); // do the actual rendering
  2286. },
  2287. // Renders a mock event
  2288. renderHelper: function(event, sourceSeg) {
  2289. // subclasses must implement
  2290. },
  2291. // Unrenders a mock event
  2292. destroyHelper: function() {
  2293. // subclasses must implement
  2294. },
  2295. /* Selection
  2296. ------------------------------------------------------------------------------------------------------------------*/
  2297. // Renders a visual indication of a selection. Will highlight by default but can be overridden by subclasses.
  2298. renderSelection: function(range) {
  2299. this.renderHighlight(range);
  2300. },
  2301. // Unrenders any visual indications of a selection. Will unrender a highlight by default.
  2302. destroySelection: function() {
  2303. this.destroyHighlight();
  2304. },
  2305. // Given the first and last cells of a selection, returns a range object.
  2306. // Will return something falsy if the selection is invalid (when outside of selectionConstraint for example).
  2307. // Subclasses can override and provide additional data in the range object. Will be passed to renderSelection().
  2308. computeSelection: function(firstCell, lastCell) {
  2309. var dates = [
  2310. firstCell.start,
  2311. firstCell.end,
  2312. lastCell.start,
  2313. lastCell.end
  2314. ];
  2315. var range;
  2316. dates.sort(compareNumbers); // sorts chronologically. works with Moments
  2317. range = {
  2318. start: dates[0].clone(),
  2319. end: dates[3].clone()
  2320. };
  2321. if (!this.view.calendar.isSelectionRangeAllowed(range)) {
  2322. return null;
  2323. }
  2324. return range;
  2325. },
  2326. /* Highlight
  2327. ------------------------------------------------------------------------------------------------------------------*/
  2328. // Renders an emphasis on the given date range. `start` is inclusive. `end` is exclusive.
  2329. renderHighlight: function(range) {
  2330. this.renderFill('highlight', this.rangeToSegs(range));
  2331. },
  2332. // Unrenders the emphasis on a date range
  2333. destroyHighlight: function() {
  2334. this.destroyFill('highlight');
  2335. },
  2336. // Generates an array of classNames for rendering the highlight. Used by the fill system.
  2337. highlightSegClasses: function() {
  2338. return [ 'fc-highlight' ];
  2339. },
  2340. /* Fill System (highlight, background events, business hours)
  2341. ------------------------------------------------------------------------------------------------------------------*/
  2342. // Renders a set of rectangles over the given segments of time.
  2343. // Returns a subset of segs, the segs that were actually rendered.
  2344. // Responsible for populating this.elsByFill. TODO: better API for expressing this requirement
  2345. renderFill: function(type, segs) {
  2346. // subclasses must implement
  2347. },
  2348. // Unrenders a specific type of fill that is currently rendered on the grid
  2349. destroyFill: function(type) {
  2350. var el = this.elsByFill[type];
  2351. if (el) {
  2352. el.remove();
  2353. delete this.elsByFill[type];
  2354. }
  2355. },
  2356. // Renders and assigns an `el` property for each fill segment. Generic enough to work with different types.
  2357. // Only returns segments that successfully rendered.
  2358. // To be harnessed by renderFill (implemented by subclasses).
  2359. // Analagous to renderFgSegEls.
  2360. renderFillSegEls: function(type, segs) {
  2361. var _this = this;
  2362. var segElMethod = this[type + 'SegEl'];
  2363. var html = '';
  2364. var renderedSegs = [];
  2365. var i;
  2366. if (segs.length) {
  2367. // build a large concatenation of segment HTML
  2368. for (i = 0; i < segs.length; i++) {
  2369. html += this.fillSegHtml(type, segs[i]);
  2370. }
  2371. // Grab individual elements from the combined HTML string. Use each as the default rendering.
  2372. // Then, compute the 'el' for each segment.
  2373. $(html).each(function(i, node) {
  2374. var seg = segs[i];
  2375. var el = $(node);
  2376. // allow custom filter methods per-type
  2377. if (segElMethod) {
  2378. el = segElMethod.call(_this, seg, el);
  2379. }
  2380. if (el) { // custom filters did not cancel the render
  2381. el = $(el); // allow custom filter to return raw DOM node
  2382. // correct element type? (would be bad if a non-TD were inserted into a table for example)
  2383. if (el.is(_this.fillSegTag)) {
  2384. seg.el = el;
  2385. renderedSegs.push(seg);
  2386. }
  2387. }
  2388. });
  2389. }
  2390. return renderedSegs;
  2391. },
  2392. fillSegTag: 'div', // subclasses can override
  2393. // Builds the HTML needed for one fill segment. Generic enought o work with different types.
  2394. fillSegHtml: function(type, seg) {
  2395. var classesMethod = this[type + 'SegClasses']; // custom hooks per-type
  2396. var stylesMethod = this[type + 'SegStyles']; //
  2397. var classes = classesMethod ? classesMethod.call(this, seg) : [];
  2398. var styles = stylesMethod ? stylesMethod.call(this, seg) : ''; // a semi-colon separated CSS property string
  2399. return '<' + this.fillSegTag +
  2400. (classes.length ? ' class="' + classes.join(' ') + '"' : '') +
  2401. (styles ? ' style="' + styles + '"' : '') +
  2402. ' />';
  2403. },
  2404. /* Generic rendering utilities for subclasses
  2405. ------------------------------------------------------------------------------------------------------------------*/
  2406. // Renders a day-of-week header row.
  2407. // TODO: move to another class. not applicable to all Grids
  2408. headHtml: function() {
  2409. return '' +
  2410. '<div class="fc-row ' + this.view.widgetHeaderClass + '">' +
  2411. '<table>' +
  2412. '<thead>' +
  2413. this.rowHtml('head') + // leverages RowRenderer
  2414. '</thead>' +
  2415. '</table>' +
  2416. '</div>';
  2417. },
  2418. // Used by the `headHtml` method, via RowRenderer, for rendering the HTML of a day-of-week header cell
  2419. // TODO: move to another class. not applicable to all Grids
  2420. headCellHtml: function(cell) {
  2421. var view = this.view;
  2422. var date = cell.start;
  2423. return '' +
  2424. '<th class="fc-day-header ' + view.widgetHeaderClass + ' fc-' + dayIDs[date.day()] + '">' +
  2425. htmlEscape(date.format(this.colHeadFormat)) +
  2426. '</th>';
  2427. },
  2428. // Renders the HTML for a single-day background cell
  2429. bgCellHtml: function(cell) {
  2430. var view = this.view;
  2431. var date = cell.start;
  2432. var classes = this.getDayClasses(date);
  2433. classes.unshift('fc-day', view.widgetContentClass);
  2434. return '<td class="' + classes.join(' ') + '"' +
  2435. ' data-date="' + date.format('YYYY-MM-DD') + '"' + // if date has a time, won't format it
  2436. '></td>';
  2437. },
  2438. // Computes HTML classNames for a single-day cell
  2439. getDayClasses: function(date) {
  2440. var view = this.view;
  2441. var today = view.calendar.getNow().stripTime();
  2442. var classes = [ 'fc-' + dayIDs[date.day()] ];
  2443. if (
  2444. view.name === 'month' &&
  2445. date.month() != view.intervalStart.month()
  2446. ) {
  2447. classes.push('fc-other-month');
  2448. }
  2449. if (date.isSame(today, 'day')) {
  2450. classes.push(
  2451. 'fc-today',
  2452. view.highlightStateClass
  2453. );
  2454. }
  2455. else if (date < today) {
  2456. classes.push('fc-past');
  2457. }
  2458. else {
  2459. classes.push('fc-future');
  2460. }
  2461. return classes;
  2462. }
  2463. });
  2464. /* Event-rendering and event-interaction methods for the abstract Grid class
  2465. ----------------------------------------------------------------------------------------------------------------------*/
  2466. Grid.mixin({
  2467. mousedOverSeg: null, // the segment object the user's mouse is over. null if over nothing
  2468. isDraggingSeg: false, // is a segment being dragged? boolean
  2469. isResizingSeg: false, // is a segment being resized? boolean
  2470. segs: null, // the event segments currently rendered in the grid
  2471. // Renders the given events onto the grid
  2472. renderEvents: function(events) {
  2473. var segs = this.eventsToSegs(events);
  2474. var bgSegs = [];
  2475. var fgSegs = [];
  2476. var i, seg;
  2477. for (i = 0; i < segs.length; i++) {
  2478. seg = segs[i];
  2479. if (isBgEvent(seg.event)) {
  2480. bgSegs.push(seg);
  2481. }
  2482. else {
  2483. fgSegs.push(seg);
  2484. }
  2485. }
  2486. // Render each different type of segment.
  2487. // Each function may return a subset of the segs, segs that were actually rendered.
  2488. bgSegs = this.renderBgSegs(bgSegs) || bgSegs;
  2489. fgSegs = this.renderFgSegs(fgSegs) || fgSegs;
  2490. this.segs = bgSegs.concat(fgSegs);
  2491. },
  2492. // Unrenders all events currently rendered on the grid
  2493. destroyEvents: function() {
  2494. this.triggerSegMouseout(); // trigger an eventMouseout if user's mouse is over an event
  2495. this.destroyFgSegs();
  2496. this.destroyBgSegs();
  2497. this.segs = null;
  2498. },
  2499. // Retrieves all rendered segment objects currently rendered on the grid
  2500. getEventSegs: function() {
  2501. return this.segs || [];
  2502. },
  2503. /* Foreground Segment Rendering
  2504. ------------------------------------------------------------------------------------------------------------------*/
  2505. // Renders foreground event segments onto the grid. May return a subset of segs that were rendered.
  2506. renderFgSegs: function(segs) {
  2507. // subclasses must implement
  2508. },
  2509. // Unrenders all currently rendered foreground segments
  2510. destroyFgSegs: function() {
  2511. // subclasses must implement
  2512. },
  2513. // Renders and assigns an `el` property for each foreground event segment.
  2514. // Only returns segments that successfully rendered.
  2515. // A utility that subclasses may use.
  2516. renderFgSegEls: function(segs, disableResizing) {
  2517. var view = this.view;
  2518. var html = '';
  2519. var renderedSegs = [];
  2520. var i;
  2521. if (segs.length) { // don't build an empty html string
  2522. // build a large concatenation of event segment HTML
  2523. for (i = 0; i < segs.length; i++) {
  2524. html += this.fgSegHtml(segs[i], disableResizing);
  2525. }
  2526. // Grab individual elements from the combined HTML string. Use each as the default rendering.
  2527. // Then, compute the 'el' for each segment. An el might be null if the eventRender callback returned false.
  2528. $(html).each(function(i, node) {
  2529. var seg = segs[i];
  2530. var el = view.resolveEventEl(seg.event, $(node));
  2531. if (el) {
  2532. el.data('fc-seg', seg); // used by handlers
  2533. seg.el = el;
  2534. renderedSegs.push(seg);
  2535. }
  2536. });
  2537. }
  2538. return renderedSegs;
  2539. },
  2540. // Generates the HTML for the default rendering of a foreground event segment. Used by renderFgSegEls()
  2541. fgSegHtml: function(seg, disableResizing) {
  2542. // subclasses should implement
  2543. },
  2544. /* Background Segment Rendering
  2545. ------------------------------------------------------------------------------------------------------------------*/
  2546. // Renders the given background event segments onto the grid.
  2547. // Returns a subset of the segs that were actually rendered.
  2548. renderBgSegs: function(segs) {
  2549. return this.renderFill('bgEvent', segs);
  2550. },
  2551. // Unrenders all the currently rendered background event segments
  2552. destroyBgSegs: function() {
  2553. this.destroyFill('bgEvent');
  2554. },
  2555. // Renders a background event element, given the default rendering. Called by the fill system.
  2556. bgEventSegEl: function(seg, el) {
  2557. return this.view.resolveEventEl(seg.event, el); // will filter through eventRender
  2558. },
  2559. // Generates an array of classNames to be used for the default rendering of a background event.
  2560. // Called by the fill system.
  2561. bgEventSegClasses: function(seg) {
  2562. var event = seg.event;
  2563. var source = event.source || {};
  2564. return [ 'fc-bgevent' ].concat(
  2565. event.className,
  2566. source.className || []
  2567. );
  2568. },
  2569. // Generates a semicolon-separated CSS string to be used for the default rendering of a background event.
  2570. // Called by the fill system.
  2571. // TODO: consolidate with getEventSkinCss?
  2572. bgEventSegStyles: function(seg) {
  2573. var view = this.view;
  2574. var event = seg.event;
  2575. var source = event.source || {};
  2576. var eventColor = event.color;
  2577. var sourceColor = source.color;
  2578. var optionColor = view.opt('eventColor');
  2579. var backgroundColor =
  2580. event.backgroundColor ||
  2581. eventColor ||
  2582. source.backgroundColor ||
  2583. sourceColor ||
  2584. view.opt('eventBackgroundColor') ||
  2585. optionColor;
  2586. if (backgroundColor) {
  2587. return 'background-color:' + backgroundColor;
  2588. }
  2589. return '';
  2590. },
  2591. // Generates an array of classNames to be used for the rendering business hours overlay. Called by the fill system.
  2592. businessHoursSegClasses: function(seg) {
  2593. return [ 'fc-nonbusiness', 'fc-bgevent' ];
  2594. },
  2595. /* Handlers
  2596. ------------------------------------------------------------------------------------------------------------------*/
  2597. // Attaches event-element-related handlers to the container element and leverage bubbling
  2598. bindSegHandlers: function() {
  2599. var _this = this;
  2600. var view = this.view;
  2601. $.each(
  2602. {
  2603. mouseenter: function(seg, ev) {
  2604. _this.triggerSegMouseover(seg, ev);
  2605. },
  2606. mouseleave: function(seg, ev) {
  2607. _this.triggerSegMouseout(seg, ev);
  2608. },
  2609. click: function(seg, ev) {
  2610. return view.trigger('eventClick', this, seg.event, ev); // can return `false` to cancel
  2611. },
  2612. mousedown: function(seg, ev) {
  2613. if ($(ev.target).is('.fc-resizer') && view.isEventResizable(seg.event)) {
  2614. _this.segResizeMousedown(seg, ev);
  2615. }
  2616. else if (view.isEventDraggable(seg.event)) {
  2617. _this.segDragMousedown(seg, ev);
  2618. }
  2619. }
  2620. },
  2621. function(name, func) {
  2622. // attach the handler to the container element and only listen for real event elements via bubbling
  2623. _this.el.on(name, '.fc-event-container > *', function(ev) {
  2624. var seg = $(this).data('fc-seg'); // grab segment data. put there by View::renderEvents
  2625. // only call the handlers if there is not a drag/resize in progress
  2626. if (seg && !_this.isDraggingSeg && !_this.isResizingSeg) {
  2627. return func.call(this, seg, ev); // `this` will be the event element
  2628. }
  2629. });
  2630. }
  2631. );
  2632. },
  2633. // Updates internal state and triggers handlers for when an event element is moused over
  2634. triggerSegMouseover: function(seg, ev) {
  2635. if (!this.mousedOverSeg) {
  2636. this.mousedOverSeg = seg;
  2637. this.view.trigger('eventMouseover', seg.el[0], seg.event, ev);
  2638. }
  2639. },
  2640. // Updates internal state and triggers handlers for when an event element is moused out.
  2641. // Can be given no arguments, in which case it will mouseout the segment that was previously moused over.
  2642. triggerSegMouseout: function(seg, ev) {
  2643. ev = ev || {}; // if given no args, make a mock mouse event
  2644. if (this.mousedOverSeg) {
  2645. seg = seg || this.mousedOverSeg; // if given no args, use the currently moused-over segment
  2646. this.mousedOverSeg = null;
  2647. this.view.trigger('eventMouseout', seg.el[0], seg.event, ev);
  2648. }
  2649. },
  2650. /* Event Dragging
  2651. ------------------------------------------------------------------------------------------------------------------*/
  2652. // Called when the user does a mousedown on an event, which might lead to dragging.
  2653. // Generic enough to work with any type of Grid.
  2654. segDragMousedown: function(seg, ev) {
  2655. var _this = this;
  2656. var view = this.view;
  2657. var el = seg.el;
  2658. var event = seg.event;
  2659. var dropLocation;
  2660. // A clone of the original element that will move with the mouse
  2661. var mouseFollower = new MouseFollower(seg.el, {
  2662. parentEl: view.el,
  2663. opacity: view.opt('dragOpacity'),
  2664. revertDuration: view.opt('dragRevertDuration'),
  2665. zIndex: 2 // one above the .fc-view
  2666. });
  2667. // Tracks mouse movement over the *view's* coordinate map. Allows dragging and dropping between subcomponents
  2668. // of the view.
  2669. var dragListener = new DragListener(view.coordMap, {
  2670. distance: 5,
  2671. scroll: view.opt('dragScroll'),
  2672. listenStart: function(ev) {
  2673. mouseFollower.hide(); // don't show until we know this is a real drag
  2674. mouseFollower.start(ev);
  2675. },
  2676. dragStart: function(ev) {
  2677. _this.triggerSegMouseout(seg, ev); // ensure a mouseout on the manipulated event has been reported
  2678. _this.isDraggingSeg = true;
  2679. view.hideEvent(event); // hide all event segments. our mouseFollower will take over
  2680. view.trigger('eventDragStart', el[0], event, ev, {}); // last argument is jqui dummy
  2681. },
  2682. cellOver: function(cell, isOrig) {
  2683. var origCell = seg.cell || dragListener.origCell; // starting cell could be forced (DayGrid.limit)
  2684. dropLocation = _this.computeEventDrop(origCell, cell, event);
  2685. if (dropLocation) {
  2686. if (view.renderDrag(dropLocation, seg)) { // have the subclass render a visual indication
  2687. mouseFollower.hide(); // if the subclass is already using a mock event "helper", hide our own
  2688. }
  2689. else {
  2690. mouseFollower.show();
  2691. }
  2692. if (isOrig) {
  2693. dropLocation = null; // needs to have moved cells to be a valid drop
  2694. }
  2695. }
  2696. else {
  2697. // have the helper follow the mouse (no snapping) with a warning-style cursor
  2698. mouseFollower.show();
  2699. disableCursor();
  2700. }
  2701. },
  2702. cellOut: function() { // called before mouse moves to a different cell OR moved out of all cells
  2703. dropLocation = null;
  2704. view.destroyDrag(); // unrender whatever was done in renderDrag
  2705. mouseFollower.show(); // show in case we are moving out of all cells
  2706. enableCursor();
  2707. },
  2708. dragStop: function(ev) {
  2709. // do revert animation if hasn't changed. calls a callback when finished (whether animation or not)
  2710. mouseFollower.stop(!dropLocation, function() {
  2711. _this.isDraggingSeg = false;
  2712. view.destroyDrag();
  2713. view.showEvent(event);
  2714. view.trigger('eventDragStop', el[0], event, ev, {}); // last argument is jqui dummy
  2715. if (dropLocation) {
  2716. view.reportEventDrop(event, dropLocation, el, ev);
  2717. }
  2718. });
  2719. enableCursor();
  2720. },
  2721. listenStop: function() {
  2722. mouseFollower.stop(); // put in listenStop in case there was a mousedown but the drag never started
  2723. }
  2724. });
  2725. dragListener.mousedown(ev); // start listening, which will eventually lead to a dragStart
  2726. },
  2727. // Given the cell an event drag began, and the cell event was dropped, calculates the new start/end/allDay
  2728. // values for the event. Subclasses may override and set additional properties to be used by renderDrag.
  2729. // A falsy returned value indicates an invalid drop.
  2730. computeEventDrop: function(startCell, endCell, event) {
  2731. var dragStart = startCell.start;
  2732. var dragEnd = endCell.start;
  2733. var delta;
  2734. var newStart;
  2735. var newEnd;
  2736. var newAllDay;
  2737. var dropLocation;
  2738. if (dragStart.hasTime() === dragEnd.hasTime()) {
  2739. delta = diffDayTime(dragEnd, dragStart);
  2740. newStart = event.start.clone().add(delta);
  2741. if (event.end === null) { // do we need to compute an end?
  2742. newEnd = null;
  2743. }
  2744. else {
  2745. newEnd = event.end.clone().add(delta);
  2746. }
  2747. newAllDay = event.allDay; // keep it the same
  2748. }
  2749. else {
  2750. // if switching from day <-> timed, start should be reset to the dropped date, and the end cleared
  2751. newStart = dragEnd.clone();
  2752. newEnd = null; // end should be cleared
  2753. newAllDay = !dragEnd.hasTime();
  2754. }
  2755. dropLocation = {
  2756. start: newStart,
  2757. end: newEnd,
  2758. allDay: newAllDay
  2759. };
  2760. if (!this.view.calendar.isEventRangeAllowed(dropLocation, event)) {
  2761. return null;
  2762. }
  2763. return dropLocation;
  2764. },
  2765. /* External Element Dragging
  2766. ------------------------------------------------------------------------------------------------------------------*/
  2767. // Called when a jQuery UI drag is initiated anywhere in the DOM
  2768. documentDragStart: function(ev, ui) {
  2769. var view = this.view;
  2770. var el;
  2771. var accept;
  2772. if (view.opt('droppable')) { // only listen if this setting is on
  2773. el = $(ev.target);
  2774. // Test that the dragged element passes the dropAccept selector or filter function.
  2775. // FYI, the default is "*" (matches all)
  2776. accept = view.opt('dropAccept');
  2777. if ($.isFunction(accept) ? accept.call(el[0], el) : el.is(accept)) {
  2778. this.startExternalDrag(el, ev, ui);
  2779. }
  2780. }
  2781. },
  2782. // Called when a jQuery UI drag starts and it needs to be monitored for cell dropping
  2783. startExternalDrag: function(el, ev, ui) {
  2784. var _this = this;
  2785. var meta = getDraggedElMeta(el); // extra data about event drop, including possible event to create
  2786. var dragListener;
  2787. var dropLocation; // a null value signals an unsuccessful drag
  2788. // listener that tracks mouse movement over date-associated pixel regions
  2789. dragListener = new DragListener(this.coordMap, {
  2790. cellOver: function(cell) {
  2791. dropLocation = _this.computeExternalDrop(cell, meta);
  2792. if (dropLocation) {
  2793. _this.renderDrag(dropLocation); // called without a seg parameter
  2794. }
  2795. else { // invalid drop cell
  2796. disableCursor();
  2797. }
  2798. },
  2799. cellOut: function() {
  2800. dropLocation = null; // signal unsuccessful
  2801. _this.destroyDrag();
  2802. enableCursor();
  2803. }
  2804. });
  2805. // gets called, only once, when jqui drag is finished
  2806. $(document).one('dragstop', function(ev, ui) {
  2807. _this.destroyDrag();
  2808. enableCursor();
  2809. if (dropLocation) { // element was dropped on a valid date/time cell
  2810. _this.view.reportExternalDrop(meta, dropLocation, el, ev, ui);
  2811. }
  2812. });
  2813. dragListener.startDrag(ev); // start listening immediately
  2814. },
  2815. // Given a cell to be dropped upon, and misc data associated with the jqui drag (guaranteed to be a plain object),
  2816. // returns start/end dates for the event that would result from the hypothetical drop. end might be null.
  2817. // Returning a null value signals an invalid drop cell.
  2818. computeExternalDrop: function(cell, meta) {
  2819. var dropLocation = {
  2820. start: cell.start.clone(),
  2821. end: null
  2822. };
  2823. // if dropped on an all-day cell, and element's metadata specified a time, set it
  2824. if (meta.startTime && !dropLocation.start.hasTime()) {
  2825. dropLocation.start.time(meta.startTime);
  2826. }
  2827. if (meta.duration) {
  2828. dropLocation.end = dropLocation.start.clone().add(meta.duration);
  2829. }
  2830. if (!this.view.calendar.isExternalDropRangeAllowed(dropLocation, meta.eventProps)) {
  2831. return null;
  2832. }
  2833. return dropLocation;
  2834. },
  2835. /* Drag Rendering (for both events and an external elements)
  2836. ------------------------------------------------------------------------------------------------------------------*/
  2837. // Renders a visual indication of an event or external element being dragged.
  2838. // `dropLocation` contains hypothetical start/end/allDay values the event would have if dropped. end can be null.
  2839. // `seg` is the internal segment object that is being dragged. If dragging an external element, `seg` is null.
  2840. // A truthy returned value indicates this method has rendered a helper element.
  2841. renderDrag: function(dropLocation, seg) {
  2842. // subclasses must implement
  2843. },
  2844. // Unrenders a visual indication of an event or external element being dragged
  2845. destroyDrag: function() {
  2846. // subclasses must implement
  2847. },
  2848. /* Resizing
  2849. ------------------------------------------------------------------------------------------------------------------*/
  2850. // Called when the user does a mousedown on an event's resizer, which might lead to resizing.
  2851. // Generic enough to work with any type of Grid.
  2852. segResizeMousedown: function(seg, ev) {
  2853. var _this = this;
  2854. var view = this.view;
  2855. var calendar = view.calendar;
  2856. var el = seg.el;
  2857. var event = seg.event;
  2858. var start = event.start;
  2859. var oldEnd = calendar.getEventEnd(event);
  2860. var newEnd; // falsy if invalid resize
  2861. var dragListener;
  2862. function destroy() { // resets the rendering to show the original event
  2863. _this.destroyEventResize();
  2864. view.showEvent(event);
  2865. enableCursor();
  2866. }
  2867. // Tracks mouse movement over the *grid's* coordinate map
  2868. dragListener = new DragListener(this.coordMap, {
  2869. distance: 5,
  2870. scroll: view.opt('dragScroll'),
  2871. dragStart: function(ev) {
  2872. _this.triggerSegMouseout(seg, ev); // ensure a mouseout on the manipulated event has been reported
  2873. _this.isResizingSeg = true;
  2874. view.trigger('eventResizeStart', el[0], event, ev, {}); // last argument is jqui dummy
  2875. },
  2876. cellOver: function(cell) {
  2877. newEnd = cell.end;
  2878. if (!newEnd.isAfter(start)) { // was end moved before start?
  2879. newEnd = start.clone().add( // make the event span a single slot
  2880. diffDayTime(cell.end, cell.start) // assumes all slot durations are the same
  2881. );
  2882. }
  2883. if (newEnd.isSame(oldEnd)) {
  2884. newEnd = null;
  2885. }
  2886. else if (!calendar.isEventRangeAllowed({ start: start, end: newEnd }, event)) {
  2887. newEnd = null;
  2888. disableCursor();
  2889. }
  2890. else {
  2891. _this.renderEventResize({ start: start, end: newEnd }, seg);
  2892. view.hideEvent(event);
  2893. }
  2894. },
  2895. cellOut: function() { // called before mouse moves to a different cell OR moved out of all cells
  2896. newEnd = null;
  2897. destroy();
  2898. },
  2899. dragStop: function(ev) {
  2900. _this.isResizingSeg = false;
  2901. destroy();
  2902. view.trigger('eventResizeStop', el[0], event, ev, {}); // last argument is jqui dummy
  2903. if (newEnd) { // valid date to resize to?
  2904. view.reportEventResize(event, newEnd, el, ev);
  2905. }
  2906. }
  2907. });
  2908. dragListener.mousedown(ev); // start listening, which will eventually lead to a dragStart
  2909. },
  2910. // Renders a visual indication of an event being resized.
  2911. // `range` has the updated dates of the event. `seg` is the original segment object involved in the drag.
  2912. renderEventResize: function(range, seg) {
  2913. // subclasses must implement
  2914. },
  2915. // Unrenders a visual indication of an event being resized.
  2916. destroyEventResize: function() {
  2917. // subclasses must implement
  2918. },
  2919. /* Rendering Utils
  2920. ------------------------------------------------------------------------------------------------------------------*/
  2921. // Compute the text that should be displayed on an event's element.
  2922. // `range` can be the Event object itself, or something range-like, with at least a `start`.
  2923. // The `timeFormat` options and the grid's default format is used, but `formatStr` can override.
  2924. getEventTimeText: function(range, formatStr) {
  2925. formatStr = formatStr || this.eventTimeFormat;
  2926. if (range.end && this.displayEventEnd) {
  2927. return this.view.formatRange(range, formatStr);
  2928. }
  2929. else {
  2930. return range.start.format(formatStr);
  2931. }
  2932. },
  2933. // Generic utility for generating the HTML classNames for an event segment's element
  2934. getSegClasses: function(seg, isDraggable, isResizable) {
  2935. var event = seg.event;
  2936. var classes = [
  2937. 'fc-event',
  2938. seg.isStart ? 'fc-start' : 'fc-not-start',
  2939. seg.isEnd ? 'fc-end' : 'fc-not-end'
  2940. ].concat(
  2941. event.className,
  2942. event.source ? event.source.className : []
  2943. );
  2944. if (isDraggable) {
  2945. classes.push('fc-draggable');
  2946. }
  2947. if (isResizable) {
  2948. classes.push('fc-resizable');
  2949. }
  2950. return classes;
  2951. },
  2952. // Utility for generating a CSS string with all the event skin-related properties
  2953. getEventSkinCss: function(event) {
  2954. var view = this.view;
  2955. var source = event.source || {};
  2956. var eventColor = event.color;
  2957. var sourceColor = source.color;
  2958. var optionColor = view.opt('eventColor');
  2959. var backgroundColor =
  2960. event.backgroundColor ||
  2961. eventColor ||
  2962. source.backgroundColor ||
  2963. sourceColor ||
  2964. view.opt('eventBackgroundColor') ||
  2965. optionColor;
  2966. var borderColor =
  2967. event.borderColor ||
  2968. eventColor ||
  2969. source.borderColor ||
  2970. sourceColor ||
  2971. view.opt('eventBorderColor') ||
  2972. optionColor;
  2973. var textColor =
  2974. event.textColor ||
  2975. source.textColor ||
  2976. view.opt('eventTextColor');
  2977. var statements = [];
  2978. if (backgroundColor) {
  2979. statements.push('background-color:' + backgroundColor);
  2980. }
  2981. if (borderColor) {
  2982. statements.push('border-color:' + borderColor);
  2983. }
  2984. if (textColor) {
  2985. statements.push('color:' + textColor);
  2986. }
  2987. return statements.join(';');
  2988. },
  2989. /* Converting events -> ranges -> segs
  2990. ------------------------------------------------------------------------------------------------------------------*/
  2991. // Converts an array of event objects into an array of event segment objects.
  2992. // A custom `rangeToSegsFunc` may be given for arbitrarily slicing up events.
  2993. eventsToSegs: function(events, rangeToSegsFunc) {
  2994. var eventRanges = this.eventsToRanges(events);
  2995. var segs = [];
  2996. var i;
  2997. for (i = 0; i < eventRanges.length; i++) {
  2998. segs.push.apply(
  2999. segs,
  3000. this.eventRangeToSegs(eventRanges[i], rangeToSegsFunc)
  3001. );
  3002. }
  3003. return segs;
  3004. },
  3005. // Converts an array of events into an array of "range" objects.
  3006. // A "range" object is a plain object with start/end properties denoting the time it covers. Also an event property.
  3007. // For "normal" events, this will be identical to the event's start/end, but for "inverse-background" events,
  3008. // will create an array of ranges that span the time *not* covered by the given event.
  3009. eventsToRanges: function(events) {
  3010. var _this = this;
  3011. var eventsById = groupEventsById(events);
  3012. var ranges = [];
  3013. // group by ID so that related inverse-background events can be rendered together
  3014. $.each(eventsById, function(id, eventGroup) {
  3015. if (eventGroup.length) {
  3016. ranges.push.apply(
  3017. ranges,
  3018. isInverseBgEvent(eventGroup[0]) ?
  3019. _this.eventsToInverseRanges(eventGroup) :
  3020. _this.eventsToNormalRanges(eventGroup)
  3021. );
  3022. }
  3023. });
  3024. return ranges;
  3025. },
  3026. // Converts an array of "normal" events (not inverted rendering) into a parallel array of ranges
  3027. eventsToNormalRanges: function(events) {
  3028. var calendar = this.view.calendar;
  3029. var ranges = [];
  3030. var i, event;
  3031. var eventStart, eventEnd;
  3032. for (i = 0; i < events.length; i++) {
  3033. event = events[i];
  3034. // make copies and normalize by stripping timezone
  3035. eventStart = event.start.clone().stripZone();
  3036. eventEnd = calendar.getEventEnd(event).stripZone();
  3037. ranges.push({
  3038. event: event,
  3039. start: eventStart,
  3040. end: eventEnd,
  3041. eventStartMS: +eventStart,
  3042. eventDurationMS: eventEnd - eventStart
  3043. });
  3044. }
  3045. return ranges;
  3046. },
  3047. // Converts an array of events, with inverse-background rendering, into an array of range objects.
  3048. // The range objects will cover all the time NOT covered by the events.
  3049. eventsToInverseRanges: function(events) {
  3050. var view = this.view;
  3051. var viewStart = view.start.clone().stripZone(); // normalize timezone
  3052. var viewEnd = view.end.clone().stripZone(); // normalize timezone
  3053. var normalRanges = this.eventsToNormalRanges(events); // will give us normalized dates we can use w/o copies
  3054. var inverseRanges = [];
  3055. var event0 = events[0]; // assign this to each range's `.event`
  3056. var start = viewStart; // the end of the previous range. the start of the new range
  3057. var i, normalRange;
  3058. // ranges need to be in order. required for our date-walking algorithm
  3059. normalRanges.sort(compareNormalRanges);
  3060. for (i = 0; i < normalRanges.length; i++) {
  3061. normalRange = normalRanges[i];
  3062. // add the span of time before the event (if there is any)
  3063. if (normalRange.start > start) { // compare millisecond time (skip any ambig logic)
  3064. inverseRanges.push({
  3065. event: event0,
  3066. start: start,
  3067. end: normalRange.start
  3068. });
  3069. }
  3070. start = normalRange.end;
  3071. }
  3072. // add the span of time after the last event (if there is any)
  3073. if (start < viewEnd) { // compare millisecond time (skip any ambig logic)
  3074. inverseRanges.push({
  3075. event: event0,
  3076. start: start,
  3077. end: viewEnd
  3078. });
  3079. }
  3080. return inverseRanges;
  3081. },
  3082. // Slices the given event range into one or more segment objects.
  3083. // A `rangeToSegsFunc` custom slicing function can be given.
  3084. eventRangeToSegs: function(eventRange, rangeToSegsFunc) {
  3085. var segs;
  3086. var i, seg;
  3087. if (rangeToSegsFunc) {
  3088. segs = rangeToSegsFunc(eventRange);
  3089. }
  3090. else {
  3091. segs = this.rangeToSegs(eventRange); // defined by the subclass
  3092. }
  3093. for (i = 0; i < segs.length; i++) {
  3094. seg = segs[i];
  3095. seg.event = eventRange.event;
  3096. seg.eventStartMS = eventRange.eventStartMS;
  3097. seg.eventDurationMS = eventRange.eventDurationMS;
  3098. }
  3099. return segs;
  3100. }
  3101. });
  3102. /* Utilities
  3103. ----------------------------------------------------------------------------------------------------------------------*/
  3104. function isBgEvent(event) { // returns true if background OR inverse-background
  3105. var rendering = getEventRendering(event);
  3106. return rendering === 'background' || rendering === 'inverse-background';
  3107. }
  3108. function isInverseBgEvent(event) {
  3109. return getEventRendering(event) === 'inverse-background';
  3110. }
  3111. function getEventRendering(event) {
  3112. return firstDefined((event.source || {}).rendering, event.rendering);
  3113. }
  3114. function groupEventsById(events) {
  3115. var eventsById = {};
  3116. var i, event;
  3117. for (i = 0; i < events.length; i++) {
  3118. event = events[i];
  3119. (eventsById[event._id] || (eventsById[event._id] = [])).push(event);
  3120. }
  3121. return eventsById;
  3122. }
  3123. // A cmp function for determining which non-inverted "ranges" (see above) happen earlier
  3124. function compareNormalRanges(range1, range2) {
  3125. return range1.eventStartMS - range2.eventStartMS; // earlier ranges go first
  3126. }
  3127. // A cmp function for determining which segments should take visual priority
  3128. // DOES NOT WORK ON INVERTED BACKGROUND EVENTS because they have no eventStartMS/eventDurationMS
  3129. function compareSegs(seg1, seg2) {
  3130. return seg1.eventStartMS - seg2.eventStartMS || // earlier events go first
  3131. seg2.eventDurationMS - seg1.eventDurationMS || // tie? longer events go first
  3132. seg2.event.allDay - seg1.event.allDay || // tie? put all-day events first (booleans cast to 0/1)
  3133. (seg1.event.title || '').localeCompare(seg2.event.title); // tie? alphabetically by title
  3134. }
  3135. fc.compareSegs = compareSegs; // export
  3136. /* External-Dragging-Element Data
  3137. ----------------------------------------------------------------------------------------------------------------------*/
  3138. // Require all HTML5 data-* attributes used by FullCalendar to have this prefix.
  3139. // A value of '' will query attributes like data-event. A value of 'fc' will query attributes like data-fc-event.
  3140. fc.dataAttrPrefix = '';
  3141. // Given a jQuery element that might represent a dragged FullCalendar event, returns an intermediate data structure
  3142. // to be used for Event Object creation.
  3143. // A defined `.eventProps`, even when empty, indicates that an event should be created.
  3144. function getDraggedElMeta(el) {
  3145. var prefix = fc.dataAttrPrefix;
  3146. var eventProps; // properties for creating the event, not related to date/time
  3147. var startTime; // a Duration
  3148. var duration;
  3149. var stick;
  3150. if (prefix) { prefix += '-'; }
  3151. eventProps = el.data(prefix + 'event') || null;
  3152. if (eventProps) {
  3153. if (typeof eventProps === 'object') {
  3154. eventProps = $.extend({}, eventProps); // make a copy
  3155. }
  3156. else { // something like 1 or true. still signal event creation
  3157. eventProps = {};
  3158. }
  3159. // pluck special-cased date/time properties
  3160. startTime = eventProps.start;
  3161. if (startTime == null) { startTime = eventProps.time; } // accept 'time' as well
  3162. duration = eventProps.duration;
  3163. stick = eventProps.stick;
  3164. delete eventProps.start;
  3165. delete eventProps.time;
  3166. delete eventProps.duration;
  3167. delete eventProps.stick;
  3168. }
  3169. // fallback to standalone attribute values for each of the date/time properties
  3170. if (startTime == null) { startTime = el.data(prefix + 'start'); }
  3171. if (startTime == null) { startTime = el.data(prefix + 'time'); } // accept 'time' as well
  3172. if (duration == null) { duration = el.data(prefix + 'duration'); }
  3173. if (stick == null) { stick = el.data(prefix + 'stick'); }
  3174. // massage into correct data types
  3175. startTime = startTime != null ? moment.duration(startTime) : null;
  3176. duration = duration != null ? moment.duration(duration) : null;
  3177. stick = Boolean(stick);
  3178. return { eventProps: eventProps, startTime: startTime, duration: duration, stick: stick };
  3179. }
  3180. /* A component that renders a grid of whole-days that runs horizontally. There can be multiple rows, one per week.
  3181. ----------------------------------------------------------------------------------------------------------------------*/
  3182. var DayGrid = Grid.extend({
  3183. numbersVisible: false, // should render a row for day/week numbers? set by outside view. TODO: make internal
  3184. bottomCoordPadding: 0, // hack for extending the hit area for the last row of the coordinate grid
  3185. breakOnWeeks: null, // should create a new row for each week? set by outside view
  3186. cellDates: null, // flat chronological array of each cell's dates
  3187. dayToCellOffsets: null, // maps days offsets from grid's start date, to cell offsets
  3188. rowEls: null, // set of fake row elements
  3189. dayEls: null, // set of whole-day elements comprising the row's background
  3190. helperEls: null, // set of cell skeleton elements for rendering the mock event "helper"
  3191. // Renders the rows and columns into the component's `this.el`, which should already be assigned.
  3192. // isRigid determins whether the individual rows should ignore the contents and be a constant height.
  3193. // Relies on the view's colCnt and rowCnt. In the future, this component should probably be self-sufficient.
  3194. render: function(isRigid) {
  3195. var view = this.view;
  3196. var rowCnt = this.rowCnt;
  3197. var colCnt = this.colCnt;
  3198. var cellCnt = rowCnt * colCnt;
  3199. var html = '';
  3200. var row;
  3201. var i, cell;
  3202. for (row = 0; row < rowCnt; row++) {
  3203. html += this.dayRowHtml(row, isRigid);
  3204. }
  3205. this.el.html(html);
  3206. this.rowEls = this.el.find('.fc-row');
  3207. this.dayEls = this.el.find('.fc-day');
  3208. // trigger dayRender with each cell's element
  3209. for (i = 0; i < cellCnt; i++) {
  3210. cell = this.getCell(i);
  3211. view.trigger('dayRender', null, cell.start, this.dayEls.eq(i));
  3212. }
  3213. Grid.prototype.render.call(this); // call the super-method
  3214. },
  3215. destroy: function() {
  3216. this.destroySegPopover();
  3217. Grid.prototype.destroy.call(this); // call the super-method
  3218. },
  3219. // Generates the HTML for a single row. `row` is the row number.
  3220. dayRowHtml: function(row, isRigid) {
  3221. var view = this.view;
  3222. var classes = [ 'fc-row', 'fc-week', view.widgetContentClass ];
  3223. if (isRigid) {
  3224. classes.push('fc-rigid');
  3225. }
  3226. return '' +
  3227. '<div class="' + classes.join(' ') + '">' +
  3228. '<div class="fc-bg">' +
  3229. '<table>' +
  3230. this.rowHtml('day', row) + // leverages RowRenderer. calls dayCellHtml()
  3231. '</table>' +
  3232. '</div>' +
  3233. '<div class="fc-content-skeleton">' +
  3234. '<table>' +
  3235. (this.numbersVisible ?
  3236. '<thead>' +
  3237. this.rowHtml('number', row) + // leverages RowRenderer. View will define render method
  3238. '</thead>' :
  3239. ''
  3240. ) +
  3241. '</table>' +
  3242. '</div>' +
  3243. '</div>';
  3244. },
  3245. // Renders the HTML for a whole-day cell. Will eventually end up in the day-row's background.
  3246. // We go through a 'day' row type instead of just doing a 'bg' row type so that the View can do custom rendering
  3247. // specifically for whole-day rows, whereas a 'bg' might also be used for other purposes (TimeGrid bg for example).
  3248. dayCellHtml: function(cell) {
  3249. return this.bgCellHtml(cell);
  3250. },
  3251. /* Options
  3252. ------------------------------------------------------------------------------------------------------------------*/
  3253. // Computes a default column header formatting string if `colFormat` is not explicitly defined
  3254. computeColHeadFormat: function() {
  3255. if (this.rowCnt > 1) { // more than one week row. day numbers will be in each cell
  3256. return 'ddd'; // "Sat"
  3257. }
  3258. else if (this.colCnt > 1) { // multiple days, so full single date string WON'T be in title text
  3259. return this.view.opt('dayOfMonthFormat'); // "Sat 12/10"
  3260. }
  3261. else { // single day, so full single date string will probably be in title text
  3262. return 'dddd'; // "Saturday"
  3263. }
  3264. },
  3265. // Computes a default event time formatting string if `timeFormat` is not explicitly defined
  3266. computeEventTimeFormat: function() {
  3267. return this.view.opt('extraSmallTimeFormat'); // like "6p" or "6:30p"
  3268. },
  3269. // Computes a default `displayEventEnd` value if one is not expliclty defined
  3270. computeDisplayEventEnd: function() {
  3271. return this.colCnt == 1; // we'll likely have space if there's only one day
  3272. },
  3273. /* Cell System
  3274. ------------------------------------------------------------------------------------------------------------------*/
  3275. // Initializes row/col information
  3276. updateCells: function() {
  3277. var cellDates;
  3278. var firstDay;
  3279. var rowCnt;
  3280. var colCnt;
  3281. this.updateCellDates(); // populates cellDates and dayToCellOffsets
  3282. cellDates = this.cellDates;
  3283. if (this.breakOnWeeks) {
  3284. // count columns until the day-of-week repeats
  3285. firstDay = cellDates[0].day();
  3286. for (colCnt = 1; colCnt < cellDates.length; colCnt++) {
  3287. if (cellDates[colCnt].day() == firstDay) {
  3288. break;
  3289. }
  3290. }
  3291. rowCnt = Math.ceil(cellDates.length / colCnt);
  3292. }
  3293. else {
  3294. rowCnt = 1;
  3295. colCnt = cellDates.length;
  3296. }
  3297. this.rowCnt = rowCnt;
  3298. this.colCnt = colCnt;
  3299. },
  3300. // Populates cellDates and dayToCellOffsets
  3301. updateCellDates: function() {
  3302. var view = this.view;
  3303. var date = this.start.clone();
  3304. var dates = [];
  3305. var offset = -1;
  3306. var offsets = [];
  3307. while (date.isBefore(this.end)) { // loop each day from start to end
  3308. if (view.isHiddenDay(date)) {
  3309. offsets.push(offset + 0.5); // mark that it's between offsets
  3310. }
  3311. else {
  3312. offset++;
  3313. offsets.push(offset);
  3314. dates.push(date.clone());
  3315. }
  3316. date.add(1, 'days');
  3317. }
  3318. this.cellDates = dates;
  3319. this.dayToCellOffsets = offsets;
  3320. },
  3321. // Given a cell object, generates a range object
  3322. computeCellRange: function(cell) {
  3323. var colCnt = this.colCnt;
  3324. var index = cell.row * colCnt + (this.isRTL ? colCnt - cell.col - 1 : cell.col);
  3325. var start = this.cellDates[index].clone();
  3326. var end = start.clone().add(1, 'day');
  3327. return { start: start, end: end };
  3328. },
  3329. // Retrieves the element representing the given row
  3330. getRowEl: function(row) {
  3331. return this.rowEls.eq(row);
  3332. },
  3333. // Retrieves the element representing the given column
  3334. getColEl: function(col) {
  3335. return this.dayEls.eq(col);
  3336. },
  3337. // Gets the whole-day element associated with the cell
  3338. getCellDayEl: function(cell) {
  3339. return this.dayEls.eq(cell.row * this.colCnt + cell.col);
  3340. },
  3341. // Overrides Grid's method for when row coordinates are computed
  3342. computeRowCoords: function() {
  3343. var rowCoords = Grid.prototype.computeRowCoords.call(this); // call the super-method
  3344. // hack for extending last row (used by AgendaView)
  3345. rowCoords[rowCoords.length - 1].bottom += this.bottomCoordPadding;
  3346. return rowCoords;
  3347. },
  3348. /* Dates
  3349. ------------------------------------------------------------------------------------------------------------------*/
  3350. // Slices up a date range by row into an array of segments
  3351. rangeToSegs: function(range) {
  3352. var isRTL = this.isRTL;
  3353. var rowCnt = this.rowCnt;
  3354. var colCnt = this.colCnt;
  3355. var segs = [];
  3356. var first, last; // inclusive cell-offset range for given range
  3357. var row;
  3358. var rowFirst, rowLast; // inclusive cell-offset range for current row
  3359. var isStart, isEnd;
  3360. var segFirst, segLast; // inclusive cell-offset range for segment
  3361. var seg;
  3362. range = this.view.computeDayRange(range); // make whole-day range, considering nextDayThreshold
  3363. first = this.dateToCellOffset(range.start);
  3364. last = this.dateToCellOffset(range.end.subtract(1, 'days')); // offset of inclusive end date
  3365. for (row = 0; row < rowCnt; row++) {
  3366. rowFirst = row * colCnt;
  3367. rowLast = rowFirst + colCnt - 1;
  3368. // intersect segment's offset range with the row's
  3369. segFirst = Math.max(rowFirst, first);
  3370. segLast = Math.min(rowLast, last);
  3371. // deal with in-between indices
  3372. segFirst = Math.ceil(segFirst); // in-between starts round to next cell
  3373. segLast = Math.floor(segLast); // in-between ends round to prev cell
  3374. if (segFirst <= segLast) { // was there any intersection with the current row?
  3375. // must be matching integers to be the segment's start/end
  3376. isStart = segFirst === first;
  3377. isEnd = segLast === last;
  3378. // translate offsets to be relative to start-of-row
  3379. segFirst -= rowFirst;
  3380. segLast -= rowFirst;
  3381. seg = { row: row, isStart: isStart, isEnd: isEnd };
  3382. if (isRTL) {
  3383. seg.leftCol = colCnt - segLast - 1;
  3384. seg.rightCol = colCnt - segFirst - 1;
  3385. }
  3386. else {
  3387. seg.leftCol = segFirst;
  3388. seg.rightCol = segLast;
  3389. }
  3390. segs.push(seg);
  3391. }
  3392. }
  3393. return segs;
  3394. },
  3395. // Given a date, returns its chronolocial cell-offset from the first cell of the grid.
  3396. // If the date lies between cells (because of hiddenDays), returns a floating-point value between offsets.
  3397. // If before the first offset, returns a negative number.
  3398. // If after the last offset, returns an offset past the last cell offset.
  3399. // Only works for *start* dates of cells. Will not work for exclusive end dates for cells.
  3400. dateToCellOffset: function(date) {
  3401. var offsets = this.dayToCellOffsets;
  3402. var day = date.diff(this.start, 'days');
  3403. if (day < 0) {
  3404. return offsets[0] - 1;
  3405. }
  3406. else if (day >= offsets.length) {
  3407. return offsets[offsets.length - 1] + 1;
  3408. }
  3409. else {
  3410. return offsets[day];
  3411. }
  3412. },
  3413. /* Event Drag Visualization
  3414. ------------------------------------------------------------------------------------------------------------------*/
  3415. // TODO: move to DayGrid.event, similar to what we did with Grid's drag methods
  3416. // Renders a visual indication of an event or external element being dragged.
  3417. // The dropLocation's end can be null. seg can be null. See Grid::renderDrag for more info.
  3418. renderDrag: function(dropLocation, seg) {
  3419. var opacity;
  3420. // always render a highlight underneath
  3421. this.renderHighlight(
  3422. this.view.calendar.ensureVisibleEventRange(dropLocation) // needs to be a proper range
  3423. );
  3424. // if a segment from the same calendar but another component is being dragged, render a helper event
  3425. if (seg && !seg.el.closest(this.el).length) {
  3426. this.renderRangeHelper(dropLocation, seg);
  3427. opacity = this.view.opt('dragOpacity');
  3428. if (opacity !== undefined) {
  3429. this.helperEls.css('opacity', opacity);
  3430. }
  3431. return true; // a helper has been rendered
  3432. }
  3433. },
  3434. // Unrenders any visual indication of a hovering event
  3435. destroyDrag: function() {
  3436. this.destroyHighlight();
  3437. this.destroyHelper();
  3438. },
  3439. /* Event Resize Visualization
  3440. ------------------------------------------------------------------------------------------------------------------*/
  3441. // Renders a visual indication of an event being resized
  3442. renderEventResize: function(range, seg) {
  3443. this.renderHighlight(range);
  3444. this.renderRangeHelper(range, seg);
  3445. },
  3446. // Unrenders a visual indication of an event being resized
  3447. destroyEventResize: function() {
  3448. this.destroyHighlight();
  3449. this.destroyHelper();
  3450. },
  3451. /* Event Helper
  3452. ------------------------------------------------------------------------------------------------------------------*/
  3453. // Renders a mock "helper" event. `sourceSeg` is the associated internal segment object. It can be null.
  3454. renderHelper: function(event, sourceSeg) {
  3455. var helperNodes = [];
  3456. var segs = this.eventsToSegs([ event ]);
  3457. var rowStructs;
  3458. segs = this.renderFgSegEls(segs); // assigns each seg's el and returns a subset of segs that were rendered
  3459. rowStructs = this.renderSegRows(segs);
  3460. // inject each new event skeleton into each associated row
  3461. this.rowEls.each(function(row, rowNode) {
  3462. var rowEl = $(rowNode); // the .fc-row
  3463. var skeletonEl = $('<div class="fc-helper-skeleton"><table/></div>'); // will be absolutely positioned
  3464. var skeletonTop;
  3465. // If there is an original segment, match the top position. Otherwise, put it at the row's top level
  3466. if (sourceSeg && sourceSeg.row === row) {
  3467. skeletonTop = sourceSeg.el.position().top;
  3468. }
  3469. else {
  3470. skeletonTop = rowEl.find('.fc-content-skeleton tbody').position().top;
  3471. }
  3472. skeletonEl.css('top', skeletonTop)
  3473. .find('table')
  3474. .append(rowStructs[row].tbodyEl);
  3475. rowEl.append(skeletonEl);
  3476. helperNodes.push(skeletonEl[0]);
  3477. });
  3478. this.helperEls = $(helperNodes); // array -> jQuery set
  3479. },
  3480. // Unrenders any visual indication of a mock helper event
  3481. destroyHelper: function() {
  3482. if (this.helperEls) {
  3483. this.helperEls.remove();
  3484. this.helperEls = null;
  3485. }
  3486. },
  3487. /* Fill System (highlight, background events, business hours)
  3488. ------------------------------------------------------------------------------------------------------------------*/
  3489. fillSegTag: 'td', // override the default tag name
  3490. // Renders a set of rectangles over the given segments of days.
  3491. // Only returns segments that successfully rendered.
  3492. renderFill: function(type, segs) {
  3493. var nodes = [];
  3494. var i, seg;
  3495. var skeletonEl;
  3496. segs = this.renderFillSegEls(type, segs); // assignes `.el` to each seg. returns successfully rendered segs
  3497. for (i = 0; i < segs.length; i++) {
  3498. seg = segs[i];
  3499. skeletonEl = this.renderFillRow(type, seg);
  3500. this.rowEls.eq(seg.row).append(skeletonEl);
  3501. nodes.push(skeletonEl[0]);
  3502. }
  3503. this.elsByFill[type] = $(nodes);
  3504. return segs;
  3505. },
  3506. // Generates the HTML needed for one row of a fill. Requires the seg's el to be rendered.
  3507. renderFillRow: function(type, seg) {
  3508. var colCnt = this.colCnt;
  3509. var startCol = seg.leftCol;
  3510. var endCol = seg.rightCol + 1;
  3511. var skeletonEl;
  3512. var trEl;
  3513. skeletonEl = $(
  3514. '<div class="fc-' + type.toLowerCase() + '-skeleton">' +
  3515. '<table><tr/></table>' +
  3516. '</div>'
  3517. );
  3518. trEl = skeletonEl.find('tr');
  3519. if (startCol > 0) {
  3520. trEl.append('<td colspan="' + startCol + '"/>');
  3521. }
  3522. trEl.append(
  3523. seg.el.attr('colspan', endCol - startCol)
  3524. );
  3525. if (endCol < colCnt) {
  3526. trEl.append('<td colspan="' + (colCnt - endCol) + '"/>');
  3527. }
  3528. this.bookendCells(trEl, type);
  3529. return skeletonEl;
  3530. }
  3531. });
  3532. /* Event-rendering methods for the DayGrid class
  3533. ----------------------------------------------------------------------------------------------------------------------*/
  3534. DayGrid.mixin({
  3535. rowStructs: null, // an array of objects, each holding information about a row's foreground event-rendering
  3536. // Unrenders all events currently rendered on the grid
  3537. destroyEvents: function() {
  3538. this.destroySegPopover(); // removes the "more.." events popover
  3539. Grid.prototype.destroyEvents.apply(this, arguments); // calls the super-method
  3540. },
  3541. // Retrieves all rendered segment objects currently rendered on the grid
  3542. getEventSegs: function() {
  3543. return Grid.prototype.getEventSegs.call(this) // get the segments from the super-method
  3544. .concat(this.popoverSegs || []); // append the segments from the "more..." popover
  3545. },
  3546. // Renders the given background event segments onto the grid
  3547. renderBgSegs: function(segs) {
  3548. // don't render timed background events
  3549. var allDaySegs = $.grep(segs, function(seg) {
  3550. return seg.event.allDay;
  3551. });
  3552. return Grid.prototype.renderBgSegs.call(this, allDaySegs); // call the super-method
  3553. },
  3554. // Renders the given foreground event segments onto the grid
  3555. renderFgSegs: function(segs) {
  3556. var rowStructs;
  3557. // render an `.el` on each seg
  3558. // returns a subset of the segs. segs that were actually rendered
  3559. segs = this.renderFgSegEls(segs);
  3560. rowStructs = this.rowStructs = this.renderSegRows(segs);
  3561. // append to each row's content skeleton
  3562. this.rowEls.each(function(i, rowNode) {
  3563. $(rowNode).find('.fc-content-skeleton > table').append(
  3564. rowStructs[i].tbodyEl
  3565. );
  3566. });
  3567. return segs; // return only the segs that were actually rendered
  3568. },
  3569. // Unrenders all currently rendered foreground event segments
  3570. destroyFgSegs: function() {
  3571. var rowStructs = this.rowStructs || [];
  3572. var rowStruct;
  3573. while ((rowStruct = rowStructs.pop())) {
  3574. rowStruct.tbodyEl.remove();
  3575. }
  3576. this.rowStructs = null;
  3577. },
  3578. // Uses the given events array to generate <tbody> elements that should be appended to each row's content skeleton.
  3579. // Returns an array of rowStruct objects (see the bottom of `renderSegRow`).
  3580. // PRECONDITION: each segment shoud already have a rendered and assigned `.el`
  3581. renderSegRows: function(segs) {
  3582. var rowStructs = [];
  3583. var segRows;
  3584. var row;
  3585. segRows = this.groupSegRows(segs); // group into nested arrays
  3586. // iterate each row of segment groupings
  3587. for (row = 0; row < segRows.length; row++) {
  3588. rowStructs.push(
  3589. this.renderSegRow(row, segRows[row])
  3590. );
  3591. }
  3592. return rowStructs;
  3593. },
  3594. // Builds the HTML to be used for the default element for an individual segment
  3595. fgSegHtml: function(seg, disableResizing) {
  3596. var view = this.view;
  3597. var event = seg.event;
  3598. var isDraggable = view.isEventDraggable(event);
  3599. var isResizable = !disableResizing && event.allDay && seg.isEnd && view.isEventResizable(event);
  3600. var classes = this.getSegClasses(seg, isDraggable, isResizable);
  3601. var skinCss = this.getEventSkinCss(event);
  3602. var timeHtml = '';
  3603. var titleHtml;
  3604. classes.unshift('fc-day-grid-event');
  3605. // Only display a timed events time if it is the starting segment
  3606. if (!event.allDay && seg.isStart) {
  3607. timeHtml = '<span class="fc-time">' + htmlEscape(this.getEventTimeText(event)) + '</span>';
  3608. }
  3609. titleHtml =
  3610. '<span class="fc-title">' +
  3611. (htmlEscape(event.title || '') || '&nbsp;') + // we always want one line of height
  3612. '</span>';
  3613. return '<a class="' + classes.join(' ') + '"' +
  3614. (event.url ?
  3615. ' href="' + htmlEscape(event.url) + '"' :
  3616. ''
  3617. ) +
  3618. (skinCss ?
  3619. ' style="' + skinCss + '"' :
  3620. ''
  3621. ) +
  3622. '>' +
  3623. '<div class="fc-content">' +
  3624. (this.isRTL ?
  3625. titleHtml + ' ' + timeHtml : // put a natural space in between
  3626. timeHtml + ' ' + titleHtml //
  3627. ) +
  3628. '</div>' +
  3629. (isResizable ?
  3630. '<div class="fc-resizer"/>' :
  3631. ''
  3632. ) +
  3633. '</a>';
  3634. },
  3635. // Given a row # and an array of segments all in the same row, render a <tbody> element, a skeleton that contains
  3636. // the segments. Returns object with a bunch of internal data about how the render was calculated.
  3637. renderSegRow: function(row, rowSegs) {
  3638. var colCnt = this.colCnt;
  3639. var segLevels = this.buildSegLevels(rowSegs); // group into sub-arrays of levels
  3640. var levelCnt = Math.max(1, segLevels.length); // ensure at least one level
  3641. var tbody = $('<tbody/>');
  3642. var segMatrix = []; // lookup for which segments are rendered into which level+col cells
  3643. var cellMatrix = []; // lookup for all <td> elements of the level+col matrix
  3644. var loneCellMatrix = []; // lookup for <td> elements that only take up a single column
  3645. var i, levelSegs;
  3646. var col;
  3647. var tr;
  3648. var j, seg;
  3649. var td;
  3650. // populates empty cells from the current column (`col`) to `endCol`
  3651. function emptyCellsUntil(endCol) {
  3652. while (col < endCol) {
  3653. // try to grab a cell from the level above and extend its rowspan. otherwise, create a fresh cell
  3654. td = (loneCellMatrix[i - 1] || [])[col];
  3655. if (td) {
  3656. td.attr(
  3657. 'rowspan',
  3658. parseInt(td.attr('rowspan') || 1, 10) + 1
  3659. );
  3660. }
  3661. else {
  3662. td = $('<td/>');
  3663. tr.append(td);
  3664. }
  3665. cellMatrix[i][col] = td;
  3666. loneCellMatrix[i][col] = td;
  3667. col++;
  3668. }
  3669. }
  3670. for (i = 0; i < levelCnt; i++) { // iterate through all levels
  3671. levelSegs = segLevels[i];
  3672. col = 0;
  3673. tr = $('<tr/>');
  3674. segMatrix.push([]);
  3675. cellMatrix.push([]);
  3676. loneCellMatrix.push([]);
  3677. // levelCnt might be 1 even though there are no actual levels. protect against this.
  3678. // this single empty row is useful for styling.
  3679. if (levelSegs) {
  3680. for (j = 0; j < levelSegs.length; j++) { // iterate through segments in level
  3681. seg = levelSegs[j];
  3682. emptyCellsUntil(seg.leftCol);
  3683. // create a container that occupies or more columns. append the event element.
  3684. td = $('<td class="fc-event-container"/>').append(seg.el);
  3685. if (seg.leftCol != seg.rightCol) {
  3686. td.attr('colspan', seg.rightCol - seg.leftCol + 1);
  3687. }
  3688. else { // a single-column segment
  3689. loneCellMatrix[i][col] = td;
  3690. }
  3691. while (col <= seg.rightCol) {
  3692. cellMatrix[i][col] = td;
  3693. segMatrix[i][col] = seg;
  3694. col++;
  3695. }
  3696. tr.append(td);
  3697. }
  3698. }
  3699. emptyCellsUntil(colCnt); // finish off the row
  3700. this.bookendCells(tr, 'eventSkeleton');
  3701. tbody.append(tr);
  3702. }
  3703. return { // a "rowStruct"
  3704. row: row, // the row number
  3705. tbodyEl: tbody,
  3706. cellMatrix: cellMatrix,
  3707. segMatrix: segMatrix,
  3708. segLevels: segLevels,
  3709. segs: rowSegs
  3710. };
  3711. },
  3712. // Stacks a flat array of segments, which are all assumed to be in the same row, into subarrays of vertical levels.
  3713. buildSegLevels: function(segs) {
  3714. var levels = [];
  3715. var i, seg;
  3716. var j;
  3717. // Give preference to elements with certain criteria, so they have
  3718. // a chance to be closer to the top.
  3719. segs.sort(compareSegs);
  3720. for (i = 0; i < segs.length; i++) {
  3721. seg = segs[i];
  3722. // loop through levels, starting with the topmost, until the segment doesn't collide with other segments
  3723. for (j = 0; j < levels.length; j++) {
  3724. if (!isDaySegCollision(seg, levels[j])) {
  3725. break;
  3726. }
  3727. }
  3728. // `j` now holds the desired subrow index
  3729. seg.level = j;
  3730. // create new level array if needed and append segment
  3731. (levels[j] || (levels[j] = [])).push(seg);
  3732. }
  3733. // order segments left-to-right. very important if calendar is RTL
  3734. for (j = 0; j < levels.length; j++) {
  3735. levels[j].sort(compareDaySegCols);
  3736. }
  3737. return levels;
  3738. },
  3739. // Given a flat array of segments, return an array of sub-arrays, grouped by each segment's row
  3740. groupSegRows: function(segs) {
  3741. var segRows = [];
  3742. var i;
  3743. for (i = 0; i < this.rowCnt; i++) {
  3744. segRows.push([]);
  3745. }
  3746. for (i = 0; i < segs.length; i++) {
  3747. segRows[segs[i].row].push(segs[i]);
  3748. }
  3749. return segRows;
  3750. }
  3751. });
  3752. // Computes whether two segments' columns collide. They are assumed to be in the same row.
  3753. function isDaySegCollision(seg, otherSegs) {
  3754. var i, otherSeg;
  3755. for (i = 0; i < otherSegs.length; i++) {
  3756. otherSeg = otherSegs[i];
  3757. if (
  3758. otherSeg.leftCol <= seg.rightCol &&
  3759. otherSeg.rightCol >= seg.leftCol
  3760. ) {
  3761. return true;
  3762. }
  3763. }
  3764. return false;
  3765. }
  3766. // A cmp function for determining the leftmost event
  3767. function compareDaySegCols(a, b) {
  3768. return a.leftCol - b.leftCol;
  3769. }
  3770. /* Methods relate to limiting the number events for a given day on a DayGrid
  3771. ----------------------------------------------------------------------------------------------------------------------*/
  3772. // NOTE: all the segs being passed around in here are foreground segs
  3773. DayGrid.mixin({
  3774. segPopover: null, // the Popover that holds events that can't fit in a cell. null when not visible
  3775. popoverSegs: null, // an array of segment objects that the segPopover holds. null when not visible
  3776. destroySegPopover: function() {
  3777. if (this.segPopover) {
  3778. this.segPopover.hide(); // will trigger destruction of `segPopover` and `popoverSegs`
  3779. }
  3780. },
  3781. // Limits the number of "levels" (vertically stacking layers of events) for each row of the grid.
  3782. // `levelLimit` can be false (don't limit), a number, or true (should be computed).
  3783. limitRows: function(levelLimit) {
  3784. var rowStructs = this.rowStructs || [];
  3785. var row; // row #
  3786. var rowLevelLimit;
  3787. for (row = 0; row < rowStructs.length; row++) {
  3788. this.unlimitRow(row);
  3789. if (!levelLimit) {
  3790. rowLevelLimit = false;
  3791. }
  3792. else if (typeof levelLimit === 'number') {
  3793. rowLevelLimit = levelLimit;
  3794. }
  3795. else {
  3796. rowLevelLimit = this.computeRowLevelLimit(row);
  3797. }
  3798. if (rowLevelLimit !== false) {
  3799. this.limitRow(row, rowLevelLimit);
  3800. }
  3801. }
  3802. },
  3803. // Computes the number of levels a row will accomodate without going outside its bounds.
  3804. // Assumes the row is "rigid" (maintains a constant height regardless of what is inside).
  3805. // `row` is the row number.
  3806. computeRowLevelLimit: function(row) {
  3807. var rowEl = this.rowEls.eq(row); // the containing "fake" row div
  3808. var rowHeight = rowEl.height(); // TODO: cache somehow?
  3809. var trEls = this.rowStructs[row].tbodyEl.children();
  3810. var i, trEl;
  3811. // Reveal one level <tr> at a time and stop when we find one out of bounds
  3812. for (i = 0; i < trEls.length; i++) {
  3813. trEl = trEls.eq(i).removeClass('fc-limited'); // get and reveal
  3814. if (trEl.position().top + trEl.outerHeight() > rowHeight) {
  3815. return i;
  3816. }
  3817. }
  3818. return false; // should not limit at all
  3819. },
  3820. // Limits the given grid row to the maximum number of levels and injects "more" links if necessary.
  3821. // `row` is the row number.
  3822. // `levelLimit` is a number for the maximum (inclusive) number of levels allowed.
  3823. limitRow: function(row, levelLimit) {
  3824. var _this = this;
  3825. var rowStruct = this.rowStructs[row];
  3826. var moreNodes = []; // array of "more" <a> links and <td> DOM nodes
  3827. var col = 0; // col #, left-to-right (not chronologically)
  3828. var cell;
  3829. var levelSegs; // array of segment objects in the last allowable level, ordered left-to-right
  3830. var cellMatrix; // a matrix (by level, then column) of all <td> jQuery elements in the row
  3831. var limitedNodes; // array of temporarily hidden level <tr> and segment <td> DOM nodes
  3832. var i, seg;
  3833. var segsBelow; // array of segment objects below `seg` in the current `col`
  3834. var totalSegsBelow; // total number of segments below `seg` in any of the columns `seg` occupies
  3835. var colSegsBelow; // array of segment arrays, below seg, one for each column (offset from segs's first column)
  3836. var td, rowspan;
  3837. var segMoreNodes; // array of "more" <td> cells that will stand-in for the current seg's cell
  3838. var j;
  3839. var moreTd, moreWrap, moreLink;
  3840. // Iterates through empty level cells and places "more" links inside if need be
  3841. function emptyCellsUntil(endCol) { // goes from current `col` to `endCol`
  3842. while (col < endCol) {
  3843. cell = _this.getCell(row, col);
  3844. segsBelow = _this.getCellSegs(cell, levelLimit);
  3845. if (segsBelow.length) {
  3846. td = cellMatrix[levelLimit - 1][col];
  3847. moreLink = _this.renderMoreLink(cell, segsBelow);
  3848. moreWrap = $('<div/>').append(moreLink);
  3849. td.append(moreWrap);
  3850. moreNodes.push(moreWrap[0]);
  3851. }
  3852. col++;
  3853. }
  3854. }
  3855. if (levelLimit && levelLimit < rowStruct.segLevels.length) { // is it actually over the limit?
  3856. levelSegs = rowStruct.segLevels[levelLimit - 1];
  3857. cellMatrix = rowStruct.cellMatrix;
  3858. limitedNodes = rowStruct.tbodyEl.children().slice(levelLimit) // get level <tr> elements past the limit
  3859. .addClass('fc-limited').get(); // hide elements and get a simple DOM-nodes array
  3860. // iterate though segments in the last allowable level
  3861. for (i = 0; i < levelSegs.length; i++) {
  3862. seg = levelSegs[i];
  3863. emptyCellsUntil(seg.leftCol); // process empty cells before the segment
  3864. // determine *all* segments below `seg` that occupy the same columns
  3865. colSegsBelow = [];
  3866. totalSegsBelow = 0;
  3867. while (col <= seg.rightCol) {
  3868. cell = this.getCell(row, col);
  3869. segsBelow = this.getCellSegs(cell, levelLimit);
  3870. colSegsBelow.push(segsBelow);
  3871. totalSegsBelow += segsBelow.length;
  3872. col++;
  3873. }
  3874. if (totalSegsBelow) { // do we need to replace this segment with one or many "more" links?
  3875. td = cellMatrix[levelLimit - 1][seg.leftCol]; // the segment's parent cell
  3876. rowspan = td.attr('rowspan') || 1;
  3877. segMoreNodes = [];
  3878. // make a replacement <td> for each column the segment occupies. will be one for each colspan
  3879. for (j = 0; j < colSegsBelow.length; j++) {
  3880. moreTd = $('<td class="fc-more-cell"/>').attr('rowspan', rowspan);
  3881. segsBelow = colSegsBelow[j];
  3882. cell = this.getCell(row, seg.leftCol + j);
  3883. moreLink = this.renderMoreLink(cell, [ seg ].concat(segsBelow)); // count seg as hidden too
  3884. moreWrap = $('<div/>').append(moreLink);
  3885. moreTd.append(moreWrap);
  3886. segMoreNodes.push(moreTd[0]);
  3887. moreNodes.push(moreTd[0]);
  3888. }
  3889. td.addClass('fc-limited').after($(segMoreNodes)); // hide original <td> and inject replacements
  3890. limitedNodes.push(td[0]);
  3891. }
  3892. }
  3893. emptyCellsUntil(this.colCnt); // finish off the level
  3894. rowStruct.moreEls = $(moreNodes); // for easy undoing later
  3895. rowStruct.limitedEls = $(limitedNodes); // for easy undoing later
  3896. }
  3897. },
  3898. // Reveals all levels and removes all "more"-related elements for a grid's row.
  3899. // `row` is a row number.
  3900. unlimitRow: function(row) {
  3901. var rowStruct = this.rowStructs[row];
  3902. if (rowStruct.moreEls) {
  3903. rowStruct.moreEls.remove();
  3904. rowStruct.moreEls = null;
  3905. }
  3906. if (rowStruct.limitedEls) {
  3907. rowStruct.limitedEls.removeClass('fc-limited');
  3908. rowStruct.limitedEls = null;
  3909. }
  3910. },
  3911. // Renders an <a> element that represents hidden event element for a cell.
  3912. // Responsible for attaching click handler as well.
  3913. renderMoreLink: function(cell, hiddenSegs) {
  3914. var _this = this;
  3915. var view = this.view;
  3916. return $('<a class="fc-more"/>')
  3917. .text(
  3918. this.getMoreLinkText(hiddenSegs.length)
  3919. )
  3920. .on('click', function(ev) {
  3921. var clickOption = view.opt('eventLimitClick');
  3922. var date = cell.start;
  3923. var moreEl = $(this);
  3924. var dayEl = _this.getCellDayEl(cell);
  3925. var allSegs = _this.getCellSegs(cell);
  3926. // rescope the segments to be within the cell's date
  3927. var reslicedAllSegs = _this.resliceDaySegs(allSegs, date);
  3928. var reslicedHiddenSegs = _this.resliceDaySegs(hiddenSegs, date);
  3929. if (typeof clickOption === 'function') {
  3930. // the returned value can be an atomic option
  3931. clickOption = view.trigger('eventLimitClick', null, {
  3932. date: date,
  3933. dayEl: dayEl,
  3934. moreEl: moreEl,
  3935. segs: reslicedAllSegs,
  3936. hiddenSegs: reslicedHiddenSegs
  3937. }, ev);
  3938. }
  3939. if (clickOption === 'popover') {
  3940. _this.showSegPopover(cell, moreEl, reslicedAllSegs);
  3941. }
  3942. else if (typeof clickOption === 'string') { // a view name
  3943. view.calendar.zoomTo(date, clickOption);
  3944. }
  3945. });
  3946. },
  3947. // Reveals the popover that displays all events within a cell
  3948. showSegPopover: function(cell, moreLink, segs) {
  3949. var _this = this;
  3950. var view = this.view;
  3951. var moreWrap = moreLink.parent(); // the <div> wrapper around the <a>
  3952. var topEl; // the element we want to match the top coordinate of
  3953. var options;
  3954. if (this.rowCnt == 1) {
  3955. topEl = view.el; // will cause the popover to cover any sort of header
  3956. }
  3957. else {
  3958. topEl = this.rowEls.eq(cell.row); // will align with top of row
  3959. }
  3960. options = {
  3961. className: 'fc-more-popover',
  3962. content: this.renderSegPopoverContent(cell, segs),
  3963. parentEl: this.el,
  3964. top: topEl.offset().top,
  3965. autoHide: true, // when the user clicks elsewhere, hide the popover
  3966. viewportConstrain: view.opt('popoverViewportConstrain'),
  3967. hide: function() {
  3968. // destroy everything when the popover is hidden
  3969. _this.segPopover.destroy();
  3970. _this.segPopover = null;
  3971. _this.popoverSegs = null;
  3972. }
  3973. };
  3974. // Determine horizontal coordinate.
  3975. // We use the moreWrap instead of the <td> to avoid border confusion.
  3976. if (this.isRTL) {
  3977. options.right = moreWrap.offset().left + moreWrap.outerWidth() + 1; // +1 to be over cell border
  3978. }
  3979. else {
  3980. options.left = moreWrap.offset().left - 1; // -1 to be over cell border
  3981. }
  3982. this.segPopover = new Popover(options);
  3983. this.segPopover.show();
  3984. },
  3985. // Builds the inner DOM contents of the segment popover
  3986. renderSegPopoverContent: function(cell, segs) {
  3987. var view = this.view;
  3988. var isTheme = view.opt('theme');
  3989. var title = cell.start.format(view.opt('dayPopoverFormat'));
  3990. var content = $(
  3991. '<div class="fc-header ' + view.widgetHeaderClass + '">' +
  3992. '<span class="fc-close ' +
  3993. (isTheme ? 'ui-icon ui-icon-closethick' : 'fc-icon fc-icon-x') +
  3994. '"></span>' +
  3995. '<span class="fc-title">' +
  3996. htmlEscape(title) +
  3997. '</span>' +
  3998. '<div class="fc-clear"/>' +
  3999. '</div>' +
  4000. '<div class="fc-body ' + view.widgetContentClass + '">' +
  4001. '<div class="fc-event-container"></div>' +
  4002. '</div>'
  4003. );
  4004. var segContainer = content.find('.fc-event-container');
  4005. var i;
  4006. // render each seg's `el` and only return the visible segs
  4007. segs = this.renderFgSegEls(segs, true); // disableResizing=true
  4008. this.popoverSegs = segs;
  4009. for (i = 0; i < segs.length; i++) {
  4010. // because segments in the popover are not part of a grid coordinate system, provide a hint to any
  4011. // grids that want to do drag-n-drop about which cell it came from
  4012. segs[i].cell = cell;
  4013. segContainer.append(segs[i].el);
  4014. }
  4015. return content;
  4016. },
  4017. // Given the events within an array of segment objects, reslice them to be in a single day
  4018. resliceDaySegs: function(segs, dayDate) {
  4019. // build an array of the original events
  4020. var events = $.map(segs, function(seg) {
  4021. return seg.event;
  4022. });
  4023. var dayStart = dayDate.clone().stripTime();
  4024. var dayEnd = dayStart.clone().add(1, 'days');
  4025. var dayRange = { start: dayStart, end: dayEnd };
  4026. // slice the events with a custom slicing function
  4027. return this.eventsToSegs(
  4028. events,
  4029. function(range) {
  4030. var seg = intersectionToSeg(range, dayRange); // undefind if no intersection
  4031. return seg ? [ seg ] : []; // must return an array of segments
  4032. }
  4033. );
  4034. },
  4035. // Generates the text that should be inside a "more" link, given the number of events it represents
  4036. getMoreLinkText: function(num) {
  4037. var opt = this.view.opt('eventLimitText');
  4038. if (typeof opt === 'function') {
  4039. return opt(num);
  4040. }
  4041. else {
  4042. return '+' + num + ' ' + opt;
  4043. }
  4044. },
  4045. // Returns segments within a given cell.
  4046. // If `startLevel` is specified, returns only events including and below that level. Otherwise returns all segs.
  4047. getCellSegs: function(cell, startLevel) {
  4048. var segMatrix = this.rowStructs[cell.row].segMatrix;
  4049. var level = startLevel || 0;
  4050. var segs = [];
  4051. var seg;
  4052. while (level < segMatrix.length) {
  4053. seg = segMatrix[level][cell.col];
  4054. if (seg) {
  4055. segs.push(seg);
  4056. }
  4057. level++;
  4058. }
  4059. return segs;
  4060. }
  4061. });
  4062. /* A component that renders one or more columns of vertical time slots
  4063. ----------------------------------------------------------------------------------------------------------------------*/
  4064. var TimeGrid = Grid.extend({
  4065. slotDuration: null, // duration of a "slot", a distinct time segment on given day, visualized by lines
  4066. snapDuration: null, // granularity of time for dragging and selecting
  4067. minTime: null, // Duration object that denotes the first visible time of any given day
  4068. maxTime: null, // Duration object that denotes the exclusive visible end time of any given day
  4069. axisFormat: null, // formatting string for times running along vertical axis
  4070. dayEls: null, // cells elements in the day-row background
  4071. slatEls: null, // elements running horizontally across all columns
  4072. slatTops: null, // an array of top positions, relative to the container. last item holds bottom of last slot
  4073. helperEl: null, // cell skeleton element for rendering the mock event "helper"
  4074. businessHourSegs: null,
  4075. constructor: function() {
  4076. Grid.apply(this, arguments); // call the super-constructor
  4077. this.processOptions();
  4078. },
  4079. // Renders the time grid into `this.el`, which should already be assigned.
  4080. // Relies on the view's colCnt. In the future, this component should probably be self-sufficient.
  4081. render: function() {
  4082. this.el.html(this.renderHtml());
  4083. this.dayEls = this.el.find('.fc-day');
  4084. this.slatEls = this.el.find('.fc-slats tr');
  4085. this.computeSlatTops();
  4086. this.renderBusinessHours();
  4087. Grid.prototype.render.call(this); // call the super-method
  4088. },
  4089. renderBusinessHours: function() {
  4090. var events = this.view.calendar.getBusinessHoursEvents();
  4091. this.businessHourSegs = this.renderFill('businessHours', this.eventsToSegs(events), 'bgevent');
  4092. },
  4093. // Renders the basic HTML skeleton for the grid
  4094. renderHtml: function() {
  4095. return '' +
  4096. '<div class="fc-bg">' +
  4097. '<table>' +
  4098. this.rowHtml('slotBg') + // leverages RowRenderer, which will call slotBgCellHtml
  4099. '</table>' +
  4100. '</div>' +
  4101. '<div class="fc-slats">' +
  4102. '<table>' +
  4103. this.slatRowHtml() +
  4104. '</table>' +
  4105. '</div>';
  4106. },
  4107. // Renders the HTML for a vertical background cell behind the slots.
  4108. // This method is distinct from 'bg' because we wanted a new `rowType` so the View could customize the rendering.
  4109. slotBgCellHtml: function(cell) {
  4110. return this.bgCellHtml(cell);
  4111. },
  4112. // Generates the HTML for the horizontal "slats" that run width-wise. Has a time axis on a side. Depends on RTL.
  4113. slatRowHtml: function() {
  4114. var view = this.view;
  4115. var isRTL = this.isRTL;
  4116. var html = '';
  4117. var slotNormal = this.slotDuration.asMinutes() % 15 === 0;
  4118. var slotTime = moment.duration(+this.minTime); // wish there was .clone() for durations
  4119. var slotDate; // will be on the view's first day, but we only care about its time
  4120. var minutes;
  4121. var axisHtml;
  4122. // Calculate the time for each slot
  4123. while (slotTime < this.maxTime) {
  4124. slotDate = this.start.clone().time(slotTime); // will be in UTC but that's good. to avoid DST issues
  4125. minutes = slotDate.minutes();
  4126. axisHtml =
  4127. '<td class="fc-axis fc-time ' + view.widgetContentClass + '" ' + view.axisStyleAttr() + '>' +
  4128. ((!slotNormal || !minutes) ? // if irregular slot duration, or on the hour, then display the time
  4129. '<span>' + // for matchCellWidths
  4130. htmlEscape(slotDate.format(this.axisFormat)) +
  4131. '</span>' :
  4132. ''
  4133. ) +
  4134. '</td>';
  4135. html +=
  4136. '<tr ' + (!minutes ? '' : 'class="fc-minor"') + '>' +
  4137. (!isRTL ? axisHtml : '') +
  4138. '<td class="' + view.widgetContentClass + '"/>' +
  4139. (isRTL ? axisHtml : '') +
  4140. "</tr>";
  4141. slotTime.add(this.slotDuration);
  4142. }
  4143. return html;
  4144. },
  4145. /* Options
  4146. ------------------------------------------------------------------------------------------------------------------*/
  4147. // Parses various options into properties of this object
  4148. processOptions: function() {
  4149. var view = this.view;
  4150. var slotDuration = view.opt('slotDuration');
  4151. var snapDuration = view.opt('snapDuration');
  4152. slotDuration = moment.duration(slotDuration);
  4153. snapDuration = snapDuration ? moment.duration(snapDuration) : slotDuration;
  4154. this.slotDuration = slotDuration;
  4155. this.snapDuration = snapDuration;
  4156. this.minTime = moment.duration(view.opt('minTime'));
  4157. this.maxTime = moment.duration(view.opt('maxTime'));
  4158. this.axisFormat = view.opt('axisFormat') || view.opt('smallTimeFormat');
  4159. },
  4160. // Computes a default column header formatting string if `colFormat` is not explicitly defined
  4161. computeColHeadFormat: function() {
  4162. if (this.colCnt > 1) { // multiple days, so full single date string WON'T be in title text
  4163. return this.view.opt('dayOfMonthFormat'); // "Sat 12/10"
  4164. }
  4165. else { // single day, so full single date string will probably be in title text
  4166. return 'dddd'; // "Saturday"
  4167. }
  4168. },
  4169. // Computes a default event time formatting string if `timeFormat` is not explicitly defined
  4170. computeEventTimeFormat: function() {
  4171. return this.view.opt('noMeridiemTimeFormat'); // like "6:30" (no AM/PM)
  4172. },
  4173. // Computes a default `displayEventEnd` value if one is not expliclty defined
  4174. computeDisplayEventEnd: function() {
  4175. return true;
  4176. },
  4177. /* Cell System
  4178. ------------------------------------------------------------------------------------------------------------------*/
  4179. // Initializes row/col information
  4180. updateCells: function() {
  4181. var view = this.view;
  4182. var colData = [];
  4183. var date;
  4184. date = this.start.clone();
  4185. while (date.isBefore(this.end)) {
  4186. colData.push({
  4187. day: date.clone()
  4188. });
  4189. date.add(1, 'day');
  4190. date = view.skipHiddenDays(date);
  4191. }
  4192. if (this.isRTL) {
  4193. colData.reverse();
  4194. }
  4195. this.colData = colData;
  4196. this.colCnt = colData.length;
  4197. this.rowCnt = Math.ceil((this.maxTime - this.minTime) / this.snapDuration); // # of vertical snaps
  4198. },
  4199. // Given a cell object, generates a range object
  4200. computeCellRange: function(cell) {
  4201. var time = this.computeSnapTime(cell.row);
  4202. var start = this.view.calendar.rezoneDate(cell.day).time(time);
  4203. var end = start.clone().add(this.snapDuration);
  4204. return { start: start, end: end };
  4205. },
  4206. // Retrieves the element representing the given column
  4207. getColEl: function(col) {
  4208. return this.dayEls.eq(col);
  4209. },
  4210. /* Dates
  4211. ------------------------------------------------------------------------------------------------------------------*/
  4212. // Given a row number of the grid, representing a "snap", returns a time (Duration) from its start-of-day
  4213. computeSnapTime: function(row) {
  4214. return moment.duration(this.minTime + this.snapDuration * row);
  4215. },
  4216. // Slices up a date range by column into an array of segments
  4217. rangeToSegs: function(range) {
  4218. var colCnt = this.colCnt;
  4219. var segs = [];
  4220. var seg;
  4221. var col;
  4222. var colDate;
  4223. var colRange;
  4224. // normalize :(
  4225. range = {
  4226. start: range.start.clone().stripZone(),
  4227. end: range.end.clone().stripZone()
  4228. };
  4229. for (col = 0; col < colCnt; col++) {
  4230. colDate = this.colData[col].day; // will be ambig time/timezone
  4231. colRange = {
  4232. start: colDate.clone().time(this.minTime),
  4233. end: colDate.clone().time(this.maxTime)
  4234. };
  4235. seg = intersectionToSeg(range, colRange); // both will be ambig timezone
  4236. if (seg) {
  4237. seg.col = col;
  4238. segs.push(seg);
  4239. }
  4240. }
  4241. return segs;
  4242. },
  4243. /* Coordinates
  4244. ------------------------------------------------------------------------------------------------------------------*/
  4245. // Called when there is a window resize/zoom and we need to recalculate coordinates for the grid
  4246. resize: function() {
  4247. this.computeSlatTops();
  4248. this.updateSegVerticals();
  4249. },
  4250. // Computes the top/bottom coordinates of each "snap" rows
  4251. computeRowCoords: function() {
  4252. var originTop = this.el.offset().top;
  4253. var items = [];
  4254. var i;
  4255. var item;
  4256. for (i = 0; i < this.rowCnt; i++) {
  4257. item = {
  4258. top: originTop + this.computeTimeTop(this.computeSnapTime(i))
  4259. };
  4260. if (i > 0) {
  4261. items[i - 1].bottom = item.top;
  4262. }
  4263. items.push(item);
  4264. }
  4265. item.bottom = item.top + this.computeTimeTop(this.computeSnapTime(i));
  4266. return items;
  4267. },
  4268. // Computes the top coordinate, relative to the bounds of the grid, of the given date.
  4269. // A `startOfDayDate` must be given for avoiding ambiguity over how to treat midnight.
  4270. computeDateTop: function(date, startOfDayDate) {
  4271. return this.computeTimeTop(
  4272. moment.duration(
  4273. date.clone().stripZone() - startOfDayDate.clone().stripTime()
  4274. )
  4275. );
  4276. },
  4277. // Computes the top coordinate, relative to the bounds of the grid, of the given time (a Duration).
  4278. computeTimeTop: function(time) {
  4279. var slatCoverage = (time - this.minTime) / this.slotDuration; // floating-point value of # of slots covered
  4280. var slatIndex;
  4281. var slatRemainder;
  4282. var slatTop;
  4283. var slatBottom;
  4284. // constrain. because minTime/maxTime might be customized
  4285. slatCoverage = Math.max(0, slatCoverage);
  4286. slatCoverage = Math.min(this.slatEls.length, slatCoverage);
  4287. slatIndex = Math.floor(slatCoverage); // an integer index of the furthest whole slot
  4288. slatRemainder = slatCoverage - slatIndex;
  4289. slatTop = this.slatTops[slatIndex]; // the top position of the furthest whole slot
  4290. if (slatRemainder) { // time spans part-way into the slot
  4291. slatBottom = this.slatTops[slatIndex + 1];
  4292. return slatTop + (slatBottom - slatTop) * slatRemainder; // part-way between slots
  4293. }
  4294. else {
  4295. return slatTop;
  4296. }
  4297. },
  4298. // Queries each `slatEl` for its position relative to the grid's container and stores it in `slatTops`.
  4299. // Includes the the bottom of the last slat as the last item in the array.
  4300. computeSlatTops: function() {
  4301. var tops = [];
  4302. var top;
  4303. this.slatEls.each(function(i, node) {
  4304. top = $(node).position().top;
  4305. tops.push(top);
  4306. });
  4307. tops.push(top + this.slatEls.last().outerHeight()); // bottom of the last slat
  4308. this.slatTops = tops;
  4309. },
  4310. /* Event Drag Visualization
  4311. ------------------------------------------------------------------------------------------------------------------*/
  4312. // Renders a visual indication of an event being dragged over the specified date(s).
  4313. // dropLocation's end might be null, as well as `seg`. See Grid::renderDrag for more info.
  4314. // A returned value of `true` signals that a mock "helper" event has been rendered.
  4315. renderDrag: function(dropLocation, seg) {
  4316. var opacity;
  4317. if (seg) { // if there is event information for this drag, render a helper event
  4318. this.renderRangeHelper(dropLocation, seg);
  4319. opacity = this.view.opt('dragOpacity');
  4320. if (opacity !== undefined) {
  4321. this.helperEl.css('opacity', opacity);
  4322. }
  4323. return true; // signal that a helper has been rendered
  4324. }
  4325. else {
  4326. // otherwise, just render a highlight
  4327. this.renderHighlight(
  4328. this.view.calendar.ensureVisibleEventRange(dropLocation) // needs to be a proper range
  4329. );
  4330. }
  4331. },
  4332. // Unrenders any visual indication of an event being dragged
  4333. destroyDrag: function() {
  4334. this.destroyHelper();
  4335. this.destroyHighlight();
  4336. },
  4337. /* Event Resize Visualization
  4338. ------------------------------------------------------------------------------------------------------------------*/
  4339. // Renders a visual indication of an event being resized
  4340. renderEventResize: function(range, seg) {
  4341. this.renderRangeHelper(range, seg);
  4342. },
  4343. // Unrenders any visual indication of an event being resized
  4344. destroyEventResize: function() {
  4345. this.destroyHelper();
  4346. },
  4347. /* Event Helper
  4348. ------------------------------------------------------------------------------------------------------------------*/
  4349. // Renders a mock "helper" event. `sourceSeg` is the original segment object and might be null (an external drag)
  4350. renderHelper: function(event, sourceSeg) {
  4351. var segs = this.eventsToSegs([ event ]);
  4352. var tableEl;
  4353. var i, seg;
  4354. var sourceEl;
  4355. segs = this.renderFgSegEls(segs); // assigns each seg's el and returns a subset of segs that were rendered
  4356. tableEl = this.renderSegTable(segs);
  4357. // Try to make the segment that is in the same row as sourceSeg look the same
  4358. for (i = 0; i < segs.length; i++) {
  4359. seg = segs[i];
  4360. if (sourceSeg && sourceSeg.col === seg.col) {
  4361. sourceEl = sourceSeg.el;
  4362. seg.el.css({
  4363. left: sourceEl.css('left'),
  4364. right: sourceEl.css('right'),
  4365. 'margin-left': sourceEl.css('margin-left'),
  4366. 'margin-right': sourceEl.css('margin-right')
  4367. });
  4368. }
  4369. }
  4370. this.helperEl = $('<div class="fc-helper-skeleton"/>')
  4371. .append(tableEl)
  4372. .appendTo(this.el);
  4373. },
  4374. // Unrenders any mock helper event
  4375. destroyHelper: function() {
  4376. if (this.helperEl) {
  4377. this.helperEl.remove();
  4378. this.helperEl = null;
  4379. }
  4380. },
  4381. /* Selection
  4382. ------------------------------------------------------------------------------------------------------------------*/
  4383. // Renders a visual indication of a selection. Overrides the default, which was to simply render a highlight.
  4384. renderSelection: function(range) {
  4385. if (this.view.opt('selectHelper')) { // this setting signals that a mock helper event should be rendered
  4386. this.renderRangeHelper(range);
  4387. }
  4388. else {
  4389. this.renderHighlight(range);
  4390. }
  4391. },
  4392. // Unrenders any visual indication of a selection
  4393. destroySelection: function() {
  4394. this.destroyHelper();
  4395. this.destroyHighlight();
  4396. },
  4397. /* Fill System (highlight, background events, business hours)
  4398. ------------------------------------------------------------------------------------------------------------------*/
  4399. // Renders a set of rectangles over the given time segments.
  4400. // Only returns segments that successfully rendered.
  4401. renderFill: function(type, segs, className) {
  4402. var segCols;
  4403. var skeletonEl;
  4404. var trEl;
  4405. var col, colSegs;
  4406. var tdEl;
  4407. var containerEl;
  4408. var dayDate;
  4409. var i, seg;
  4410. if (segs.length) {
  4411. segs = this.renderFillSegEls(type, segs); // assignes `.el` to each seg. returns successfully rendered segs
  4412. segCols = this.groupSegCols(segs); // group into sub-arrays, and assigns 'col' to each seg
  4413. className = className || type.toLowerCase();
  4414. skeletonEl = $(
  4415. '<div class="fc-' + className + '-skeleton">' +
  4416. '<table><tr/></table>' +
  4417. '</div>'
  4418. );
  4419. trEl = skeletonEl.find('tr');
  4420. for (col = 0; col < segCols.length; col++) {
  4421. colSegs = segCols[col];
  4422. tdEl = $('<td/>').appendTo(trEl);
  4423. if (colSegs.length) {
  4424. containerEl = $('<div class="fc-' + className + '-container"/>').appendTo(tdEl);
  4425. dayDate = this.colData[col].day;
  4426. for (i = 0; i < colSegs.length; i++) {
  4427. seg = colSegs[i];
  4428. containerEl.append(
  4429. seg.el.css({
  4430. top: this.computeDateTop(seg.start, dayDate),
  4431. bottom: -this.computeDateTop(seg.end, dayDate) // the y position of the bottom edge
  4432. })
  4433. );
  4434. }
  4435. }
  4436. }
  4437. this.bookendCells(trEl, type);
  4438. this.el.append(skeletonEl);
  4439. this.elsByFill[type] = skeletonEl;
  4440. }
  4441. return segs;
  4442. }
  4443. });
  4444. /* Event-rendering methods for the TimeGrid class
  4445. ----------------------------------------------------------------------------------------------------------------------*/
  4446. TimeGrid.mixin({
  4447. eventSkeletonEl: null, // has cells with event-containers, which contain absolutely positioned event elements
  4448. // Renders the given foreground event segments onto the grid
  4449. renderFgSegs: function(segs) {
  4450. segs = this.renderFgSegEls(segs); // returns a subset of the segs. segs that were actually rendered
  4451. this.el.append(
  4452. this.eventSkeletonEl = $('<div class="fc-content-skeleton"/>')
  4453. .append(this.renderSegTable(segs))
  4454. );
  4455. return segs; // return only the segs that were actually rendered
  4456. },
  4457. // Unrenders all currently rendered foreground event segments
  4458. destroyFgSegs: function(segs) {
  4459. if (this.eventSkeletonEl) {
  4460. this.eventSkeletonEl.remove();
  4461. this.eventSkeletonEl = null;
  4462. }
  4463. },
  4464. // Renders and returns the <table> portion of the event-skeleton.
  4465. // Returns an object with properties 'tbodyEl' and 'segs'.
  4466. renderSegTable: function(segs) {
  4467. var tableEl = $('<table><tr/></table>');
  4468. var trEl = tableEl.find('tr');
  4469. var segCols;
  4470. var i, seg;
  4471. var col, colSegs;
  4472. var containerEl;
  4473. segCols = this.groupSegCols(segs); // group into sub-arrays, and assigns 'col' to each seg
  4474. this.computeSegVerticals(segs); // compute and assign top/bottom
  4475. for (col = 0; col < segCols.length; col++) { // iterate each column grouping
  4476. colSegs = segCols[col];
  4477. placeSlotSegs(colSegs); // compute horizontal coordinates, z-index's, and reorder the array
  4478. containerEl = $('<div class="fc-event-container"/>');
  4479. // assign positioning CSS and insert into container
  4480. for (i = 0; i < colSegs.length; i++) {
  4481. seg = colSegs[i];
  4482. seg.el.css(this.generateSegPositionCss(seg));
  4483. // if the height is short, add a className for alternate styling
  4484. if (seg.bottom - seg.top < 30) {
  4485. seg.el.addClass('fc-short');
  4486. }
  4487. containerEl.append(seg.el);
  4488. }
  4489. trEl.append($('<td/>').append(containerEl));
  4490. }
  4491. this.bookendCells(trEl, 'eventSkeleton');
  4492. return tableEl;
  4493. },
  4494. // Refreshes the CSS top/bottom coordinates for each segment element. Probably after a window resize/zoom.
  4495. // Repositions business hours segs too, so not just for events. Maybe shouldn't be here.
  4496. updateSegVerticals: function() {
  4497. var allSegs = (this.segs || []).concat(this.businessHourSegs || []);
  4498. var i;
  4499. this.computeSegVerticals(allSegs);
  4500. for (i = 0; i < allSegs.length; i++) {
  4501. allSegs[i].el.css(
  4502. this.generateSegVerticalCss(allSegs[i])
  4503. );
  4504. }
  4505. },
  4506. // For each segment in an array, computes and assigns its top and bottom properties
  4507. computeSegVerticals: function(segs) {
  4508. var i, seg;
  4509. for (i = 0; i < segs.length; i++) {
  4510. seg = segs[i];
  4511. seg.top = this.computeDateTop(seg.start, seg.start);
  4512. seg.bottom = this.computeDateTop(seg.end, seg.start);
  4513. }
  4514. },
  4515. // Renders the HTML for a single event segment's default rendering
  4516. fgSegHtml: function(seg, disableResizing) {
  4517. var view = this.view;
  4518. var event = seg.event;
  4519. var isDraggable = view.isEventDraggable(event);
  4520. var isResizable = !disableResizing && seg.isEnd && view.isEventResizable(event);
  4521. var classes = this.getSegClasses(seg, isDraggable, isResizable);
  4522. var skinCss = this.getEventSkinCss(event);
  4523. var timeText;
  4524. var fullTimeText; // more verbose time text. for the print stylesheet
  4525. var startTimeText; // just the start time text
  4526. classes.unshift('fc-time-grid-event');
  4527. if (view.isMultiDayEvent(event)) { // if the event appears to span more than one day...
  4528. // Don't display time text on segments that run entirely through a day.
  4529. // That would appear as midnight-midnight and would look dumb.
  4530. // Otherwise, display the time text for the *segment's* times (like 6pm-midnight or midnight-10am)
  4531. if (seg.isStart || seg.isEnd) {
  4532. timeText = this.getEventTimeText(seg);
  4533. fullTimeText = this.getEventTimeText(seg, 'LT');
  4534. startTimeText = this.getEventTimeText({ start: seg.start });
  4535. }
  4536. } else {
  4537. // Display the normal time text for the *event's* times
  4538. timeText = this.getEventTimeText(event);
  4539. fullTimeText = this.getEventTimeText(event, 'LT');
  4540. startTimeText = this.getEventTimeText({ start: event.start });
  4541. }
  4542. return '<a class="' + classes.join(' ') + '"' +
  4543. (event.url ?
  4544. ' href="' + htmlEscape(event.url) + '"' :
  4545. ''
  4546. ) +
  4547. (skinCss ?
  4548. ' style="' + skinCss + '"' :
  4549. ''
  4550. ) +
  4551. '>' +
  4552. '<div class="fc-content">' +
  4553. (timeText ?
  4554. '<div class="fc-time"' +
  4555. ' data-start="' + htmlEscape(startTimeText) + '"' +
  4556. ' data-full="' + htmlEscape(fullTimeText) + '"' +
  4557. '>' +
  4558. '<span>' + htmlEscape(timeText) + '</span>' +
  4559. '</div>' :
  4560. ''
  4561. ) +
  4562. (event.title ?
  4563. '<div class="fc-title">' +
  4564. htmlEscape(event.title) +
  4565. '</div>' :
  4566. ''
  4567. ) +
  4568. '</div>' +
  4569. '<div class="fc-bg"/>' +
  4570. (isResizable ?
  4571. '<div class="fc-resizer"/>' :
  4572. ''
  4573. ) +
  4574. '</a>';
  4575. },
  4576. // Generates an object with CSS properties/values that should be applied to an event segment element.
  4577. // Contains important positioning-related properties that should be applied to any event element, customized or not.
  4578. generateSegPositionCss: function(seg) {
  4579. var shouldOverlap = this.view.opt('slotEventOverlap');
  4580. var backwardCoord = seg.backwardCoord; // the left side if LTR. the right side if RTL. floating-point
  4581. var forwardCoord = seg.forwardCoord; // the right side if LTR. the left side if RTL. floating-point
  4582. var props = this.generateSegVerticalCss(seg); // get top/bottom first
  4583. var left; // amount of space from left edge, a fraction of the total width
  4584. var right; // amount of space from right edge, a fraction of the total width
  4585. if (shouldOverlap) {
  4586. // double the width, but don't go beyond the maximum forward coordinate (1.0)
  4587. forwardCoord = Math.min(1, backwardCoord + (forwardCoord - backwardCoord) * 2);
  4588. }
  4589. if (this.isRTL) {
  4590. left = 1 - forwardCoord;
  4591. right = backwardCoord;
  4592. }
  4593. else {
  4594. left = backwardCoord;
  4595. right = 1 - forwardCoord;
  4596. }
  4597. props.zIndex = seg.level + 1; // convert from 0-base to 1-based
  4598. props.left = left * 100 + '%';
  4599. props.right = right * 100 + '%';
  4600. if (shouldOverlap && seg.forwardPressure) {
  4601. // add padding to the edge so that forward stacked events don't cover the resizer's icon
  4602. props[this.isRTL ? 'marginLeft' : 'marginRight'] = 10 * 2; // 10 is a guesstimate of the icon's width
  4603. }
  4604. return props;
  4605. },
  4606. // Generates an object with CSS properties for the top/bottom coordinates of a segment element
  4607. generateSegVerticalCss: function(seg) {
  4608. return {
  4609. top: seg.top,
  4610. bottom: -seg.bottom // flipped because needs to be space beyond bottom edge of event container
  4611. };
  4612. },
  4613. // Given a flat array of segments, return an array of sub-arrays, grouped by each segment's col
  4614. groupSegCols: function(segs) {
  4615. var segCols = [];
  4616. var i;
  4617. for (i = 0; i < this.colCnt; i++) {
  4618. segCols.push([]);
  4619. }
  4620. for (i = 0; i < segs.length; i++) {
  4621. segCols[segs[i].col].push(segs[i]);
  4622. }
  4623. return segCols;
  4624. }
  4625. });
  4626. // Given an array of segments that are all in the same column, sets the backwardCoord and forwardCoord on each.
  4627. // Also reorders the given array by date!
  4628. function placeSlotSegs(segs) {
  4629. var levels;
  4630. var level0;
  4631. var i;
  4632. segs.sort(compareSegs); // order by date
  4633. levels = buildSlotSegLevels(segs);
  4634. computeForwardSlotSegs(levels);
  4635. if ((level0 = levels[0])) {
  4636. for (i = 0; i < level0.length; i++) {
  4637. computeSlotSegPressures(level0[i]);
  4638. }
  4639. for (i = 0; i < level0.length; i++) {
  4640. computeSlotSegCoords(level0[i], 0, 0);
  4641. }
  4642. }
  4643. }
  4644. // Builds an array of segments "levels". The first level will be the leftmost tier of segments if the calendar is
  4645. // left-to-right, or the rightmost if the calendar is right-to-left. Assumes the segments are already ordered by date.
  4646. function buildSlotSegLevels(segs) {
  4647. var levels = [];
  4648. var i, seg;
  4649. var j;
  4650. for (i=0; i<segs.length; i++) {
  4651. seg = segs[i];
  4652. // go through all the levels and stop on the first level where there are no collisions
  4653. for (j=0; j<levels.length; j++) {
  4654. if (!computeSlotSegCollisions(seg, levels[j]).length) {
  4655. break;
  4656. }
  4657. }
  4658. seg.level = j;
  4659. (levels[j] || (levels[j] = [])).push(seg);
  4660. }
  4661. return levels;
  4662. }
  4663. // For every segment, figure out the other segments that are in subsequent
  4664. // levels that also occupy the same vertical space. Accumulate in seg.forwardSegs
  4665. function computeForwardSlotSegs(levels) {
  4666. var i, level;
  4667. var j, seg;
  4668. var k;
  4669. for (i=0; i<levels.length; i++) {
  4670. level = levels[i];
  4671. for (j=0; j<level.length; j++) {
  4672. seg = level[j];
  4673. seg.forwardSegs = [];
  4674. for (k=i+1; k<levels.length; k++) {
  4675. computeSlotSegCollisions(seg, levels[k], seg.forwardSegs);
  4676. }
  4677. }
  4678. }
  4679. }
  4680. // Figure out which path forward (via seg.forwardSegs) results in the longest path until
  4681. // the furthest edge is reached. The number of segments in this path will be seg.forwardPressure
  4682. function computeSlotSegPressures(seg) {
  4683. var forwardSegs = seg.forwardSegs;
  4684. var forwardPressure = 0;
  4685. var i, forwardSeg;
  4686. if (seg.forwardPressure === undefined) { // not already computed
  4687. for (i=0; i<forwardSegs.length; i++) {
  4688. forwardSeg = forwardSegs[i];
  4689. // figure out the child's maximum forward path
  4690. computeSlotSegPressures(forwardSeg);
  4691. // either use the existing maximum, or use the child's forward pressure
  4692. // plus one (for the forwardSeg itself)
  4693. forwardPressure = Math.max(
  4694. forwardPressure,
  4695. 1 + forwardSeg.forwardPressure
  4696. );
  4697. }
  4698. seg.forwardPressure = forwardPressure;
  4699. }
  4700. }
  4701. // Calculate seg.forwardCoord and seg.backwardCoord for the segment, where both values range
  4702. // from 0 to 1. If the calendar is left-to-right, the seg.backwardCoord maps to "left" and
  4703. // seg.forwardCoord maps to "right" (via percentage). Vice-versa if the calendar is right-to-left.
  4704. //
  4705. // The segment might be part of a "series", which means consecutive segments with the same pressure
  4706. // who's width is unknown until an edge has been hit. `seriesBackwardPressure` is the number of
  4707. // segments behind this one in the current series, and `seriesBackwardCoord` is the starting
  4708. // coordinate of the first segment in the series.
  4709. function computeSlotSegCoords(seg, seriesBackwardPressure, seriesBackwardCoord) {
  4710. var forwardSegs = seg.forwardSegs;
  4711. var i;
  4712. if (seg.forwardCoord === undefined) { // not already computed
  4713. if (!forwardSegs.length) {
  4714. // if there are no forward segments, this segment should butt up against the edge
  4715. seg.forwardCoord = 1;
  4716. }
  4717. else {
  4718. // sort highest pressure first
  4719. forwardSegs.sort(compareForwardSlotSegs);
  4720. // this segment's forwardCoord will be calculated from the backwardCoord of the
  4721. // highest-pressure forward segment.
  4722. computeSlotSegCoords(forwardSegs[0], seriesBackwardPressure + 1, seriesBackwardCoord);
  4723. seg.forwardCoord = forwardSegs[0].backwardCoord;
  4724. }
  4725. // calculate the backwardCoord from the forwardCoord. consider the series
  4726. seg.backwardCoord = seg.forwardCoord -
  4727. (seg.forwardCoord - seriesBackwardCoord) / // available width for series
  4728. (seriesBackwardPressure + 1); // # of segments in the series
  4729. // use this segment's coordinates to computed the coordinates of the less-pressurized
  4730. // forward segments
  4731. for (i=0; i<forwardSegs.length; i++) {
  4732. computeSlotSegCoords(forwardSegs[i], 0, seg.forwardCoord);
  4733. }
  4734. }
  4735. }
  4736. // Find all the segments in `otherSegs` that vertically collide with `seg`.
  4737. // Append into an optionally-supplied `results` array and return.
  4738. function computeSlotSegCollisions(seg, otherSegs, results) {
  4739. results = results || [];
  4740. for (var i=0; i<otherSegs.length; i++) {
  4741. if (isSlotSegCollision(seg, otherSegs[i])) {
  4742. results.push(otherSegs[i]);
  4743. }
  4744. }
  4745. return results;
  4746. }
  4747. // Do these segments occupy the same vertical space?
  4748. function isSlotSegCollision(seg1, seg2) {
  4749. return seg1.bottom > seg2.top && seg1.top < seg2.bottom;
  4750. }
  4751. // A cmp function for determining which forward segment to rely on more when computing coordinates.
  4752. function compareForwardSlotSegs(seg1, seg2) {
  4753. // put higher-pressure first
  4754. return seg2.forwardPressure - seg1.forwardPressure ||
  4755. // put segments that are closer to initial edge first (and favor ones with no coords yet)
  4756. (seg1.backwardCoord || 0) - (seg2.backwardCoord || 0) ||
  4757. // do normal sorting...
  4758. compareSegs(seg1, seg2);
  4759. }
  4760. /* An abstract class from which other views inherit from
  4761. ----------------------------------------------------------------------------------------------------------------------*/
  4762. var View = fc.View = Class.extend({
  4763. type: null, // subclass' view name (string)
  4764. name: null, // deprecated. use `type` instead
  4765. calendar: null, // owner Calendar object
  4766. options: null, // view-specific options
  4767. coordMap: null, // a CoordMap object for converting pixel regions to dates
  4768. el: null, // the view's containing element. set by Calendar
  4769. // range the view is actually displaying (moments)
  4770. start: null,
  4771. end: null, // exclusive
  4772. // range the view is formally responsible for (moments)
  4773. // may be different from start/end. for example, a month view might have 1st-31st, excluding padded dates
  4774. intervalStart: null,
  4775. intervalEnd: null, // exclusive
  4776. intervalDuration: null, // the whole-unit duration that is being displayed
  4777. intervalUnit: null, // name of largest unit being displayed, like "month" or "week"
  4778. isSelected: false, // boolean whether a range of time is user-selected or not
  4779. // subclasses can optionally use a scroll container
  4780. scrollerEl: null, // the element that will most likely scroll when content is too tall
  4781. scrollTop: null, // cached vertical scroll value
  4782. // classNames styled by jqui themes
  4783. widgetHeaderClass: null,
  4784. widgetContentClass: null,
  4785. highlightStateClass: null,
  4786. // for date utils, computed from options
  4787. nextDayThreshold: null,
  4788. isHiddenDayHash: null,
  4789. // document handlers, bound to `this` object
  4790. documentMousedownProxy: null, // TODO: doesn't work with touch
  4791. constructor: function(calendar, viewOptions, viewType) {
  4792. this.calendar = calendar;
  4793. this.options = viewOptions;
  4794. this.type = this.name = viewType; // .name is deprecated
  4795. this.nextDayThreshold = moment.duration(this.opt('nextDayThreshold'));
  4796. this.initTheming();
  4797. this.initHiddenDays();
  4798. this.documentMousedownProxy = $.proxy(this, 'documentMousedown');
  4799. this.initialize();
  4800. },
  4801. // A good place for subclasses to initialize member variables
  4802. initialize: function() {
  4803. // subclasses can implement
  4804. },
  4805. // Retrieves an option with the given name
  4806. opt: function(name) {
  4807. var val;
  4808. val = this.options[name]; // look at view-specific options first
  4809. if (val !== undefined) {
  4810. return val;
  4811. }
  4812. val = this.calendar.options[name];
  4813. if ($.isPlainObject(val) && !isForcedAtomicOption(name)) { // view-option-hashes are deprecated
  4814. return smartProperty(val, this.type);
  4815. }
  4816. return val;
  4817. },
  4818. // Triggers handlers that are view-related. Modifies args before passing to calendar.
  4819. trigger: function(name, thisObj) { // arguments beyond thisObj are passed along
  4820. var calendar = this.calendar;
  4821. return calendar.trigger.apply(
  4822. calendar,
  4823. [name, thisObj || this].concat(
  4824. Array.prototype.slice.call(arguments, 2), // arguments beyond thisObj
  4825. [ this ] // always make the last argument a reference to the view. TODO: deprecate
  4826. )
  4827. );
  4828. },
  4829. /* Dates
  4830. ------------------------------------------------------------------------------------------------------------------*/
  4831. // Updates all internal dates to center around the given current date
  4832. setDate: function(date) {
  4833. this.setRange(this.computeRange(date));
  4834. },
  4835. // Updates all internal dates for displaying the given range.
  4836. // Expects all values to be normalized (like what computeRange does).
  4837. setRange: function(range) {
  4838. $.extend(this, range);
  4839. },
  4840. // Given a single current date, produce information about what range to display.
  4841. // Subclasses can override. Must return all properties.
  4842. computeRange: function(date) {
  4843. var intervalDuration = moment.duration(this.opt('duration') || this.constructor.duration || { days: 1 });
  4844. var intervalUnit = computeIntervalUnit(intervalDuration);
  4845. var intervalStart = date.clone().startOf(intervalUnit);
  4846. var intervalEnd = intervalStart.clone().add(intervalDuration);
  4847. var start, end;
  4848. // normalize the range's time-ambiguity
  4849. if (computeIntervalAs('days', intervalDuration)) { // whole-days?
  4850. intervalStart.stripTime();
  4851. intervalEnd.stripTime();
  4852. }
  4853. else { // needs to have a time?
  4854. if (!intervalStart.hasTime()) {
  4855. intervalStart = this.calendar.rezoneDate(intervalStart); // convert to current timezone, with 00:00
  4856. }
  4857. if (!intervalEnd.hasTime()) {
  4858. intervalEnd = this.calendar.rezoneDate(intervalEnd); // convert to current timezone, with 00:00
  4859. }
  4860. }
  4861. start = intervalStart.clone();
  4862. start = this.skipHiddenDays(start);
  4863. end = intervalEnd.clone();
  4864. end = this.skipHiddenDays(end, -1, true); // exclusively move backwards
  4865. return {
  4866. intervalDuration: intervalDuration,
  4867. intervalUnit: intervalUnit,
  4868. intervalStart: intervalStart,
  4869. intervalEnd: intervalEnd,
  4870. start: start,
  4871. end: end
  4872. };
  4873. },
  4874. // Computes the new date when the user hits the prev button, given the current date
  4875. computePrevDate: function(date) {
  4876. return this.skipHiddenDays(
  4877. date.clone().startOf(this.intervalUnit).subtract(this.intervalDuration), -1
  4878. );
  4879. },
  4880. // Computes the new date when the user hits the next button, given the current date
  4881. computeNextDate: function(date) {
  4882. return this.skipHiddenDays(
  4883. date.clone().startOf(this.intervalUnit).add(this.intervalDuration)
  4884. );
  4885. },
  4886. /* Title and Date Formatting
  4887. ------------------------------------------------------------------------------------------------------------------*/
  4888. // Computes what the title at the top of the calendar should be for this view
  4889. computeTitle: function() {
  4890. return this.formatRange(
  4891. { start: this.intervalStart, end: this.intervalEnd },
  4892. this.opt('titleFormat') || this.computeTitleFormat(),
  4893. this.opt('titleRangeSeparator')
  4894. );
  4895. },
  4896. // Generates the format string that should be used to generate the title for the current date range.
  4897. // Attempts to compute the most appropriate format if not explicitly specified with `titleFormat`.
  4898. computeTitleFormat: function() {
  4899. if (this.intervalUnit == 'year') {
  4900. return 'YYYY';
  4901. }
  4902. else if (this.intervalUnit == 'month') {
  4903. return this.opt('monthYearFormat'); // like "September 2014"
  4904. }
  4905. else if (this.intervalDuration.as('days') > 1) {
  4906. return 'll'; // multi-day range. shorter, like "Sep 9 - 10 2014"
  4907. }
  4908. else {
  4909. return 'LL'; // one day. longer, like "September 9 2014"
  4910. }
  4911. },
  4912. // Utility for formatting a range. Accepts a range object, formatting string, and optional separator.
  4913. // Displays all-day ranges naturally, with an inclusive end. Takes the current isRTL into account.
  4914. formatRange: function(range, formatStr, separator) {
  4915. var end = range.end;
  4916. if (!end.hasTime()) { // all-day?
  4917. end = end.clone().subtract(1); // convert to inclusive. last ms of previous day
  4918. }
  4919. return formatRange(range.start, end, formatStr, separator, this.opt('isRTL'));
  4920. },
  4921. /* Rendering
  4922. ------------------------------------------------------------------------------------------------------------------*/
  4923. // Wraps the basic render() method with more View-specific logic. Called by the owner Calendar.
  4924. renderView: function() {
  4925. this.render();
  4926. this.updateSize();
  4927. this.initializeScroll();
  4928. this.trigger('viewRender', this, this, this.el);
  4929. // attach handlers to document. do it here to allow for destroy/rerender
  4930. $(document).on('mousedown', this.documentMousedownProxy);
  4931. },
  4932. // Renders the view inside an already-defined `this.el`
  4933. render: function() {
  4934. // subclasses should implement
  4935. },
  4936. // Wraps the basic destroy() method with more View-specific logic. Called by the owner Calendar.
  4937. destroyView: function() {
  4938. this.unselect();
  4939. this.destroyViewEvents();
  4940. this.destroy();
  4941. this.trigger('viewDestroy', this, this, this.el);
  4942. $(document).off('mousedown', this.documentMousedownProxy);
  4943. },
  4944. // Clears the view's rendering
  4945. destroy: function() {
  4946. this.el.empty(); // removes inner contents but leaves the element intact
  4947. },
  4948. // Initializes internal variables related to theming
  4949. initTheming: function() {
  4950. var tm = this.opt('theme') ? 'ui' : 'fc';
  4951. this.widgetHeaderClass = tm + '-widget-header';
  4952. this.widgetContentClass = tm + '-widget-content';
  4953. this.highlightStateClass = tm + '-state-highlight';
  4954. },
  4955. /* Dimensions
  4956. ------------------------------------------------------------------------------------------------------------------*/
  4957. // Refreshes anything dependant upon sizing of the container element of the grid
  4958. updateSize: function(isResize) {
  4959. if (isResize) {
  4960. this.recordScroll();
  4961. }
  4962. this.updateHeight();
  4963. this.updateWidth();
  4964. },
  4965. // Refreshes the horizontal dimensions of the calendar
  4966. updateWidth: function() {
  4967. // subclasses should implement
  4968. },
  4969. // Refreshes the vertical dimensions of the calendar
  4970. updateHeight: function() {
  4971. var calendar = this.calendar; // we poll the calendar for height information
  4972. this.setHeight(
  4973. calendar.getSuggestedViewHeight(),
  4974. calendar.isHeightAuto()
  4975. );
  4976. },
  4977. // Updates the vertical dimensions of the calendar to the specified height.
  4978. // if `isAuto` is set to true, height becomes merely a suggestion and the view should use its "natural" height.
  4979. setHeight: function(height, isAuto) {
  4980. // subclasses should implement
  4981. },
  4982. /* Scroller
  4983. ------------------------------------------------------------------------------------------------------------------*/
  4984. // Given the total height of the view, return the number of pixels that should be used for the scroller.
  4985. // By default, uses this.scrollerEl, but can pass this in as well.
  4986. // Utility for subclasses.
  4987. computeScrollerHeight: function(totalHeight, scrollerEl) {
  4988. var both;
  4989. var otherHeight; // cumulative height of everything that is not the scrollerEl in the view (header+borders)
  4990. scrollerEl = scrollerEl || this.scrollerEl;
  4991. both = this.el.add(scrollerEl);
  4992. // fuckin IE8/9/10/11 sometimes returns 0 for dimensions. this weird hack was the only thing that worked
  4993. both.css({
  4994. position: 'relative', // cause a reflow, which will force fresh dimension recalculation
  4995. left: -1 // ensure reflow in case the el was already relative. negative is less likely to cause new scroll
  4996. });
  4997. otherHeight = this.el.outerHeight() - scrollerEl.height(); // grab the dimensions
  4998. both.css({ position: '', left: '' }); // undo hack
  4999. return totalHeight - otherHeight;
  5000. },
  5001. // Sets the scroll value of the scroller to the initial pre-configured state prior to allowing the user to change it
  5002. initializeScroll: function() {
  5003. },
  5004. // Called for remembering the current scroll value of the scroller.
  5005. // Should be called before there is a destructive operation (like removing DOM elements) that might inadvertently
  5006. // change the scroll of the container.
  5007. recordScroll: function() {
  5008. if (this.scrollerEl) {
  5009. this.scrollTop = this.scrollerEl.scrollTop();
  5010. }
  5011. },
  5012. // Set the scroll value of the scroller to the previously recorded value.
  5013. // Should be called after we know the view's dimensions have been restored following some type of destructive
  5014. // operation (like temporarily removing DOM elements).
  5015. restoreScroll: function() {
  5016. if (this.scrollTop !== null) {
  5017. this.scrollerEl.scrollTop(this.scrollTop);
  5018. }
  5019. },
  5020. /* Event Elements / Segments
  5021. ------------------------------------------------------------------------------------------------------------------*/
  5022. // Wraps the basic renderEvents() method with more View-specific logic
  5023. renderViewEvents: function(events) {
  5024. this.renderEvents(events);
  5025. this.eventSegEach(function(seg) {
  5026. this.trigger('eventAfterRender', seg.event, seg.event, seg.el);
  5027. });
  5028. this.trigger('eventAfterAllRender');
  5029. },
  5030. // Renders the events onto the view.
  5031. renderEvents: function() {
  5032. // subclasses should implement
  5033. },
  5034. // Wraps the basic destroyEvents() method with more View-specific logic
  5035. destroyViewEvents: function() {
  5036. this.eventSegEach(function(seg) {
  5037. this.trigger('eventDestroy', seg.event, seg.event, seg.el);
  5038. });
  5039. this.destroyEvents();
  5040. },
  5041. // Removes event elements from the view.
  5042. destroyEvents: function() {
  5043. // subclasses should implement
  5044. },
  5045. // Given an event and the default element used for rendering, returns the element that should actually be used.
  5046. // Basically runs events and elements through the eventRender hook.
  5047. resolveEventEl: function(event, el) {
  5048. var custom = this.trigger('eventRender', event, event, el);
  5049. if (custom === false) { // means don't render at all
  5050. el = null;
  5051. }
  5052. else if (custom && custom !== true) {
  5053. el = $(custom);
  5054. }
  5055. return el;
  5056. },
  5057. // Hides all rendered event segments linked to the given event
  5058. showEvent: function(event) {
  5059. this.eventSegEach(function(seg) {
  5060. seg.el.css('visibility', '');
  5061. }, event);
  5062. },
  5063. // Shows all rendered event segments linked to the given event
  5064. hideEvent: function(event) {
  5065. this.eventSegEach(function(seg) {
  5066. seg.el.css('visibility', 'hidden');
  5067. }, event);
  5068. },
  5069. // Iterates through event segments. Goes through all by default.
  5070. // If the optional `event` argument is specified, only iterates through segments linked to that event.
  5071. // The `this` value of the callback function will be the view.
  5072. eventSegEach: function(func, event) {
  5073. var segs = this.getEventSegs();
  5074. var i;
  5075. for (i = 0; i < segs.length; i++) {
  5076. if (!event || segs[i].event._id === event._id) {
  5077. func.call(this, segs[i]);
  5078. }
  5079. }
  5080. },
  5081. // Retrieves all the rendered segment objects for the view
  5082. getEventSegs: function() {
  5083. // subclasses must implement
  5084. return [];
  5085. },
  5086. /* Event Drag-n-Drop
  5087. ------------------------------------------------------------------------------------------------------------------*/
  5088. // Computes if the given event is allowed to be dragged by the user
  5089. isEventDraggable: function(event) {
  5090. var source = event.source || {};
  5091. return firstDefined(
  5092. event.startEditable,
  5093. source.startEditable,
  5094. this.opt('eventStartEditable'),
  5095. event.editable,
  5096. source.editable,
  5097. this.opt('editable')
  5098. );
  5099. },
  5100. // Must be called when an event in the view is dropped onto new location.
  5101. // `dropLocation` is an object that contains the new start/end/allDay values for the event.
  5102. reportEventDrop: function(event, dropLocation, el, ev) {
  5103. var calendar = this.calendar;
  5104. var mutateResult = calendar.mutateEvent(event, dropLocation);
  5105. var undoFunc = function() {
  5106. mutateResult.undo();
  5107. calendar.reportEventChange();
  5108. };
  5109. this.triggerEventDrop(event, mutateResult.dateDelta, undoFunc, el, ev);
  5110. calendar.reportEventChange(); // will rerender events
  5111. },
  5112. // Triggers event-drop handlers that have subscribed via the API
  5113. triggerEventDrop: function(event, dateDelta, undoFunc, el, ev) {
  5114. this.trigger('eventDrop', el[0], event, dateDelta, undoFunc, ev, {}); // {} = jqui dummy
  5115. },
  5116. /* External Element Drag-n-Drop
  5117. ------------------------------------------------------------------------------------------------------------------*/
  5118. // Must be called when an external element, via jQuery UI, has been dropped onto the calendar.
  5119. // `meta` is the parsed data that has been embedded into the dragging event.
  5120. // `dropLocation` is an object that contains the new start/end/allDay values for the event.
  5121. reportExternalDrop: function(meta, dropLocation, el, ev, ui) {
  5122. var eventProps = meta.eventProps;
  5123. var eventInput;
  5124. var event;
  5125. // Try to build an event object and render it. TODO: decouple the two
  5126. if (eventProps) {
  5127. eventInput = $.extend({}, eventProps, dropLocation);
  5128. event = this.calendar.renderEvent(eventInput, meta.stick)[0]; // renderEvent returns an array
  5129. }
  5130. this.triggerExternalDrop(event, dropLocation, el, ev, ui);
  5131. },
  5132. // Triggers external-drop handlers that have subscribed via the API
  5133. triggerExternalDrop: function(event, dropLocation, el, ev, ui) {
  5134. // trigger 'drop' regardless of whether element represents an event
  5135. this.trigger('drop', el[0], dropLocation.start, ev, ui);
  5136. if (event) {
  5137. this.trigger('eventReceive', null, event); // signal an external event landed
  5138. }
  5139. },
  5140. /* Drag-n-Drop Rendering (for both events and external elements)
  5141. ------------------------------------------------------------------------------------------------------------------*/
  5142. // Renders a visual indication of a event or external-element drag over the given drop zone.
  5143. // If an external-element, seg will be `null`
  5144. renderDrag: function(dropLocation, seg) {
  5145. // subclasses must implement
  5146. },
  5147. // Unrenders a visual indication of an event or external-element being dragged.
  5148. destroyDrag: function() {
  5149. // subclasses must implement
  5150. },
  5151. /* Event Resizing
  5152. ------------------------------------------------------------------------------------------------------------------*/
  5153. // Computes if the given event is allowed to be resize by the user
  5154. isEventResizable: function(event) {
  5155. var source = event.source || {};
  5156. return firstDefined(
  5157. event.durationEditable,
  5158. source.durationEditable,
  5159. this.opt('eventDurationEditable'),
  5160. event.editable,
  5161. source.editable,
  5162. this.opt('editable')
  5163. );
  5164. },
  5165. // Must be called when an event in the view has been resized to a new length
  5166. reportEventResize: function(event, newEnd, el, ev) {
  5167. var calendar = this.calendar;
  5168. var mutateResult = calendar.mutateEvent(event, { end: newEnd });
  5169. var undoFunc = function() {
  5170. mutateResult.undo();
  5171. calendar.reportEventChange();
  5172. };
  5173. this.triggerEventResize(event, mutateResult.durationDelta, undoFunc, el, ev);
  5174. calendar.reportEventChange(); // will rerender events
  5175. },
  5176. // Triggers event-resize handlers that have subscribed via the API
  5177. triggerEventResize: function(event, durationDelta, undoFunc, el, ev) {
  5178. this.trigger('eventResize', el[0], event, durationDelta, undoFunc, ev, {}); // {} = jqui dummy
  5179. },
  5180. /* Selection
  5181. ------------------------------------------------------------------------------------------------------------------*/
  5182. // Selects a date range on the view. `start` and `end` are both Moments.
  5183. // `ev` is the native mouse event that begin the interaction.
  5184. select: function(range, ev) {
  5185. this.unselect(ev);
  5186. this.renderSelection(range);
  5187. this.reportSelection(range, ev);
  5188. },
  5189. // Renders a visual indication of the selection
  5190. renderSelection: function(range) {
  5191. // subclasses should implement
  5192. },
  5193. // Called when a new selection is made. Updates internal state and triggers handlers.
  5194. reportSelection: function(range, ev) {
  5195. this.isSelected = true;
  5196. this.trigger('select', null, range.start, range.end, ev);
  5197. },
  5198. // Undoes a selection. updates in the internal state and triggers handlers.
  5199. // `ev` is the native mouse event that began the interaction.
  5200. unselect: function(ev) {
  5201. if (this.isSelected) {
  5202. this.isSelected = false;
  5203. this.destroySelection();
  5204. this.trigger('unselect', null, ev);
  5205. }
  5206. },
  5207. // Unrenders a visual indication of selection
  5208. destroySelection: function() {
  5209. // subclasses should implement
  5210. },
  5211. // Handler for unselecting when the user clicks something and the 'unselectAuto' setting is on
  5212. documentMousedown: function(ev) {
  5213. var ignore;
  5214. // is there a selection, and has the user made a proper left click?
  5215. if (this.isSelected && this.opt('unselectAuto') && isPrimaryMouseButton(ev)) {
  5216. // only unselect if the clicked element is not identical to or inside of an 'unselectCancel' element
  5217. ignore = this.opt('unselectCancel');
  5218. if (!ignore || !$(ev.target).closest(ignore).length) {
  5219. this.unselect(ev);
  5220. }
  5221. }
  5222. },
  5223. /* Date Utils
  5224. ------------------------------------------------------------------------------------------------------------------*/
  5225. // Initializes internal variables related to calculating hidden days-of-week
  5226. initHiddenDays: function() {
  5227. var hiddenDays = this.opt('hiddenDays') || []; // array of day-of-week indices that are hidden
  5228. var isHiddenDayHash = []; // is the day-of-week hidden? (hash with day-of-week-index -> bool)
  5229. var dayCnt = 0;
  5230. var i;
  5231. if (this.opt('weekends') === false) {
  5232. hiddenDays.push(0, 6); // 0=sunday, 6=saturday
  5233. }
  5234. for (i = 0; i < 7; i++) {
  5235. if (
  5236. !(isHiddenDayHash[i] = $.inArray(i, hiddenDays) !== -1)
  5237. ) {
  5238. dayCnt++;
  5239. }
  5240. }
  5241. if (!dayCnt) {
  5242. throw 'invalid hiddenDays'; // all days were hidden? bad.
  5243. }
  5244. this.isHiddenDayHash = isHiddenDayHash;
  5245. },
  5246. // Is the current day hidden?
  5247. // `day` is a day-of-week index (0-6), or a Moment
  5248. isHiddenDay: function(day) {
  5249. if (moment.isMoment(day)) {
  5250. day = day.day();
  5251. }
  5252. return this.isHiddenDayHash[day];
  5253. },
  5254. // Incrementing the current day until it is no longer a hidden day, returning a copy.
  5255. // If the initial value of `date` is not a hidden day, don't do anything.
  5256. // Pass `isExclusive` as `true` if you are dealing with an end date.
  5257. // `inc` defaults to `1` (increment one day forward each time)
  5258. skipHiddenDays: function(date, inc, isExclusive) {
  5259. var out = date.clone();
  5260. inc = inc || 1;
  5261. while (
  5262. this.isHiddenDayHash[(out.day() + (isExclusive ? inc : 0) + 7) % 7]
  5263. ) {
  5264. out.add(inc, 'days');
  5265. }
  5266. return out;
  5267. },
  5268. // Returns the date range of the full days the given range visually appears to occupy.
  5269. // Returns a new range object.
  5270. computeDayRange: function(range) {
  5271. var startDay = range.start.clone().stripTime(); // the beginning of the day the range starts
  5272. var end = range.end;
  5273. var endDay = null;
  5274. var endTimeMS;
  5275. if (end) {
  5276. endDay = end.clone().stripTime(); // the beginning of the day the range exclusively ends
  5277. endTimeMS = +end.time(); // # of milliseconds into `endDay`
  5278. // If the end time is actually inclusively part of the next day and is equal to or
  5279. // beyond the next day threshold, adjust the end to be the exclusive end of `endDay`.
  5280. // Otherwise, leaving it as inclusive will cause it to exclude `endDay`.
  5281. if (endTimeMS && endTimeMS >= this.nextDayThreshold) {
  5282. endDay.add(1, 'days');
  5283. }
  5284. }
  5285. // If no end was specified, or if it is within `startDay` but not past nextDayThreshold,
  5286. // assign the default duration of one day.
  5287. if (!end || endDay <= startDay) {
  5288. endDay = startDay.clone().add(1, 'days');
  5289. }
  5290. return { start: startDay, end: endDay };
  5291. },
  5292. // Does the given event visually appear to occupy more than one day?
  5293. isMultiDayEvent: function(event) {
  5294. var range = this.computeDayRange(event); // event is range-ish
  5295. return range.end.diff(range.start, 'days') > 1;
  5296. }
  5297. });
  5298. function Calendar(element, instanceOptions) {
  5299. var t = this;
  5300. // Build options object
  5301. // -----------------------------------------------------------------------------------
  5302. // Precedence (lowest to highest): defaults, rtlDefaults, langOptions, instanceOptions
  5303. instanceOptions = instanceOptions || {};
  5304. var options = mergeOptions({}, defaults, instanceOptions);
  5305. var langOptions;
  5306. // determine language options
  5307. if (options.lang in langOptionHash) {
  5308. langOptions = langOptionHash[options.lang];
  5309. }
  5310. else {
  5311. langOptions = langOptionHash[defaults.lang];
  5312. }
  5313. if (langOptions) { // if language options exist, rebuild...
  5314. options = mergeOptions({}, defaults, langOptions, instanceOptions);
  5315. }
  5316. if (options.isRTL) { // is isRTL, rebuild...
  5317. options = mergeOptions({}, defaults, rtlDefaults, langOptions || {}, instanceOptions);
  5318. }
  5319. // Exports
  5320. // -----------------------------------------------------------------------------------
  5321. t.options = options;
  5322. t.render = render;
  5323. t.destroy = destroy;
  5324. t.refetchEvents = refetchEvents;
  5325. t.reportEvents = reportEvents;
  5326. t.reportEventChange = reportEventChange;
  5327. t.rerenderEvents = renderEvents; // `renderEvents` serves as a rerender. an API method
  5328. t.changeView = changeView;
  5329. t.select = select;
  5330. t.unselect = unselect;
  5331. t.prev = prev;
  5332. t.next = next;
  5333. t.prevYear = prevYear;
  5334. t.nextYear = nextYear;
  5335. t.today = today;
  5336. t.gotoDate = gotoDate;
  5337. t.incrementDate = incrementDate;
  5338. t.zoomTo = zoomTo;
  5339. t.getDate = getDate;
  5340. t.getCalendar = getCalendar;
  5341. t.getView = getView;
  5342. t.option = option;
  5343. t.trigger = trigger;
  5344. t.isValidViewType = isValidViewType;
  5345. t.getViewButtonText = getViewButtonText;
  5346. // Language-data Internals
  5347. // -----------------------------------------------------------------------------------
  5348. // Apply overrides to the current language's data
  5349. var localeData = createObject( // make a cheap copy
  5350. getMomentLocaleData(options.lang) // will fall back to en
  5351. );
  5352. if (options.monthNames) {
  5353. localeData._months = options.monthNames;
  5354. }
  5355. if (options.monthNamesShort) {
  5356. localeData._monthsShort = options.monthNamesShort;
  5357. }
  5358. if (options.dayNames) {
  5359. localeData._weekdays = options.dayNames;
  5360. }
  5361. if (options.dayNamesShort) {
  5362. localeData._weekdaysShort = options.dayNamesShort;
  5363. }
  5364. if (options.firstDay != null) {
  5365. var _week = createObject(localeData._week); // _week: { dow: # }
  5366. _week.dow = options.firstDay;
  5367. localeData._week = _week;
  5368. }
  5369. // Calendar-specific Date Utilities
  5370. // -----------------------------------------------------------------------------------
  5371. t.defaultAllDayEventDuration = moment.duration(options.defaultAllDayEventDuration);
  5372. t.defaultTimedEventDuration = moment.duration(options.defaultTimedEventDuration);
  5373. // Builds a moment using the settings of the current calendar: timezone and language.
  5374. // Accepts anything the vanilla moment() constructor accepts.
  5375. t.moment = function() {
  5376. var mom;
  5377. if (options.timezone === 'local') {
  5378. mom = fc.moment.apply(null, arguments);
  5379. // Force the moment to be local, because fc.moment doesn't guarantee it.
  5380. if (mom.hasTime()) { // don't give ambiguously-timed moments a local zone
  5381. mom.local();
  5382. }
  5383. }
  5384. else if (options.timezone === 'UTC') {
  5385. mom = fc.moment.utc.apply(null, arguments); // process as UTC
  5386. }
  5387. else {
  5388. mom = fc.moment.parseZone.apply(null, arguments); // let the input decide the zone
  5389. }
  5390. if ('_locale' in mom) { // moment 2.8 and above
  5391. mom._locale = localeData;
  5392. }
  5393. else { // pre-moment-2.8
  5394. mom._lang = localeData;
  5395. }
  5396. return mom;
  5397. };
  5398. // Returns a boolean about whether or not the calendar knows how to calculate
  5399. // the timezone offset of arbitrary dates in the current timezone.
  5400. t.getIsAmbigTimezone = function() {
  5401. return options.timezone !== 'local' && options.timezone !== 'UTC';
  5402. };
  5403. // Returns a copy of the given date in the current timezone of it is ambiguously zoned.
  5404. // This will also give the date an unambiguous time.
  5405. t.rezoneDate = function(date) {
  5406. return t.moment(date.toArray());
  5407. };
  5408. // Returns a moment for the current date, as defined by the client's computer,
  5409. // or overridden by the `now` option.
  5410. t.getNow = function() {
  5411. var now = options.now;
  5412. if (typeof now === 'function') {
  5413. now = now();
  5414. }
  5415. return t.moment(now);
  5416. };
  5417. // Calculates the week number for a moment according to the calendar's
  5418. // `weekNumberCalculation` setting.
  5419. t.calculateWeekNumber = function(mom) {
  5420. var calc = options.weekNumberCalculation;
  5421. if (typeof calc === 'function') {
  5422. return calc(mom);
  5423. }
  5424. else if (calc === 'local') {
  5425. return mom.week();
  5426. }
  5427. else if (calc.toUpperCase() === 'ISO') {
  5428. return mom.isoWeek();
  5429. }
  5430. };
  5431. // Get an event's normalized end date. If not present, calculate it from the defaults.
  5432. t.getEventEnd = function(event) {
  5433. if (event.end) {
  5434. return event.end.clone();
  5435. }
  5436. else {
  5437. return t.getDefaultEventEnd(event.allDay, event.start);
  5438. }
  5439. };
  5440. // Given an event's allDay status and start date, return swhat its fallback end date should be.
  5441. t.getDefaultEventEnd = function(allDay, start) { // TODO: rename to computeDefaultEventEnd
  5442. var end = start.clone();
  5443. if (allDay) {
  5444. end.stripTime().add(t.defaultAllDayEventDuration);
  5445. }
  5446. else {
  5447. end.add(t.defaultTimedEventDuration);
  5448. }
  5449. if (t.getIsAmbigTimezone()) {
  5450. end.stripZone(); // we don't know what the tzo should be
  5451. }
  5452. return end;
  5453. };
  5454. // Produces a human-readable string for the given duration.
  5455. // Side-effect: changes the locale of the given duration.
  5456. function humanizeDuration(duration) {
  5457. return (duration.locale || duration.lang).call(duration, options.lang) // works moment-pre-2.8
  5458. .humanize();
  5459. }
  5460. // Imports
  5461. // -----------------------------------------------------------------------------------
  5462. EventManager.call(t, options);
  5463. var isFetchNeeded = t.isFetchNeeded;
  5464. var fetchEvents = t.fetchEvents;
  5465. // Locals
  5466. // -----------------------------------------------------------------------------------
  5467. var _element = element[0];
  5468. var header;
  5469. var headerElement;
  5470. var content;
  5471. var tm; // for making theme classes
  5472. var viewSpecCache = {};
  5473. var currentView;
  5474. var suggestedViewHeight;
  5475. var windowResizeProxy; // wraps the windowResize function
  5476. var ignoreWindowResize = 0;
  5477. var date;
  5478. var events = [];
  5479. // Main Rendering
  5480. // -----------------------------------------------------------------------------------
  5481. if (options.defaultDate != null) {
  5482. date = t.moment(options.defaultDate);
  5483. }
  5484. else {
  5485. date = t.getNow();
  5486. }
  5487. function render(inc) {
  5488. if (!content) {
  5489. initialRender();
  5490. }
  5491. else if (elementVisible()) {
  5492. // mainly for the public API
  5493. calcSize();
  5494. renderView(inc);
  5495. }
  5496. }
  5497. function initialRender() {
  5498. tm = options.theme ? 'ui' : 'fc';
  5499. element.addClass('fc');
  5500. if (options.isRTL) {
  5501. element.addClass('fc-rtl');
  5502. }
  5503. else {
  5504. element.addClass('fc-ltr');
  5505. }
  5506. if (options.theme) {
  5507. element.addClass('ui-widget');
  5508. }
  5509. else {
  5510. element.addClass('fc-unthemed');
  5511. }
  5512. content = $("<div class='fc-view-container'/>").prependTo(element);
  5513. header = new Header(t, options);
  5514. headerElement = header.render();
  5515. if (headerElement) {
  5516. element.prepend(headerElement);
  5517. }
  5518. changeView(options.defaultView);
  5519. if (options.handleWindowResize) {
  5520. windowResizeProxy = debounce(windowResize, options.windowResizeDelay); // prevents rapid calls
  5521. $(window).resize(windowResizeProxy);
  5522. }
  5523. }
  5524. function destroy() {
  5525. if (currentView) {
  5526. currentView.destroyView();
  5527. }
  5528. header.destroy();
  5529. content.remove();
  5530. element.removeClass('fc fc-ltr fc-rtl fc-unthemed ui-widget');
  5531. $(window).unbind('resize', windowResizeProxy);
  5532. }
  5533. function elementVisible() {
  5534. return element.is(':visible');
  5535. }
  5536. // View Rendering
  5537. // -----------------------------------------------------------------------------------
  5538. function changeView(viewType) {
  5539. renderView(0, viewType);
  5540. }
  5541. // Renders a view because of a date change, view-type change, or for the first time
  5542. function renderView(delta, viewType) {
  5543. ignoreWindowResize++;
  5544. // if viewType is changing, destroy the old view
  5545. if (currentView && viewType && currentView.type !== viewType) {
  5546. header.deactivateButton(currentView.type);
  5547. freezeContentHeight(); // prevent a scroll jump when view element is removed
  5548. if (currentView.start) { // rendered before?
  5549. currentView.destroyView();
  5550. }
  5551. currentView.el.remove();
  5552. currentView = null;
  5553. }
  5554. // if viewType changed, or the view was never created, create a fresh view
  5555. if (!currentView && viewType) {
  5556. currentView = instantiateView(viewType);
  5557. currentView.el = $("<div class='fc-view fc-" + viewType + "-view' />").appendTo(content);
  5558. header.activateButton(viewType);
  5559. }
  5560. if (currentView) {
  5561. // let the view determine what the delta means
  5562. if (delta < 0) {
  5563. date = currentView.computePrevDate(date);
  5564. }
  5565. else if (delta > 0) {
  5566. date = currentView.computeNextDate(date);
  5567. }
  5568. // render or rerender the view
  5569. if (
  5570. !currentView.start || // never rendered before
  5571. delta || // explicit date window change
  5572. !date.isWithin(currentView.intervalStart, currentView.intervalEnd) // implicit date window change
  5573. ) {
  5574. if (elementVisible()) {
  5575. freezeContentHeight();
  5576. if (currentView.start) { // rendered before?
  5577. currentView.destroyView();
  5578. }
  5579. currentView.setDate(date);
  5580. currentView.renderView();
  5581. unfreezeContentHeight();
  5582. // need to do this after View::render, so dates are calculated
  5583. updateTitle();
  5584. updateTodayButton();
  5585. getAndRenderEvents();
  5586. }
  5587. }
  5588. }
  5589. unfreezeContentHeight(); // undo any lone freezeContentHeight calls
  5590. ignoreWindowResize--;
  5591. }
  5592. // View Instantiation
  5593. // -----------------------------------------------------------------------------------
  5594. // Given a view name for a custom view or a standard view, creates a ready-to-go View object
  5595. function instantiateView(viewType) {
  5596. var spec = getViewSpec(viewType);
  5597. return new spec['class'](t, spec.options, viewType);
  5598. }
  5599. // Gets information about how to create a view
  5600. function getViewSpec(requestedViewType) {
  5601. var allDefaultButtonText = options.defaultButtonText || {};
  5602. var allButtonText = options.buttonText || {};
  5603. var hash = options.views || {}; // the `views` option object
  5604. var viewType = requestedViewType;
  5605. var viewOptionsChain = [];
  5606. var viewOptions;
  5607. var viewClass;
  5608. var duration, unit, unitIsSingle = false;
  5609. var buttonText;
  5610. if (viewSpecCache[requestedViewType]) {
  5611. return viewSpecCache[requestedViewType];
  5612. }
  5613. function processSpecInput(input) {
  5614. if (typeof input === 'function') {
  5615. viewClass = input;
  5616. }
  5617. else if (typeof input === 'object') {
  5618. $.extend(viewOptions, input);
  5619. }
  5620. }
  5621. // iterate up a view's spec ancestor chain util we find a class to instantiate
  5622. while (viewType && !viewClass) {
  5623. viewOptions = {}; // only for this specific view in the ancestry
  5624. processSpecInput(fcViews[viewType]); // $.fullCalendar.views, lower precedence
  5625. processSpecInput(hash[viewType]); // options at initialization, higher precedence
  5626. viewOptionsChain.unshift(viewOptions); // record older ancestors first
  5627. viewType = viewOptions.type;
  5628. }
  5629. viewOptionsChain.unshift({}); // jQuery's extend needs at least one arg
  5630. viewOptions = $.extend.apply($, viewOptionsChain); // combine all, newer ancestors overwritting old
  5631. if (viewClass) {
  5632. duration = viewOptions.duration || viewClass.duration;
  5633. if (duration) {
  5634. duration = moment.duration(duration);
  5635. unit = computeIntervalUnit(duration);
  5636. unitIsSingle = computeIntervalAs(unit, duration) === 1;
  5637. }
  5638. // options that are specified per the view's duration, like "week" or "day"
  5639. if (unitIsSingle && hash[unit]) {
  5640. viewOptions = $.extend({}, hash[unit], viewOptions); // lowest priority
  5641. }
  5642. // compute the final text for the button representing this view
  5643. buttonText =
  5644. allButtonText[requestedViewType] || // init options, like "agendaWeek"
  5645. (unitIsSingle ? allButtonText[unit] : null) || // init options, like "week"
  5646. allDefaultButtonText[requestedViewType] || // lang data, like "agendaWeek"
  5647. (unitIsSingle ? allDefaultButtonText[unit] : null) || // lang data, like "week"
  5648. viewOptions.buttonText ||
  5649. viewClass.buttonText ||
  5650. (duration ? humanizeDuration(duration) : null) ||
  5651. requestedViewType;
  5652. return (viewSpecCache[requestedViewType] = {
  5653. 'class': viewClass,
  5654. options: viewOptions,
  5655. buttonText: buttonText
  5656. });
  5657. }
  5658. }
  5659. // Returns a boolean about whether the view is okay to instantiate at some point
  5660. function isValidViewType(viewType) {
  5661. return Boolean(getViewSpec(viewType));
  5662. }
  5663. // Gets the text that should be displayed on a view's button in the header
  5664. function getViewButtonText(viewType) {
  5665. var spec = getViewSpec(viewType);
  5666. if (spec) {
  5667. return spec.buttonText;
  5668. }
  5669. }
  5670. // Resizing
  5671. // -----------------------------------------------------------------------------------
  5672. t.getSuggestedViewHeight = function() {
  5673. if (suggestedViewHeight === undefined) {
  5674. calcSize();
  5675. }
  5676. return suggestedViewHeight;
  5677. };
  5678. t.isHeightAuto = function() {
  5679. return options.contentHeight === 'auto' || options.height === 'auto';
  5680. };
  5681. function updateSize(shouldRecalc) {
  5682. if (elementVisible()) {
  5683. if (shouldRecalc) {
  5684. _calcSize();
  5685. }
  5686. ignoreWindowResize++;
  5687. currentView.updateSize(true); // isResize=true. will poll getSuggestedViewHeight() and isHeightAuto()
  5688. ignoreWindowResize--;
  5689. return true; // signal success
  5690. }
  5691. }
  5692. function calcSize() {
  5693. if (elementVisible()) {
  5694. _calcSize();
  5695. }
  5696. }
  5697. function _calcSize() { // assumes elementVisible
  5698. if (typeof options.contentHeight === 'number') { // exists and not 'auto'
  5699. suggestedViewHeight = options.contentHeight;
  5700. }
  5701. else if (typeof options.height === 'number') { // exists and not 'auto'
  5702. suggestedViewHeight = options.height - (headerElement ? headerElement.outerHeight(true) : 0);
  5703. }
  5704. else {
  5705. suggestedViewHeight = Math.round(content.width() / Math.max(options.aspectRatio, .5));
  5706. }
  5707. }
  5708. function windowResize(ev) {
  5709. if (
  5710. !ignoreWindowResize &&
  5711. ev.target === window && // so we don't process jqui "resize" events that have bubbled up
  5712. currentView.start // view has already been rendered
  5713. ) {
  5714. if (updateSize(true)) {
  5715. currentView.trigger('windowResize', _element);
  5716. }
  5717. }
  5718. }
  5719. /* Event Fetching/Rendering
  5720. -----------------------------------------------------------------------------*/
  5721. // TODO: going forward, most of this stuff should be directly handled by the view
  5722. function refetchEvents() { // can be called as an API method
  5723. destroyEvents(); // so that events are cleared before user starts waiting for AJAX
  5724. fetchAndRenderEvents();
  5725. }
  5726. function renderEvents() { // destroys old events if previously rendered
  5727. if (elementVisible()) {
  5728. freezeContentHeight();
  5729. currentView.destroyViewEvents(); // no performance cost if never rendered
  5730. currentView.renderViewEvents(events);
  5731. unfreezeContentHeight();
  5732. }
  5733. }
  5734. function destroyEvents() {
  5735. freezeContentHeight();
  5736. currentView.destroyViewEvents();
  5737. unfreezeContentHeight();
  5738. }
  5739. function getAndRenderEvents() {
  5740. if (!options.lazyFetching || isFetchNeeded(currentView.start, currentView.end)) {
  5741. fetchAndRenderEvents();
  5742. }
  5743. else {
  5744. renderEvents();
  5745. }
  5746. }
  5747. function fetchAndRenderEvents() {
  5748. fetchEvents(currentView.start, currentView.end);
  5749. // ... will call reportEvents
  5750. // ... which will call renderEvents
  5751. }
  5752. // called when event data arrives
  5753. function reportEvents(_events) {
  5754. events = _events;
  5755. renderEvents();
  5756. }
  5757. // called when a single event's data has been changed
  5758. function reportEventChange() {
  5759. renderEvents();
  5760. }
  5761. /* Header Updating
  5762. -----------------------------------------------------------------------------*/
  5763. function updateTitle() {
  5764. header.updateTitle(currentView.computeTitle());
  5765. }
  5766. function updateTodayButton() {
  5767. var now = t.getNow();
  5768. if (now.isWithin(currentView.intervalStart, currentView.intervalEnd)) {
  5769. header.disableButton('today');
  5770. }
  5771. else {
  5772. header.enableButton('today');
  5773. }
  5774. }
  5775. /* Selection
  5776. -----------------------------------------------------------------------------*/
  5777. function select(start, end) {
  5778. start = t.moment(start);
  5779. if (end) {
  5780. end = t.moment(end);
  5781. }
  5782. else if (start.hasTime()) {
  5783. end = start.clone().add(t.defaultTimedEventDuration);
  5784. }
  5785. else {
  5786. end = start.clone().add(t.defaultAllDayEventDuration);
  5787. }
  5788. currentView.select({ start: start, end: end }); // accepts a range
  5789. }
  5790. function unselect() { // safe to be called before renderView
  5791. if (currentView) {
  5792. currentView.unselect();
  5793. }
  5794. }
  5795. /* Date
  5796. -----------------------------------------------------------------------------*/
  5797. function prev() {
  5798. renderView(-1);
  5799. }
  5800. function next() {
  5801. renderView(1);
  5802. }
  5803. function prevYear() {
  5804. date.add(-1, 'years');
  5805. renderView();
  5806. }
  5807. function nextYear() {
  5808. date.add(1, 'years');
  5809. renderView();
  5810. }
  5811. function today() {
  5812. date = t.getNow();
  5813. renderView();
  5814. }
  5815. function gotoDate(dateInput) {
  5816. date = t.moment(dateInput);
  5817. renderView();
  5818. }
  5819. function incrementDate(delta) {
  5820. date.add(moment.duration(delta));
  5821. renderView();
  5822. }
  5823. // Forces navigation to a view for the given date.
  5824. // `viewType` can be a specific view name or a generic one like "week" or "day".
  5825. function zoomTo(newDate, viewType) {
  5826. var viewStr;
  5827. var match;
  5828. if (!viewType || !isValidViewType(viewType)) { // a general view name, or "auto"
  5829. viewType = viewType || 'day';
  5830. viewStr = header.getViewsWithButtons().join(' '); // space-separated string of all the views in the header
  5831. // try to match a general view name, like "week", against a specific one, like "agendaWeek"
  5832. match = viewStr.match(new RegExp('\\w+' + capitaliseFirstLetter(viewType)));
  5833. // fall back to the day view being used in the header
  5834. if (!match) {
  5835. match = viewStr.match(/\w+Day/);
  5836. }
  5837. viewType = match ? match[0] : 'agendaDay'; // fall back to agendaDay
  5838. }
  5839. date = newDate;
  5840. changeView(viewType);
  5841. }
  5842. function getDate() {
  5843. return date.clone();
  5844. }
  5845. /* Height "Freezing"
  5846. -----------------------------------------------------------------------------*/
  5847. function freezeContentHeight() {
  5848. content.css({
  5849. width: '100%',
  5850. height: content.height(),
  5851. overflow: 'hidden'
  5852. });
  5853. }
  5854. function unfreezeContentHeight() {
  5855. content.css({
  5856. width: '',
  5857. height: '',
  5858. overflow: ''
  5859. });
  5860. }
  5861. /* Misc
  5862. -----------------------------------------------------------------------------*/
  5863. function getCalendar() {
  5864. return t;
  5865. }
  5866. function getView() {
  5867. return currentView;
  5868. }
  5869. function option(name, value) {
  5870. if (value === undefined) {
  5871. return options[name];
  5872. }
  5873. if (name == 'height' || name == 'contentHeight' || name == 'aspectRatio') {
  5874. options[name] = value;
  5875. updateSize(true); // true = allow recalculation of height
  5876. }
  5877. }
  5878. function trigger(name, thisObj) {
  5879. if (options[name]) {
  5880. return options[name].apply(
  5881. thisObj || _element,
  5882. Array.prototype.slice.call(arguments, 2)
  5883. );
  5884. }
  5885. }
  5886. }
  5887. /* Top toolbar area with buttons and title
  5888. ----------------------------------------------------------------------------------------------------------------------*/
  5889. // TODO: rename all header-related things to "toolbar"
  5890. function Header(calendar, options) {
  5891. var t = this;
  5892. // exports
  5893. t.render = render;
  5894. t.destroy = destroy;
  5895. t.updateTitle = updateTitle;
  5896. t.activateButton = activateButton;
  5897. t.deactivateButton = deactivateButton;
  5898. t.disableButton = disableButton;
  5899. t.enableButton = enableButton;
  5900. t.getViewsWithButtons = getViewsWithButtons;
  5901. // locals
  5902. var el = $();
  5903. var viewsWithButtons = [];
  5904. var tm;
  5905. function render() {
  5906. var sections = options.header;
  5907. tm = options.theme ? 'ui' : 'fc';
  5908. if (sections) {
  5909. el = $("<div class='fc-toolbar'/>")
  5910. .append(renderSection('left'))
  5911. .append(renderSection('right'))
  5912. .append(renderSection('center'))
  5913. .append('<div class="fc-clear"/>');
  5914. return el;
  5915. }
  5916. }
  5917. function destroy() {
  5918. el.remove();
  5919. }
  5920. function renderSection(position) {
  5921. var sectionEl = $('<div class="fc-' + position + '"/>');
  5922. var buttonStr = options.header[position];
  5923. if (buttonStr) {
  5924. $.each(buttonStr.split(' '), function(i) {
  5925. var groupChildren = $();
  5926. var isOnlyButtons = true;
  5927. var groupEl;
  5928. $.each(this.split(','), function(j, buttonName) {
  5929. var buttonClick;
  5930. var themeIcon;
  5931. var normalIcon;
  5932. var defaultText;
  5933. var viewText; // highest priority
  5934. var customText;
  5935. var innerHtml;
  5936. var classes;
  5937. var button;
  5938. if (buttonName == 'title') {
  5939. groupChildren = groupChildren.add($('<h2>&nbsp;</h2>')); // we always want it to take up height
  5940. isOnlyButtons = false;
  5941. }
  5942. else {
  5943. if (calendar[buttonName]) { // a calendar method
  5944. buttonClick = function() {
  5945. calendar[buttonName]();
  5946. };
  5947. }
  5948. else if (calendar.isValidViewType(buttonName)) { // a view type
  5949. buttonClick = function() {
  5950. calendar.changeView(buttonName);
  5951. };
  5952. viewsWithButtons.push(buttonName);
  5953. viewText = calendar.getViewButtonText(buttonName);
  5954. }
  5955. if (buttonClick) {
  5956. // smartProperty allows different text per view button (ex: "Agenda Week" vs "Basic Week")
  5957. themeIcon = smartProperty(options.themeButtonIcons, buttonName);
  5958. normalIcon = smartProperty(options.buttonIcons, buttonName);
  5959. defaultText = smartProperty(options.defaultButtonText, buttonName); // from languages
  5960. customText = smartProperty(options.buttonText, buttonName);
  5961. if (viewText || customText) {
  5962. innerHtml = htmlEscape(viewText || customText);
  5963. }
  5964. else if (themeIcon && options.theme) {
  5965. innerHtml = "<span class='ui-icon ui-icon-" + themeIcon + "'></span>";
  5966. }
  5967. else if (normalIcon && !options.theme) {
  5968. innerHtml = "<span class='fc-icon fc-icon-" + normalIcon + "'></span>";
  5969. }
  5970. else {
  5971. innerHtml = htmlEscape(defaultText || buttonName);
  5972. }
  5973. classes = [
  5974. 'fc-' + buttonName + '-button',
  5975. tm + '-button',
  5976. tm + '-state-default'
  5977. ];
  5978. button = $( // type="button" so that it doesn't submit a form
  5979. '<button type="button" class="' + classes.join(' ') + '">' +
  5980. innerHtml +
  5981. '</button>'
  5982. )
  5983. .click(function() {
  5984. // don't process clicks for disabled buttons
  5985. if (!button.hasClass(tm + '-state-disabled')) {
  5986. buttonClick();
  5987. // after the click action, if the button becomes the "active" tab, or disabled,
  5988. // it should never have a hover class, so remove it now.
  5989. if (
  5990. button.hasClass(tm + '-state-active') ||
  5991. button.hasClass(tm + '-state-disabled')
  5992. ) {
  5993. button.removeClass(tm + '-state-hover');
  5994. }
  5995. }
  5996. })
  5997. .mousedown(function() {
  5998. // the *down* effect (mouse pressed in).
  5999. // only on buttons that are not the "active" tab, or disabled
  6000. button
  6001. .not('.' + tm + '-state-active')
  6002. .not('.' + tm + '-state-disabled')
  6003. .addClass(tm + '-state-down');
  6004. })
  6005. .mouseup(function() {
  6006. // undo the *down* effect
  6007. button.removeClass(tm + '-state-down');
  6008. })
  6009. .hover(
  6010. function() {
  6011. // the *hover* effect.
  6012. // only on buttons that are not the "active" tab, or disabled
  6013. button
  6014. .not('.' + tm + '-state-active')
  6015. .not('.' + tm + '-state-disabled')
  6016. .addClass(tm + '-state-hover');
  6017. },
  6018. function() {
  6019. // undo the *hover* effect
  6020. button
  6021. .removeClass(tm + '-state-hover')
  6022. .removeClass(tm + '-state-down'); // if mouseleave happens before mouseup
  6023. }
  6024. );
  6025. groupChildren = groupChildren.add(button);
  6026. }
  6027. }
  6028. });
  6029. if (isOnlyButtons) {
  6030. groupChildren
  6031. .first().addClass(tm + '-corner-left').end()
  6032. .last().addClass(tm + '-corner-right').end();
  6033. }
  6034. if (groupChildren.length > 1) {
  6035. groupEl = $('<div/>');
  6036. if (isOnlyButtons) {
  6037. groupEl.addClass('fc-button-group');
  6038. }
  6039. groupEl.append(groupChildren);
  6040. sectionEl.append(groupEl);
  6041. }
  6042. else {
  6043. sectionEl.append(groupChildren); // 1 or 0 children
  6044. }
  6045. });
  6046. }
  6047. return sectionEl;
  6048. }
  6049. function updateTitle(text) {
  6050. el.find('h2').text(text);
  6051. }
  6052. function activateButton(buttonName) {
  6053. el.find('.fc-' + buttonName + '-button')
  6054. .addClass(tm + '-state-active');
  6055. }
  6056. function deactivateButton(buttonName) {
  6057. el.find('.fc-' + buttonName + '-button')
  6058. .removeClass(tm + '-state-active');
  6059. }
  6060. function disableButton(buttonName) {
  6061. el.find('.fc-' + buttonName + '-button')
  6062. .attr('disabled', 'disabled')
  6063. .addClass(tm + '-state-disabled');
  6064. }
  6065. function enableButton(buttonName) {
  6066. el.find('.fc-' + buttonName + '-button')
  6067. .removeAttr('disabled')
  6068. .removeClass(tm + '-state-disabled');
  6069. }
  6070. function getViewsWithButtons() {
  6071. return viewsWithButtons;
  6072. }
  6073. }
  6074. fc.sourceNormalizers = [];
  6075. fc.sourceFetchers = [];
  6076. var ajaxDefaults = {
  6077. dataType: 'json',
  6078. cache: false
  6079. };
  6080. var eventGUID = 1;
  6081. function EventManager(options) { // assumed to be a calendar
  6082. var t = this;
  6083. // exports
  6084. t.isFetchNeeded = isFetchNeeded;
  6085. t.fetchEvents = fetchEvents;
  6086. t.addEventSource = addEventSource;
  6087. t.removeEventSource = removeEventSource;
  6088. t.updateEvent = updateEvent;
  6089. t.renderEvent = renderEvent;
  6090. t.removeEvents = removeEvents;
  6091. t.clientEvents = clientEvents;
  6092. t.mutateEvent = mutateEvent;
  6093. t.normalizeEventDateProps = normalizeEventDateProps;
  6094. t.ensureVisibleEventRange = ensureVisibleEventRange;
  6095. // imports
  6096. var trigger = t.trigger;
  6097. var getView = t.getView;
  6098. var reportEvents = t.reportEvents;
  6099. // locals
  6100. var stickySource = { events: [] };
  6101. var sources = [ stickySource ];
  6102. var rangeStart, rangeEnd;
  6103. var currentFetchID = 0;
  6104. var pendingSourceCnt = 0;
  6105. var loadingLevel = 0;
  6106. var cache = []; // holds events that have already been expanded
  6107. $.each(
  6108. (options.events ? [ options.events ] : []).concat(options.eventSources || []),
  6109. function(i, sourceInput) {
  6110. var source = buildEventSource(sourceInput);
  6111. if (source) {
  6112. sources.push(source);
  6113. }
  6114. }
  6115. );
  6116. /* Fetching
  6117. -----------------------------------------------------------------------------*/
  6118. function isFetchNeeded(start, end) {
  6119. return !rangeStart || // nothing has been fetched yet?
  6120. // or, a part of the new range is outside of the old range? (after normalizing)
  6121. start.clone().stripZone() < rangeStart.clone().stripZone() ||
  6122. end.clone().stripZone() > rangeEnd.clone().stripZone();
  6123. }
  6124. function fetchEvents(start, end) {
  6125. rangeStart = start;
  6126. rangeEnd = end;
  6127. cache = [];
  6128. var fetchID = ++currentFetchID;
  6129. var len = sources.length;
  6130. pendingSourceCnt = len;
  6131. for (var i=0; i<len; i++) {
  6132. fetchEventSource(sources[i], fetchID);
  6133. }
  6134. }
  6135. function fetchEventSource(source, fetchID) {
  6136. _fetchEventSource(source, function(eventInputs) {
  6137. var isArraySource = $.isArray(source.events);
  6138. var i, eventInput;
  6139. var abstractEvent;
  6140. if (fetchID == currentFetchID) {
  6141. if (eventInputs) {
  6142. for (i = 0; i < eventInputs.length; i++) {
  6143. eventInput = eventInputs[i];
  6144. if (isArraySource) { // array sources have already been convert to Event Objects
  6145. abstractEvent = eventInput;
  6146. }
  6147. else {
  6148. abstractEvent = buildEventFromInput(eventInput, source);
  6149. }
  6150. if (abstractEvent) { // not false (an invalid event)
  6151. cache.push.apply(
  6152. cache,
  6153. expandEvent(abstractEvent) // add individual expanded events to the cache
  6154. );
  6155. }
  6156. }
  6157. }
  6158. pendingSourceCnt--;
  6159. if (!pendingSourceCnt) {
  6160. reportEvents(cache);
  6161. }
  6162. }
  6163. });
  6164. }
  6165. function _fetchEventSource(source, callback) {
  6166. var i;
  6167. var fetchers = fc.sourceFetchers;
  6168. var res;
  6169. for (i=0; i<fetchers.length; i++) {
  6170. res = fetchers[i].call(
  6171. t, // this, the Calendar object
  6172. source,
  6173. rangeStart.clone(),
  6174. rangeEnd.clone(),
  6175. options.timezone,
  6176. callback
  6177. );
  6178. if (res === true) {
  6179. // the fetcher is in charge. made its own async request
  6180. return;
  6181. }
  6182. else if (typeof res == 'object') {
  6183. // the fetcher returned a new source. process it
  6184. _fetchEventSource(res, callback);
  6185. return;
  6186. }
  6187. }
  6188. var events = source.events;
  6189. if (events) {
  6190. if ($.isFunction(events)) {
  6191. pushLoading();
  6192. events.call(
  6193. t, // this, the Calendar object
  6194. rangeStart.clone(),
  6195. rangeEnd.clone(),
  6196. options.timezone,
  6197. function(events) {
  6198. callback(events);
  6199. popLoading();
  6200. }
  6201. );
  6202. }
  6203. else if ($.isArray(events)) {
  6204. callback(events);
  6205. }
  6206. else {
  6207. callback();
  6208. }
  6209. }else{
  6210. var url = source.url;
  6211. if (url) {
  6212. var success = source.success;
  6213. var error = source.error;
  6214. var complete = source.complete;
  6215. // retrieve any outbound GET/POST $.ajax data from the options
  6216. var customData;
  6217. if ($.isFunction(source.data)) {
  6218. // supplied as a function that returns a key/value object
  6219. customData = source.data();
  6220. }
  6221. else {
  6222. // supplied as a straight key/value object
  6223. customData = source.data;
  6224. }
  6225. // use a copy of the custom data so we can modify the parameters
  6226. // and not affect the passed-in object.
  6227. var data = $.extend({}, customData || {});
  6228. var startParam = firstDefined(source.startParam, options.startParam);
  6229. var endParam = firstDefined(source.endParam, options.endParam);
  6230. var timezoneParam = firstDefined(source.timezoneParam, options.timezoneParam);
  6231. if (startParam) {
  6232. data[startParam] = rangeStart.format();
  6233. }
  6234. if (endParam) {
  6235. data[endParam] = rangeEnd.format();
  6236. }
  6237. if (options.timezone && options.timezone != 'local') {
  6238. data[timezoneParam] = options.timezone;
  6239. }
  6240. pushLoading();
  6241. $.ajax($.extend({}, ajaxDefaults, source, {
  6242. data: data,
  6243. success: function(events) {
  6244. events = events || [];
  6245. var res = applyAll(success, this, arguments);
  6246. if ($.isArray(res)) {
  6247. events = res;
  6248. }
  6249. callback(events);
  6250. },
  6251. error: function() {
  6252. applyAll(error, this, arguments);
  6253. callback();
  6254. },
  6255. complete: function() {
  6256. applyAll(complete, this, arguments);
  6257. popLoading();
  6258. }
  6259. }));
  6260. }else{
  6261. callback();
  6262. }
  6263. }
  6264. }
  6265. /* Sources
  6266. -----------------------------------------------------------------------------*/
  6267. function addEventSource(sourceInput) {
  6268. var source = buildEventSource(sourceInput);
  6269. if (source) {
  6270. sources.push(source);
  6271. pendingSourceCnt++;
  6272. fetchEventSource(source, currentFetchID); // will eventually call reportEvents
  6273. }
  6274. }
  6275. function buildEventSource(sourceInput) { // will return undefined if invalid source
  6276. var normalizers = fc.sourceNormalizers;
  6277. var source;
  6278. var i;
  6279. if ($.isFunction(sourceInput) || $.isArray(sourceInput)) {
  6280. source = { events: sourceInput };
  6281. }
  6282. else if (typeof sourceInput === 'string') {
  6283. source = { url: sourceInput };
  6284. }
  6285. else if (typeof sourceInput === 'object') {
  6286. source = $.extend({}, sourceInput); // shallow copy
  6287. }
  6288. if (source) {
  6289. // TODO: repeat code, same code for event classNames
  6290. if (source.className) {
  6291. if (typeof source.className === 'string') {
  6292. source.className = source.className.split(/\s+/);
  6293. }
  6294. // otherwise, assumed to be an array
  6295. }
  6296. else {
  6297. source.className = [];
  6298. }
  6299. // for array sources, we convert to standard Event Objects up front
  6300. if ($.isArray(source.events)) {
  6301. source.origArray = source.events; // for removeEventSource
  6302. source.events = $.map(source.events, function(eventInput) {
  6303. return buildEventFromInput(eventInput, source);
  6304. });
  6305. }
  6306. for (i=0; i<normalizers.length; i++) {
  6307. normalizers[i].call(t, source);
  6308. }
  6309. return source;
  6310. }
  6311. }
  6312. function removeEventSource(source) {
  6313. sources = $.grep(sources, function(src) {
  6314. return !isSourcesEqual(src, source);
  6315. });
  6316. // remove all client events from that source
  6317. cache = $.grep(cache, function(e) {
  6318. return !isSourcesEqual(e.source, source);
  6319. });
  6320. reportEvents(cache);
  6321. }
  6322. function isSourcesEqual(source1, source2) {
  6323. return source1 && source2 && getSourcePrimitive(source1) == getSourcePrimitive(source2);
  6324. }
  6325. function getSourcePrimitive(source) {
  6326. return (
  6327. (typeof source === 'object') ? // a normalized event source?
  6328. (source.origArray || source.googleCalendarId || source.url || source.events) : // get the primitive
  6329. null
  6330. ) ||
  6331. source; // the given argument *is* the primitive
  6332. }
  6333. /* Manipulation
  6334. -----------------------------------------------------------------------------*/
  6335. // Only ever called from the externally-facing API
  6336. function updateEvent(event) {
  6337. // massage start/end values, even if date string values
  6338. event.start = t.moment(event.start);
  6339. if (event.end) {
  6340. event.end = t.moment(event.end);
  6341. }
  6342. else {
  6343. event.end = null;
  6344. }
  6345. mutateEvent(event, getMiscEventProps(event)); // will handle start/end/allDay normalization
  6346. reportEvents(cache); // reports event modifications (so we can redraw)
  6347. }
  6348. // Returns a hash of misc event properties that should be copied over to related events.
  6349. function getMiscEventProps(event) {
  6350. var props = {};
  6351. $.each(event, function(name, val) {
  6352. if (isMiscEventPropName(name)) {
  6353. if (val !== undefined && isAtomic(val)) { // a defined non-object
  6354. props[name] = val;
  6355. }
  6356. }
  6357. });
  6358. return props;
  6359. }
  6360. // non-date-related, non-id-related, non-secret
  6361. function isMiscEventPropName(name) {
  6362. return !/^_|^(id|allDay|start|end)$/.test(name);
  6363. }
  6364. // returns the expanded events that were created
  6365. function renderEvent(eventInput, stick) {
  6366. var abstractEvent = buildEventFromInput(eventInput);
  6367. var events;
  6368. var i, event;
  6369. if (abstractEvent) { // not false (a valid input)
  6370. events = expandEvent(abstractEvent);
  6371. for (i = 0; i < events.length; i++) {
  6372. event = events[i];
  6373. if (!event.source) {
  6374. if (stick) {
  6375. stickySource.events.push(event);
  6376. event.source = stickySource;
  6377. }
  6378. cache.push(event);
  6379. }
  6380. }
  6381. reportEvents(cache);
  6382. return events;
  6383. }
  6384. return [];
  6385. }
  6386. function removeEvents(filter) {
  6387. var eventID;
  6388. var i;
  6389. if (filter == null) { // null or undefined. remove all events
  6390. filter = function() { return true; }; // will always match
  6391. }
  6392. else if (!$.isFunction(filter)) { // an event ID
  6393. eventID = filter + '';
  6394. filter = function(event) {
  6395. return event._id == eventID;
  6396. };
  6397. }
  6398. // Purge event(s) from our local cache
  6399. cache = $.grep(cache, filter, true); // inverse=true
  6400. // Remove events from array sources.
  6401. // This works because they have been converted to official Event Objects up front.
  6402. // (and as a result, event._id has been calculated).
  6403. for (i=0; i<sources.length; i++) {
  6404. if ($.isArray(sources[i].events)) {
  6405. sources[i].events = $.grep(sources[i].events, filter, true);
  6406. }
  6407. }
  6408. reportEvents(cache);
  6409. }
  6410. function clientEvents(filter) {
  6411. if ($.isFunction(filter)) {
  6412. return $.grep(cache, filter);
  6413. }
  6414. else if (filter != null) { // not null, not undefined. an event ID
  6415. filter += '';
  6416. return $.grep(cache, function(e) {
  6417. return e._id == filter;
  6418. });
  6419. }
  6420. return cache; // else, return all
  6421. }
  6422. /* Loading State
  6423. -----------------------------------------------------------------------------*/
  6424. function pushLoading() {
  6425. if (!(loadingLevel++)) {
  6426. trigger('loading', null, true, getView());
  6427. }
  6428. }
  6429. function popLoading() {
  6430. if (!(--loadingLevel)) {
  6431. trigger('loading', null, false, getView());
  6432. }
  6433. }
  6434. /* Event Normalization
  6435. -----------------------------------------------------------------------------*/
  6436. // Given a raw object with key/value properties, returns an "abstract" Event object.
  6437. // An "abstract" event is an event that, if recurring, will not have been expanded yet.
  6438. // Will return `false` when input is invalid.
  6439. // `source` is optional
  6440. function buildEventFromInput(input, source) {
  6441. var out = {};
  6442. var start, end;
  6443. var allDay;
  6444. if (options.eventDataTransform) {
  6445. input = options.eventDataTransform(input);
  6446. }
  6447. if (source && source.eventDataTransform) {
  6448. input = source.eventDataTransform(input);
  6449. }
  6450. // Copy all properties over to the resulting object.
  6451. // The special-case properties will be copied over afterwards.
  6452. $.extend(out, input);
  6453. if (source) {
  6454. out.source = source;
  6455. }
  6456. out._id = input._id || (input.id === undefined ? '_fc' + eventGUID++ : input.id + '');
  6457. if (input.className) {
  6458. if (typeof input.className == 'string') {
  6459. out.className = input.className.split(/\s+/);
  6460. }
  6461. else { // assumed to be an array
  6462. out.className = input.className;
  6463. }
  6464. }
  6465. else {
  6466. out.className = [];
  6467. }
  6468. start = input.start || input.date; // "date" is an alias for "start"
  6469. end = input.end;
  6470. // parse as a time (Duration) if applicable
  6471. if (isTimeString(start)) {
  6472. start = moment.duration(start);
  6473. }
  6474. if (isTimeString(end)) {
  6475. end = moment.duration(end);
  6476. }
  6477. if (input.dow || moment.isDuration(start) || moment.isDuration(end)) {
  6478. // the event is "abstract" (recurring) so don't calculate exact start/end dates just yet
  6479. out.start = start ? moment.duration(start) : null; // will be a Duration or null
  6480. out.end = end ? moment.duration(end) : null; // will be a Duration or null
  6481. out._recurring = true; // our internal marker
  6482. }
  6483. else {
  6484. if (start) {
  6485. start = t.moment(start);
  6486. if (!start.isValid()) {
  6487. return false;
  6488. }
  6489. }
  6490. if (end) {
  6491. end = t.moment(end);
  6492. if (!end.isValid()) {
  6493. end = null; // let defaults take over
  6494. }
  6495. }
  6496. allDay = input.allDay;
  6497. if (allDay === undefined) { // still undefined? fallback to default
  6498. allDay = firstDefined(
  6499. source ? source.allDayDefault : undefined,
  6500. options.allDayDefault
  6501. );
  6502. // still undefined? normalizeEventDateProps will calculate it
  6503. }
  6504. assignDatesToEvent(start, end, allDay, out);
  6505. }
  6506. return out;
  6507. }
  6508. // Normalizes and assigns the given dates to the given partially-formed event object.
  6509. // NOTE: mutates the given start/end moments. does not make a copy.
  6510. function assignDatesToEvent(start, end, allDay, event) {
  6511. event.start = start;
  6512. event.end = end;
  6513. event.allDay = allDay;
  6514. normalizeEventDateProps(event);
  6515. backupEventDates(event);
  6516. }
  6517. // Ensures the allDay property exists.
  6518. // Ensures the start/end dates are consistent with allDay and forceEventDuration.
  6519. // Accepts an Event object, or a plain object with event-ish properties.
  6520. // NOTE: Will modify the given object.
  6521. function normalizeEventDateProps(props) {
  6522. if (props.allDay == null) {
  6523. props.allDay = !(props.start.hasTime() || (props.end && props.end.hasTime()));
  6524. }
  6525. if (props.allDay) {
  6526. props.start.stripTime();
  6527. if (props.end) {
  6528. props.end.stripTime();
  6529. }
  6530. }
  6531. else {
  6532. if (!props.start.hasTime()) {
  6533. props.start = t.rezoneDate(props.start); // will also give it a 00:00 time
  6534. }
  6535. if (props.end && !props.end.hasTime()) {
  6536. props.end = t.rezoneDate(props.end); // will also give it a 00:00 time
  6537. }
  6538. }
  6539. if (props.end && !props.end.isAfter(props.start)) {
  6540. props.end = null;
  6541. }
  6542. if (!props.end) {
  6543. if (options.forceEventDuration) {
  6544. props.end = t.getDefaultEventEnd(props.allDay, props.start);
  6545. }
  6546. else {
  6547. props.end = null;
  6548. }
  6549. }
  6550. }
  6551. // If `range` is a proper range with a start and end, returns the original object.
  6552. // If missing an end, computes a new range with an end, computing it as if it were an event.
  6553. // TODO: make this a part of the event -> eventRange system
  6554. function ensureVisibleEventRange(range) {
  6555. var allDay;
  6556. if (!range.end) {
  6557. allDay = range.allDay; // range might be more event-ish than we think
  6558. if (allDay == null) {
  6559. allDay = !range.start.hasTime();
  6560. }
  6561. range = {
  6562. start: range.start,
  6563. end: t.getDefaultEventEnd(allDay, range.start)
  6564. };
  6565. }
  6566. return range;
  6567. }
  6568. // If the given event is a recurring event, break it down into an array of individual instances.
  6569. // If not a recurring event, return an array with the single original event.
  6570. // If given a falsy input (probably because of a failed buildEventFromInput call), returns an empty array.
  6571. // HACK: can override the recurring window by providing custom rangeStart/rangeEnd (for businessHours).
  6572. function expandEvent(abstractEvent, _rangeStart, _rangeEnd) {
  6573. var events = [];
  6574. var dowHash;
  6575. var dow;
  6576. var i;
  6577. var date;
  6578. var startTime, endTime;
  6579. var start, end;
  6580. var event;
  6581. _rangeStart = _rangeStart || rangeStart;
  6582. _rangeEnd = _rangeEnd || rangeEnd;
  6583. if (abstractEvent) {
  6584. if (abstractEvent._recurring) {
  6585. // make a boolean hash as to whether the event occurs on each day-of-week
  6586. if ((dow = abstractEvent.dow)) {
  6587. dowHash = {};
  6588. for (i = 0; i < dow.length; i++) {
  6589. dowHash[dow[i]] = true;
  6590. }
  6591. }
  6592. // iterate through every day in the current range
  6593. date = _rangeStart.clone().stripTime(); // holds the date of the current day
  6594. while (date.isBefore(_rangeEnd)) {
  6595. if (!dowHash || dowHash[date.day()]) { // if everyday, or this particular day-of-week
  6596. startTime = abstractEvent.start; // the stored start and end properties are times (Durations)
  6597. endTime = abstractEvent.end; // "
  6598. start = date.clone();
  6599. end = null;
  6600. if (startTime) {
  6601. start = start.time(startTime);
  6602. }
  6603. if (endTime) {
  6604. end = date.clone().time(endTime);
  6605. }
  6606. event = $.extend({}, abstractEvent); // make a copy of the original
  6607. assignDatesToEvent(
  6608. start, end,
  6609. !startTime && !endTime, // allDay?
  6610. event
  6611. );
  6612. events.push(event);
  6613. }
  6614. date.add(1, 'days');
  6615. }
  6616. }
  6617. else {
  6618. events.push(abstractEvent); // return the original event. will be a one-item array
  6619. }
  6620. }
  6621. return events;
  6622. }
  6623. /* Event Modification Math
  6624. -----------------------------------------------------------------------------------------*/
  6625. // Modifies an event and all related events by applying the given properties.
  6626. // Special date-diffing logic is used for manipulation of dates.
  6627. // If `props` does not contain start/end dates, the updated values are assumed to be the event's current start/end.
  6628. // All date comparisons are done against the event's pristine _start and _end dates.
  6629. // Returns an object with delta information and a function to undo all operations.
  6630. //
  6631. function mutateEvent(event, props) {
  6632. var miscProps = {};
  6633. var clearEnd;
  6634. var dateDelta;
  6635. var durationDelta;
  6636. var undoFunc;
  6637. props = props || {};
  6638. // ensure new date-related values to compare against
  6639. if (!props.start) {
  6640. props.start = event.start.clone();
  6641. }
  6642. if (props.end === undefined) {
  6643. props.end = event.end ? event.end.clone() : null;
  6644. }
  6645. if (props.allDay == null) { // is null or undefined?
  6646. props.allDay = event.allDay;
  6647. }
  6648. normalizeEventDateProps(props); // massages start/end/allDay
  6649. // clear the end date if explicitly changed to null
  6650. clearEnd = event._end !== null && props.end === null;
  6651. // compute the delta for moving the start and end dates together
  6652. if (props.allDay) {
  6653. dateDelta = diffDay(props.start, event._start); // whole-day diff from start-of-day
  6654. }
  6655. else {
  6656. dateDelta = diffDayTime(props.start, event._start);
  6657. }
  6658. // compute the delta for moving the end date (after applying dateDelta)
  6659. if (!clearEnd && props.end) {
  6660. durationDelta = diffDayTime(
  6661. // new duration
  6662. props.end,
  6663. props.start
  6664. ).subtract(diffDayTime(
  6665. // subtract old duration
  6666. event._end || t.getDefaultEventEnd(event._allDay, event._start),
  6667. event._start
  6668. ));
  6669. }
  6670. // gather all non-date-related properties
  6671. $.each(props, function(name, val) {
  6672. if (isMiscEventPropName(name)) {
  6673. if (val !== undefined) {
  6674. miscProps[name] = val;
  6675. }
  6676. }
  6677. });
  6678. // apply the operations to the event and all related events
  6679. undoFunc = mutateEvents(
  6680. clientEvents(event._id), // get events with this ID
  6681. clearEnd,
  6682. props.allDay,
  6683. dateDelta,
  6684. durationDelta,
  6685. miscProps
  6686. );
  6687. return {
  6688. dateDelta: dateDelta,
  6689. durationDelta: durationDelta,
  6690. undo: undoFunc
  6691. };
  6692. }
  6693. // Modifies an array of events in the following ways (operations are in order):
  6694. // - clear the event's `end`
  6695. // - convert the event to allDay
  6696. // - add `dateDelta` to the start and end
  6697. // - add `durationDelta` to the event's duration
  6698. // - assign `miscProps` to the event
  6699. //
  6700. // Returns a function that can be called to undo all the operations.
  6701. //
  6702. // TODO: don't use so many closures. possible memory issues when lots of events with same ID.
  6703. //
  6704. function mutateEvents(events, clearEnd, allDay, dateDelta, durationDelta, miscProps) {
  6705. var isAmbigTimezone = t.getIsAmbigTimezone();
  6706. var undoFunctions = [];
  6707. // normalize zero-length deltas to be null
  6708. if (dateDelta && !dateDelta.valueOf()) { dateDelta = null; }
  6709. if (durationDelta && !durationDelta.valueOf()) { durationDelta = null; }
  6710. $.each(events, function(i, event) {
  6711. var oldProps;
  6712. var newProps;
  6713. // build an object holding all the old values, both date-related and misc.
  6714. // for the undo function.
  6715. oldProps = {
  6716. start: event.start.clone(),
  6717. end: event.end ? event.end.clone() : null,
  6718. allDay: event.allDay
  6719. };
  6720. $.each(miscProps, function(name) {
  6721. oldProps[name] = event[name];
  6722. });
  6723. // new date-related properties. work off the original date snapshot.
  6724. // ok to use references because they will be thrown away when backupEventDates is called.
  6725. newProps = {
  6726. start: event._start,
  6727. end: event._end,
  6728. allDay: event._allDay
  6729. };
  6730. if (clearEnd) {
  6731. newProps.end = null;
  6732. }
  6733. newProps.allDay = allDay;
  6734. normalizeEventDateProps(newProps); // massages start/end/allDay
  6735. if (dateDelta) {
  6736. newProps.start.add(dateDelta);
  6737. if (newProps.end) {
  6738. newProps.end.add(dateDelta);
  6739. }
  6740. }
  6741. if (durationDelta) {
  6742. if (!newProps.end) {
  6743. newProps.end = t.getDefaultEventEnd(newProps.allDay, newProps.start);
  6744. }
  6745. newProps.end.add(durationDelta);
  6746. }
  6747. // if the dates have changed, and we know it is impossible to recompute the
  6748. // timezone offsets, strip the zone.
  6749. if (
  6750. isAmbigTimezone &&
  6751. !newProps.allDay &&
  6752. (dateDelta || durationDelta)
  6753. ) {
  6754. newProps.start.stripZone();
  6755. if (newProps.end) {
  6756. newProps.end.stripZone();
  6757. }
  6758. }
  6759. $.extend(event, miscProps, newProps); // copy over misc props, then date-related props
  6760. backupEventDates(event); // regenerate internal _start/_end/_allDay
  6761. undoFunctions.push(function() {
  6762. $.extend(event, oldProps);
  6763. backupEventDates(event); // regenerate internal _start/_end/_allDay
  6764. });
  6765. });
  6766. return function() {
  6767. for (var i = 0; i < undoFunctions.length; i++) {
  6768. undoFunctions[i]();
  6769. }
  6770. };
  6771. }
  6772. /* Business Hours
  6773. -----------------------------------------------------------------------------------------*/
  6774. t.getBusinessHoursEvents = getBusinessHoursEvents;
  6775. // Returns an array of events as to when the business hours occur in the given view.
  6776. // Abuse of our event system :(
  6777. function getBusinessHoursEvents() {
  6778. var optionVal = options.businessHours;
  6779. var defaultVal = {
  6780. className: 'fc-nonbusiness',
  6781. start: '09:00',
  6782. end: '17:00',
  6783. dow: [ 1, 2, 3, 4, 5 ], // monday - friday
  6784. rendering: 'inverse-background'
  6785. };
  6786. var view = t.getView();
  6787. var eventInput;
  6788. if (optionVal) {
  6789. if (typeof optionVal === 'object') {
  6790. // option value is an object that can override the default business hours
  6791. eventInput = $.extend({}, defaultVal, optionVal);
  6792. }
  6793. else {
  6794. // option value is `true`. use default business hours
  6795. eventInput = defaultVal;
  6796. }
  6797. }
  6798. if (eventInput) {
  6799. return expandEvent(
  6800. buildEventFromInput(eventInput),
  6801. view.start,
  6802. view.end
  6803. );
  6804. }
  6805. return [];
  6806. }
  6807. /* Overlapping / Constraining
  6808. -----------------------------------------------------------------------------------------*/
  6809. t.isEventRangeAllowed = isEventRangeAllowed;
  6810. t.isSelectionRangeAllowed = isSelectionRangeAllowed;
  6811. t.isExternalDropRangeAllowed = isExternalDropRangeAllowed;
  6812. function isEventRangeAllowed(range, event) {
  6813. var source = event.source || {};
  6814. var constraint = firstDefined(
  6815. event.constraint,
  6816. source.constraint,
  6817. options.eventConstraint
  6818. );
  6819. var overlap = firstDefined(
  6820. event.overlap,
  6821. source.overlap,
  6822. options.eventOverlap
  6823. );
  6824. range = ensureVisibleEventRange(range); // ensure a proper range with an end for isRangeAllowed
  6825. return isRangeAllowed(range, constraint, overlap, event);
  6826. }
  6827. function isSelectionRangeAllowed(range) {
  6828. return isRangeAllowed(range, options.selectConstraint, options.selectOverlap);
  6829. }
  6830. // when `eventProps` is defined, consider this an event.
  6831. // `eventProps` can contain misc non-date-related info about the event.
  6832. function isExternalDropRangeAllowed(range, eventProps) {
  6833. var eventInput;
  6834. var event;
  6835. // note: very similar logic is in View's reportExternalDrop
  6836. if (eventProps) {
  6837. eventInput = $.extend({}, eventProps, range);
  6838. event = expandEvent(buildEventFromInput(eventInput))[0];
  6839. }
  6840. if (event) {
  6841. return isEventRangeAllowed(range, event);
  6842. }
  6843. else { // treat it as a selection
  6844. range = ensureVisibleEventRange(range); // ensure a proper range with an end for isSelectionRangeAllowed
  6845. return isSelectionRangeAllowed(range);
  6846. }
  6847. }
  6848. // Returns true if the given range (caused by an event drop/resize or a selection) is allowed to exist
  6849. // according to the constraint/overlap settings.
  6850. // `event` is not required if checking a selection.
  6851. function isRangeAllowed(range, constraint, overlap, event) {
  6852. var constraintEvents;
  6853. var anyContainment;
  6854. var i, otherEvent;
  6855. var otherOverlap;
  6856. // normalize. fyi, we're normalizing in too many places :(
  6857. range = {
  6858. start: range.start.clone().stripZone(),
  6859. end: range.end.clone().stripZone()
  6860. };
  6861. // the range must be fully contained by at least one of produced constraint events
  6862. if (constraint != null) {
  6863. // not treated as an event! intermediate data structure
  6864. // TODO: use ranges in the future
  6865. constraintEvents = constraintToEvents(constraint);
  6866. anyContainment = false;
  6867. for (i = 0; i < constraintEvents.length; i++) {
  6868. if (eventContainsRange(constraintEvents[i], range)) {
  6869. anyContainment = true;
  6870. break;
  6871. }
  6872. }
  6873. if (!anyContainment) {
  6874. return false;
  6875. }
  6876. }
  6877. for (i = 0; i < cache.length; i++) { // loop all events and detect overlap
  6878. otherEvent = cache[i];
  6879. // don't compare the event to itself or other related [repeating] events
  6880. if (event && event._id === otherEvent._id) {
  6881. continue;
  6882. }
  6883. // there needs to be an actual intersection before disallowing anything
  6884. if (eventIntersectsRange(otherEvent, range)) {
  6885. // evaluate overlap for the given range and short-circuit if necessary
  6886. if (overlap === false) {
  6887. return false;
  6888. }
  6889. else if (typeof overlap === 'function' && !overlap(otherEvent, event)) {
  6890. return false;
  6891. }
  6892. // if we are computing if the given range is allowable for an event, consider the other event's
  6893. // EventObject-specific or Source-specific `overlap` property
  6894. if (event) {
  6895. otherOverlap = firstDefined(
  6896. otherEvent.overlap,
  6897. (otherEvent.source || {}).overlap
  6898. // we already considered the global `eventOverlap`
  6899. );
  6900. if (otherOverlap === false) {
  6901. return false;
  6902. }
  6903. if (typeof otherOverlap === 'function' && !otherOverlap(event, otherEvent)) {
  6904. return false;
  6905. }
  6906. }
  6907. }
  6908. }
  6909. return true;
  6910. }
  6911. // Given an event input from the API, produces an array of event objects. Possible event inputs:
  6912. // 'businessHours'
  6913. // An event ID (number or string)
  6914. // An object with specific start/end dates or a recurring event (like what businessHours accepts)
  6915. function constraintToEvents(constraintInput) {
  6916. if (constraintInput === 'businessHours') {
  6917. return getBusinessHoursEvents();
  6918. }
  6919. if (typeof constraintInput === 'object') {
  6920. return expandEvent(buildEventFromInput(constraintInput));
  6921. }
  6922. return clientEvents(constraintInput); // probably an ID
  6923. }
  6924. // Does the event's date range fully contain the given range?
  6925. // start/end already assumed to have stripped zones :(
  6926. function eventContainsRange(event, range) {
  6927. var eventStart = event.start.clone().stripZone();
  6928. var eventEnd = t.getEventEnd(event).stripZone();
  6929. return range.start >= eventStart && range.end <= eventEnd;
  6930. }
  6931. // Does the event's date range intersect with the given range?
  6932. // start/end already assumed to have stripped zones :(
  6933. function eventIntersectsRange(event, range) {
  6934. var eventStart = event.start.clone().stripZone();
  6935. var eventEnd = t.getEventEnd(event).stripZone();
  6936. return range.start < eventEnd && range.end > eventStart;
  6937. }
  6938. }
  6939. // updates the "backup" properties, which are preserved in order to compute diffs later on.
  6940. function backupEventDates(event) {
  6941. event._allDay = event.allDay;
  6942. event._start = event.start.clone();
  6943. event._end = event.end ? event.end.clone() : null;
  6944. }
  6945. /* An abstract class for the "basic" views, as well as month view. Renders one or more rows of day cells.
  6946. ----------------------------------------------------------------------------------------------------------------------*/
  6947. // It is a manager for a DayGrid subcomponent, which does most of the heavy lifting.
  6948. // It is responsible for managing width/height.
  6949. var BasicView = fcViews.basic = View.extend({
  6950. dayGrid: null, // the main subcomponent that does most of the heavy lifting
  6951. dayNumbersVisible: false, // display day numbers on each day cell?
  6952. weekNumbersVisible: false, // display week numbers along the side?
  6953. weekNumberWidth: null, // width of all the week-number cells running down the side
  6954. headRowEl: null, // the fake row element of the day-of-week header
  6955. initialize: function() {
  6956. this.dayGrid = new DayGrid(this);
  6957. this.coordMap = this.dayGrid.coordMap; // the view's date-to-cell mapping is identical to the subcomponent's
  6958. },
  6959. // Sets the display range and computes all necessary dates
  6960. setRange: function(range) {
  6961. View.prototype.setRange.call(this, range); // call the super-method
  6962. this.dayGrid.breakOnWeeks = /year|month|week/.test(this.intervalUnit); // do before setRange
  6963. this.dayGrid.setRange(range);
  6964. },
  6965. // Compute the value to feed into setRange. Overrides superclass.
  6966. computeRange: function(date) {
  6967. var range = View.prototype.computeRange.call(this, date); // get value from the super-method
  6968. // year and month views should be aligned with weeks. this is already done for week
  6969. if (/year|month/.test(range.intervalUnit)) {
  6970. range.start.startOf('week');
  6971. range.start = this.skipHiddenDays(range.start);
  6972. // make end-of-week if not already
  6973. if (range.end.weekday()) {
  6974. range.end.add(1, 'week').startOf('week');
  6975. range.end = this.skipHiddenDays(range.end, -1, true); // exclusively move backwards
  6976. }
  6977. }
  6978. return range;
  6979. },
  6980. // Renders the view into `this.el`, which should already be assigned
  6981. render: function() {
  6982. this.dayNumbersVisible = this.dayGrid.rowCnt > 1; // TODO: make grid responsible
  6983. this.weekNumbersVisible = this.opt('weekNumbers');
  6984. this.dayGrid.numbersVisible = this.dayNumbersVisible || this.weekNumbersVisible;
  6985. this.el.addClass('fc-basic-view').html(this.renderHtml());
  6986. this.headRowEl = this.el.find('thead .fc-row');
  6987. this.scrollerEl = this.el.find('.fc-day-grid-container');
  6988. this.dayGrid.coordMap.containerEl = this.scrollerEl; // constrain clicks/etc to the dimensions of the scroller
  6989. this.dayGrid.el = this.el.find('.fc-day-grid');
  6990. this.dayGrid.render(this.hasRigidRows());
  6991. },
  6992. // Make subcomponents ready for cleanup
  6993. destroy: function() {
  6994. this.dayGrid.destroy();
  6995. View.prototype.destroy.call(this); // call the super-method
  6996. },
  6997. // Builds the HTML skeleton for the view.
  6998. // The day-grid component will render inside of a container defined by this HTML.
  6999. renderHtml: function() {
  7000. return '' +
  7001. '<table>' +
  7002. '<thead>' +
  7003. '<tr>' +
  7004. '<td class="' + this.widgetHeaderClass + '">' +
  7005. this.dayGrid.headHtml() + // render the day-of-week headers
  7006. '</td>' +
  7007. '</tr>' +
  7008. '</thead>' +
  7009. '<tbody>' +
  7010. '<tr>' +
  7011. '<td class="' + this.widgetContentClass + '">' +
  7012. '<div class="fc-day-grid-container">' +
  7013. '<div class="fc-day-grid"/>' +
  7014. '</div>' +
  7015. '</td>' +
  7016. '</tr>' +
  7017. '</tbody>' +
  7018. '</table>';
  7019. },
  7020. // Generates the HTML that will go before the day-of week header cells.
  7021. // Queried by the DayGrid subcomponent when generating rows. Ordering depends on isRTL.
  7022. headIntroHtml: function() {
  7023. if (this.weekNumbersVisible) {
  7024. return '' +
  7025. '<th class="fc-week-number ' + this.widgetHeaderClass + '" ' + this.weekNumberStyleAttr() + '>' +
  7026. '<span>' + // needed for matchCellWidths
  7027. htmlEscape(this.opt('weekNumberTitle')) +
  7028. '</span>' +
  7029. '</th>';
  7030. }
  7031. },
  7032. // Generates the HTML that will go before content-skeleton cells that display the day/week numbers.
  7033. // Queried by the DayGrid subcomponent. Ordering depends on isRTL.
  7034. numberIntroHtml: function(row) {
  7035. if (this.weekNumbersVisible) {
  7036. return '' +
  7037. '<td class="fc-week-number" ' + this.weekNumberStyleAttr() + '>' +
  7038. '<span>' + // needed for matchCellWidths
  7039. this.calendar.calculateWeekNumber(this.dayGrid.getCell(row, 0).start) +
  7040. '</span>' +
  7041. '</td>';
  7042. }
  7043. },
  7044. // Generates the HTML that goes before the day bg cells for each day-row.
  7045. // Queried by the DayGrid subcomponent. Ordering depends on isRTL.
  7046. dayIntroHtml: function() {
  7047. if (this.weekNumbersVisible) {
  7048. return '<td class="fc-week-number ' + this.widgetContentClass + '" ' +
  7049. this.weekNumberStyleAttr() + '></td>';
  7050. }
  7051. },
  7052. // Generates the HTML that goes before every other type of row generated by DayGrid. Ordering depends on isRTL.
  7053. // Affects helper-skeleton and highlight-skeleton rows.
  7054. introHtml: function() {
  7055. if (this.weekNumbersVisible) {
  7056. return '<td class="fc-week-number" ' + this.weekNumberStyleAttr() + '></td>';
  7057. }
  7058. },
  7059. // Generates the HTML for the <td>s of the "number" row in the DayGrid's content skeleton.
  7060. // The number row will only exist if either day numbers or week numbers are turned on.
  7061. numberCellHtml: function(cell) {
  7062. var date = cell.start;
  7063. var classes;
  7064. if (!this.dayNumbersVisible) { // if there are week numbers but not day numbers
  7065. return '<td/>'; // will create an empty space above events :(
  7066. }
  7067. classes = this.dayGrid.getDayClasses(date);
  7068. classes.unshift('fc-day-number');
  7069. return '' +
  7070. '<td class="' + classes.join(' ') + '" data-date="' + date.format() + '">' +
  7071. date.date() +
  7072. '</td>';
  7073. },
  7074. // Generates an HTML attribute string for setting the width of the week number column, if it is known
  7075. weekNumberStyleAttr: function() {
  7076. if (this.weekNumberWidth !== null) {
  7077. return 'style="width:' + this.weekNumberWidth + 'px"';
  7078. }
  7079. return '';
  7080. },
  7081. // Determines whether each row should have a constant height
  7082. hasRigidRows: function() {
  7083. var eventLimit = this.opt('eventLimit');
  7084. return eventLimit && typeof eventLimit !== 'number';
  7085. },
  7086. /* Dimensions
  7087. ------------------------------------------------------------------------------------------------------------------*/
  7088. // Refreshes the horizontal dimensions of the view
  7089. updateWidth: function() {
  7090. if (this.weekNumbersVisible) {
  7091. // Make sure all week number cells running down the side have the same width.
  7092. // Record the width for cells created later.
  7093. this.weekNumberWidth = matchCellWidths(
  7094. this.el.find('.fc-week-number')
  7095. );
  7096. }
  7097. },
  7098. // Adjusts the vertical dimensions of the view to the specified values
  7099. setHeight: function(totalHeight, isAuto) {
  7100. var eventLimit = this.opt('eventLimit');
  7101. var scrollerHeight;
  7102. // reset all heights to be natural
  7103. unsetScroller(this.scrollerEl);
  7104. uncompensateScroll(this.headRowEl);
  7105. this.dayGrid.destroySegPopover(); // kill the "more" popover if displayed
  7106. // is the event limit a constant level number?
  7107. if (eventLimit && typeof eventLimit === 'number') {
  7108. this.dayGrid.limitRows(eventLimit); // limit the levels first so the height can redistribute after
  7109. }
  7110. scrollerHeight = this.computeScrollerHeight(totalHeight);
  7111. this.setGridHeight(scrollerHeight, isAuto);
  7112. // is the event limit dynamically calculated?
  7113. if (eventLimit && typeof eventLimit !== 'number') {
  7114. this.dayGrid.limitRows(eventLimit); // limit the levels after the grid's row heights have been set
  7115. }
  7116. if (!isAuto && setPotentialScroller(this.scrollerEl, scrollerHeight)) { // using scrollbars?
  7117. compensateScroll(this.headRowEl, getScrollbarWidths(this.scrollerEl));
  7118. // doing the scrollbar compensation might have created text overflow which created more height. redo
  7119. scrollerHeight = this.computeScrollerHeight(totalHeight);
  7120. this.scrollerEl.height(scrollerHeight);
  7121. this.restoreScroll();
  7122. }
  7123. },
  7124. // Sets the height of just the DayGrid component in this view
  7125. setGridHeight: function(height, isAuto) {
  7126. if (isAuto) {
  7127. undistributeHeight(this.dayGrid.rowEls); // let the rows be their natural height with no expanding
  7128. }
  7129. else {
  7130. distributeHeight(this.dayGrid.rowEls, height, true); // true = compensate for height-hogging rows
  7131. }
  7132. },
  7133. /* Events
  7134. ------------------------------------------------------------------------------------------------------------------*/
  7135. // Renders the given events onto the view and populates the segments array
  7136. renderEvents: function(events) {
  7137. this.dayGrid.renderEvents(events);
  7138. this.updateHeight(); // must compensate for events that overflow the row
  7139. },
  7140. // Retrieves all segment objects that are rendered in the view
  7141. getEventSegs: function() {
  7142. return this.dayGrid.getEventSegs();
  7143. },
  7144. // Unrenders all event elements and clears internal segment data
  7145. destroyEvents: function() {
  7146. this.recordScroll(); // removing events will reduce height and mess with the scroll, so record beforehand
  7147. this.dayGrid.destroyEvents();
  7148. // we DON'T need to call updateHeight() because:
  7149. // A) a renderEvents() call always happens after this, which will eventually call updateHeight()
  7150. // B) in IE8, this causes a flash whenever events are rerendered
  7151. },
  7152. /* Dragging (for both events and external elements)
  7153. ------------------------------------------------------------------------------------------------------------------*/
  7154. // A returned value of `true` signals that a mock "helper" event has been rendered.
  7155. renderDrag: function(dropLocation, seg) {
  7156. return this.dayGrid.renderDrag(dropLocation, seg);
  7157. },
  7158. destroyDrag: function() {
  7159. this.dayGrid.destroyDrag();
  7160. },
  7161. /* Selection
  7162. ------------------------------------------------------------------------------------------------------------------*/
  7163. // Renders a visual indication of a selection
  7164. renderSelection: function(range) {
  7165. this.dayGrid.renderSelection(range);
  7166. },
  7167. // Unrenders a visual indications of a selection
  7168. destroySelection: function() {
  7169. this.dayGrid.destroySelection();
  7170. }
  7171. });
  7172. /* A month view with day cells running in rows (one-per-week) and columns
  7173. ----------------------------------------------------------------------------------------------------------------------*/
  7174. setDefaults({
  7175. fixedWeekCount: true
  7176. });
  7177. var MonthView = fcViews.month = BasicView.extend({
  7178. // Produces information about what range to display
  7179. computeRange: function(date) {
  7180. var range = BasicView.prototype.computeRange.call(this, date); // get value from super-method
  7181. if (this.isFixedWeeks()) {
  7182. // ensure 6 weeks
  7183. range.end.add(
  7184. 6 - range.end.diff(range.start, 'weeks'),
  7185. 'weeks'
  7186. );
  7187. }
  7188. return range;
  7189. },
  7190. // Overrides the default BasicView behavior to have special multi-week auto-height logic
  7191. setGridHeight: function(height, isAuto) {
  7192. isAuto = isAuto || this.opt('weekMode') === 'variable'; // LEGACY: weekMode is deprecated
  7193. // if auto, make the height of each row the height that it would be if there were 6 weeks
  7194. if (isAuto) {
  7195. height *= this.rowCnt / 6;
  7196. }
  7197. distributeHeight(this.dayGrid.rowEls, height, !isAuto); // if auto, don't compensate for height-hogging rows
  7198. },
  7199. isFixedWeeks: function() {
  7200. var weekMode = this.opt('weekMode'); // LEGACY: weekMode is deprecated
  7201. if (weekMode) {
  7202. return weekMode === 'fixed'; // if any other type of weekMode, assume NOT fixed
  7203. }
  7204. return this.opt('fixedWeekCount');
  7205. }
  7206. });
  7207. MonthView.duration = { months: 1 };
  7208. /* A week view with simple day cells running horizontally
  7209. ----------------------------------------------------------------------------------------------------------------------*/
  7210. fcViews.basicWeek = {
  7211. type: 'basic',
  7212. duration: { weeks: 1 }
  7213. };
  7214. /* A view with a single simple day cell
  7215. ----------------------------------------------------------------------------------------------------------------------*/
  7216. fcViews.basicDay = {
  7217. type: 'basic',
  7218. duration: { days: 1 }
  7219. };
  7220. /* An abstract class for all agenda-related views. Displays one more columns with time slots running vertically.
  7221. ----------------------------------------------------------------------------------------------------------------------*/
  7222. // Is a manager for the TimeGrid subcomponent and possibly the DayGrid subcomponent (if allDaySlot is on).
  7223. // Responsible for managing width/height.
  7224. setDefaults({
  7225. allDaySlot: true,
  7226. allDayText: 'all-day',
  7227. scrollTime: '06:00:00',
  7228. slotDuration: '00:30:00',
  7229. minTime: '00:00:00',
  7230. maxTime: '24:00:00',
  7231. slotEventOverlap: true
  7232. });
  7233. var AGENDA_ALL_DAY_EVENT_LIMIT = 5;
  7234. fcViews.agenda = View.extend({ // AgendaView
  7235. timeGrid: null, // the main time-grid subcomponent of this view
  7236. dayGrid: null, // the "all-day" subcomponent. if all-day is turned off, this will be null
  7237. axisWidth: null, // the width of the time axis running down the side
  7238. noScrollRowEls: null, // set of fake row elements that must compensate when scrollerEl has scrollbars
  7239. // when the time-grid isn't tall enough to occupy the given height, we render an <hr> underneath
  7240. bottomRuleEl: null,
  7241. bottomRuleHeight: null,
  7242. initialize: function() {
  7243. this.timeGrid = new TimeGrid(this);
  7244. if (this.opt('allDaySlot')) { // should we display the "all-day" area?
  7245. this.dayGrid = new DayGrid(this); // the all-day subcomponent of this view
  7246. // the coordinate grid will be a combination of both subcomponents' grids
  7247. this.coordMap = new ComboCoordMap([
  7248. this.dayGrid.coordMap,
  7249. this.timeGrid.coordMap
  7250. ]);
  7251. }
  7252. else {
  7253. this.coordMap = this.timeGrid.coordMap;
  7254. }
  7255. },
  7256. /* Rendering
  7257. ------------------------------------------------------------------------------------------------------------------*/
  7258. // Sets the display range and computes all necessary dates
  7259. setRange: function(range) {
  7260. View.prototype.setRange.call(this, range); // call the super-method
  7261. this.timeGrid.setRange(range);
  7262. if (this.dayGrid) {
  7263. this.dayGrid.setRange(range);
  7264. }
  7265. },
  7266. // Renders the view into `this.el`, which has already been assigned
  7267. render: function() {
  7268. this.el.addClass('fc-agenda-view').html(this.renderHtml());
  7269. // the element that wraps the time-grid that will probably scroll
  7270. this.scrollerEl = this.el.find('.fc-time-grid-container');
  7271. this.timeGrid.coordMap.containerEl = this.scrollerEl; // don't accept clicks/etc outside of this
  7272. this.timeGrid.el = this.el.find('.fc-time-grid');
  7273. this.timeGrid.render();
  7274. // the <hr> that sometimes displays under the time-grid
  7275. this.bottomRuleEl = $('<hr class="' + this.widgetHeaderClass + '"/>')
  7276. .appendTo(this.timeGrid.el); // inject it into the time-grid
  7277. if (this.dayGrid) {
  7278. this.dayGrid.el = this.el.find('.fc-day-grid');
  7279. this.dayGrid.render();
  7280. // have the day-grid extend it's coordinate area over the <hr> dividing the two grids
  7281. this.dayGrid.bottomCoordPadding = this.dayGrid.el.next('hr').outerHeight();
  7282. }
  7283. this.noScrollRowEls = this.el.find('.fc-row:not(.fc-scroller *)'); // fake rows not within the scroller
  7284. },
  7285. // Make subcomponents ready for cleanup
  7286. destroy: function() {
  7287. this.timeGrid.destroy();
  7288. if (this.dayGrid) {
  7289. this.dayGrid.destroy();
  7290. }
  7291. View.prototype.destroy.call(this); // call the super-method
  7292. },
  7293. // Builds the HTML skeleton for the view.
  7294. // The day-grid and time-grid components will render inside containers defined by this HTML.
  7295. renderHtml: function() {
  7296. return '' +
  7297. '<table>' +
  7298. '<thead>' +
  7299. '<tr>' +
  7300. '<td class="' + this.widgetHeaderClass + '">' +
  7301. this.timeGrid.headHtml() + // render the day-of-week headers
  7302. '</td>' +
  7303. '</tr>' +
  7304. '</thead>' +
  7305. '<tbody>' +
  7306. '<tr>' +
  7307. '<td class="' + this.widgetContentClass + '">' +
  7308. (this.dayGrid ?
  7309. '<div class="fc-day-grid"/>' +
  7310. '<hr class="' + this.widgetHeaderClass + '"/>' :
  7311. ''
  7312. ) +
  7313. '<div class="fc-time-grid-container">' +
  7314. '<div class="fc-time-grid"/>' +
  7315. '</div>' +
  7316. '</td>' +
  7317. '</tr>' +
  7318. '</tbody>' +
  7319. '</table>';
  7320. },
  7321. // Generates the HTML that will go before the day-of week header cells.
  7322. // Queried by the TimeGrid subcomponent when generating rows. Ordering depends on isRTL.
  7323. headIntroHtml: function() {
  7324. var date;
  7325. var weekNumber;
  7326. var weekTitle;
  7327. var weekText;
  7328. if (this.opt('weekNumbers')) {
  7329. date = this.timeGrid.getCell(0).start;
  7330. weekNumber = this.calendar.calculateWeekNumber(date);
  7331. weekTitle = this.opt('weekNumberTitle');
  7332. if (this.opt('isRTL')) {
  7333. weekText = weekNumber + weekTitle;
  7334. }
  7335. else {
  7336. weekText = weekTitle + weekNumber;
  7337. }
  7338. return '' +
  7339. '<th class="fc-axis fc-week-number ' + this.widgetHeaderClass + '" ' + this.axisStyleAttr() + '>' +
  7340. '<span>' + // needed for matchCellWidths
  7341. htmlEscape(weekText) +
  7342. '</span>' +
  7343. '</th>';
  7344. }
  7345. else {
  7346. return '<th class="fc-axis ' + this.widgetHeaderClass + '" ' + this.axisStyleAttr() + '></th>';
  7347. }
  7348. },
  7349. // Generates the HTML that goes before the all-day cells.
  7350. // Queried by the DayGrid subcomponent when generating rows. Ordering depends on isRTL.
  7351. dayIntroHtml: function() {
  7352. return '' +
  7353. '<td class="fc-axis ' + this.widgetContentClass + '" ' + this.axisStyleAttr() + '>' +
  7354. '<span>' + // needed for matchCellWidths
  7355. (this.opt('allDayHtml') || htmlEscape(this.opt('allDayText'))) +
  7356. '</span>' +
  7357. '</td>';
  7358. },
  7359. // Generates the HTML that goes before the bg of the TimeGrid slot area. Long vertical column.
  7360. slotBgIntroHtml: function() {
  7361. return '<td class="fc-axis ' + this.widgetContentClass + '" ' + this.axisStyleAttr() + '></td>';
  7362. },
  7363. // Generates the HTML that goes before all other types of cells.
  7364. // Affects content-skeleton, helper-skeleton, highlight-skeleton for both the time-grid and day-grid.
  7365. // Queried by the TimeGrid and DayGrid subcomponents when generating rows. Ordering depends on isRTL.
  7366. introHtml: function() {
  7367. return '<td class="fc-axis" ' + this.axisStyleAttr() + '></td>';
  7368. },
  7369. // Generates an HTML attribute string for setting the width of the axis, if it is known
  7370. axisStyleAttr: function() {
  7371. if (this.axisWidth !== null) {
  7372. return 'style="width:' + this.axisWidth + 'px"';
  7373. }
  7374. return '';
  7375. },
  7376. /* Dimensions
  7377. ------------------------------------------------------------------------------------------------------------------*/
  7378. updateSize: function(isResize) {
  7379. if (isResize) {
  7380. this.timeGrid.resize();
  7381. }
  7382. View.prototype.updateSize.call(this, isResize);
  7383. },
  7384. // Refreshes the horizontal dimensions of the view
  7385. updateWidth: function() {
  7386. // make all axis cells line up, and record the width so newly created axis cells will have it
  7387. this.axisWidth = matchCellWidths(this.el.find('.fc-axis'));
  7388. },
  7389. // Adjusts the vertical dimensions of the view to the specified values
  7390. setHeight: function(totalHeight, isAuto) {
  7391. var eventLimit;
  7392. var scrollerHeight;
  7393. if (this.bottomRuleHeight === null) {
  7394. // calculate the height of the rule the very first time
  7395. this.bottomRuleHeight = this.bottomRuleEl.outerHeight();
  7396. }
  7397. this.bottomRuleEl.hide(); // .show() will be called later if this <hr> is necessary
  7398. // reset all dimensions back to the original state
  7399. this.scrollerEl.css('overflow', '');
  7400. unsetScroller(this.scrollerEl);
  7401. uncompensateScroll(this.noScrollRowEls);
  7402. // limit number of events in the all-day area
  7403. if (this.dayGrid) {
  7404. this.dayGrid.destroySegPopover(); // kill the "more" popover if displayed
  7405. eventLimit = this.opt('eventLimit');
  7406. if (eventLimit && typeof eventLimit !== 'number') {
  7407. eventLimit = AGENDA_ALL_DAY_EVENT_LIMIT; // make sure "auto" goes to a real number
  7408. }
  7409. if (eventLimit) {
  7410. this.dayGrid.limitRows(eventLimit);
  7411. }
  7412. }
  7413. if (!isAuto) { // should we force dimensions of the scroll container, or let the contents be natural height?
  7414. scrollerHeight = this.computeScrollerHeight(totalHeight);
  7415. if (setPotentialScroller(this.scrollerEl, scrollerHeight)) { // using scrollbars?
  7416. // make the all-day and header rows lines up
  7417. compensateScroll(this.noScrollRowEls, getScrollbarWidths(this.scrollerEl));
  7418. // the scrollbar compensation might have changed text flow, which might affect height, so recalculate
  7419. // and reapply the desired height to the scroller.
  7420. scrollerHeight = this.computeScrollerHeight(totalHeight);
  7421. this.scrollerEl.height(scrollerHeight);
  7422. this.restoreScroll();
  7423. }
  7424. else { // no scrollbars
  7425. // still, force a height and display the bottom rule (marks the end of day)
  7426. this.scrollerEl.height(scrollerHeight).css('overflow', 'hidden'); // in case <hr> goes outside
  7427. this.bottomRuleEl.show();
  7428. }
  7429. }
  7430. },
  7431. // Sets the scroll value of the scroller to the initial pre-configured state prior to allowing the user to change it
  7432. initializeScroll: function() {
  7433. var _this = this;
  7434. var scrollTime = moment.duration(this.opt('scrollTime'));
  7435. var top = this.timeGrid.computeTimeTop(scrollTime);
  7436. // zoom can give weird floating-point values. rather scroll a little bit further
  7437. top = Math.ceil(top);
  7438. if (top) {
  7439. top++; // to overcome top border that slots beyond the first have. looks better
  7440. }
  7441. function scroll() {
  7442. _this.scrollerEl.scrollTop(top);
  7443. }
  7444. scroll();
  7445. setTimeout(scroll, 0); // overrides any previous scroll state made by the browser
  7446. },
  7447. /* Events
  7448. ------------------------------------------------------------------------------------------------------------------*/
  7449. // Renders events onto the view and populates the View's segment array
  7450. renderEvents: function(events) {
  7451. var dayEvents = [];
  7452. var timedEvents = [];
  7453. var daySegs = [];
  7454. var timedSegs;
  7455. var i;
  7456. // separate the events into all-day and timed
  7457. for (i = 0; i < events.length; i++) {
  7458. if (events[i].allDay) {
  7459. dayEvents.push(events[i]);
  7460. }
  7461. else {
  7462. timedEvents.push(events[i]);
  7463. }
  7464. }
  7465. // render the events in the subcomponents
  7466. timedSegs = this.timeGrid.renderEvents(timedEvents);
  7467. if (this.dayGrid) {
  7468. daySegs = this.dayGrid.renderEvents(dayEvents);
  7469. }
  7470. // the all-day area is flexible and might have a lot of events, so shift the height
  7471. this.updateHeight();
  7472. },
  7473. // Retrieves all segment objects that are rendered in the view
  7474. getEventSegs: function() {
  7475. return this.timeGrid.getEventSegs().concat(
  7476. this.dayGrid ? this.dayGrid.getEventSegs() : []
  7477. );
  7478. },
  7479. // Unrenders all event elements and clears internal segment data
  7480. destroyEvents: function() {
  7481. // if destroyEvents is being called as part of an event rerender, renderEvents will be called shortly
  7482. // after, so remember what the scroll value was so we can restore it.
  7483. this.recordScroll();
  7484. // destroy the events in the subcomponents
  7485. this.timeGrid.destroyEvents();
  7486. if (this.dayGrid) {
  7487. this.dayGrid.destroyEvents();
  7488. }
  7489. // we DON'T need to call updateHeight() because:
  7490. // A) a renderEvents() call always happens after this, which will eventually call updateHeight()
  7491. // B) in IE8, this causes a flash whenever events are rerendered
  7492. },
  7493. /* Dragging (for events and external elements)
  7494. ------------------------------------------------------------------------------------------------------------------*/
  7495. // A returned value of `true` signals that a mock "helper" event has been rendered.
  7496. renderDrag: function(dropLocation, seg) {
  7497. if (dropLocation.start.hasTime()) {
  7498. return this.timeGrid.renderDrag(dropLocation, seg);
  7499. }
  7500. else if (this.dayGrid) {
  7501. return this.dayGrid.renderDrag(dropLocation, seg);
  7502. }
  7503. },
  7504. destroyDrag: function() {
  7505. this.timeGrid.destroyDrag();
  7506. if (this.dayGrid) {
  7507. this.dayGrid.destroyDrag();
  7508. }
  7509. },
  7510. /* Selection
  7511. ------------------------------------------------------------------------------------------------------------------*/
  7512. // Renders a visual indication of a selection
  7513. renderSelection: function(range) {
  7514. if (range.start.hasTime() || range.end.hasTime()) {
  7515. this.timeGrid.renderSelection(range);
  7516. }
  7517. else if (this.dayGrid) {
  7518. this.dayGrid.renderSelection(range);
  7519. }
  7520. },
  7521. // Unrenders a visual indications of a selection
  7522. destroySelection: function() {
  7523. this.timeGrid.destroySelection();
  7524. if (this.dayGrid) {
  7525. this.dayGrid.destroySelection();
  7526. }
  7527. }
  7528. });
  7529. /* A week view with an all-day cell area at the top, and a time grid below
  7530. ----------------------------------------------------------------------------------------------------------------------*/
  7531. fcViews.agendaWeek = {
  7532. type: 'agenda',
  7533. duration: { weeks: 1 }
  7534. };
  7535. /* A day view with an all-day cell area at the top, and a time grid below
  7536. ----------------------------------------------------------------------------------------------------------------------*/
  7537. fcViews.agendaDay = {
  7538. type: 'agenda',
  7539. duration: { days: 1 }
  7540. };
  7541. });