fullcalendar.js 365 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200
  1. /*!
  2. * <%= meta.title %> v<%= meta.version %>
  3. * Docs & License: <%= meta.homepage %>
  4. * (c) <%= meta.copyright %>
  5. */
  6. (function(factory) {
  7. if (typeof define === 'function' && define.amd) {
  8. define([ 'jquery', 'moment' ], factory);
  9. }
  10. else if (typeof exports === 'object') { // Node/CommonJS
  11. module.exports = factory(require('jquery'), require('moment'));
  12. }
  13. else {
  14. factory(jQuery, moment);
  15. }
  16. })(function($, moment) {
  17. ;;
  18. var FC = $.fullCalendar = {
  19. version: "<%= meta.version %>",
  20. internalApiVersion: 5
  21. };
  22. var fcViews = FC.views = {};
  23. $.fn.fullCalendar = function(options) {
  24. var args = Array.prototype.slice.call(arguments, 1); // for a possible method call
  25. var res = this; // what this function will return (this jQuery object by default)
  26. this.each(function(i, _element) { // loop each DOM element involved
  27. var element = $(_element);
  28. var calendar = element.data('fullCalendar'); // get the existing calendar object (if any)
  29. var singleRes; // the returned value of this single method call
  30. // a method call
  31. if (typeof options === 'string') {
  32. if (calendar && $.isFunction(calendar[options])) {
  33. singleRes = calendar[options].apply(calendar, args);
  34. if (!i) {
  35. res = singleRes; // record the first method call result
  36. }
  37. if (options === 'destroy') { // for the destroy method, must remove Calendar object data
  38. element.removeData('fullCalendar');
  39. }
  40. }
  41. }
  42. // a new calendar initialization
  43. else if (!calendar) { // don't initialize twice
  44. calendar = new Calendar(element, options);
  45. element.data('fullCalendar', calendar);
  46. calendar.render();
  47. }
  48. });
  49. return res;
  50. };
  51. var complexOptions = [ // names of options that are objects whose properties should be combined
  52. 'header',
  53. 'buttonText',
  54. 'buttonIcons',
  55. 'themeButtonIcons'
  56. ];
  57. // Merges an array of option objects into a single object
  58. function mergeOptions(optionObjs) {
  59. return mergeProps(optionObjs, complexOptions);
  60. }
  61. // Given options specified for the calendar's constructor, massages any legacy options into a non-legacy form.
  62. // Converts View-Option-Hashes into the View-Specific-Options format.
  63. function massageOverrides(input) {
  64. var overrides = { views: input.views || {} }; // the output. ensure a `views` hash
  65. var subObj;
  66. // iterate through all option override properties (except `views`)
  67. $.each(input, function(name, val) {
  68. if (name != 'views') {
  69. // could the value be a legacy View-Option-Hash?
  70. if (
  71. $.isPlainObject(val) &&
  72. !/(time|duration|interval)$/i.test(name) && // exclude duration options. might be given as objects
  73. $.inArray(name, complexOptions) == -1 // complex options aren't allowed to be View-Option-Hashes
  74. ) {
  75. subObj = null;
  76. // iterate through the properties of this possible View-Option-Hash value
  77. $.each(val, function(subName, subVal) {
  78. // is the property targeting a view?
  79. if (/^(month|week|day|default|basic(Week|Day)?|agenda(Week|Day)?)$/.test(subName)) {
  80. if (!overrides.views[subName]) { // ensure the view-target entry exists
  81. overrides.views[subName] = {};
  82. }
  83. overrides.views[subName][name] = subVal; // record the value in the `views` object
  84. }
  85. else { // a non-View-Option-Hash property
  86. if (!subObj) {
  87. subObj = {};
  88. }
  89. subObj[subName] = subVal; // accumulate these unrelated values for later
  90. }
  91. });
  92. if (subObj) { // non-View-Option-Hash properties? transfer them as-is
  93. overrides[name] = subObj;
  94. }
  95. }
  96. else {
  97. overrides[name] = val; // transfer normal options as-is
  98. }
  99. }
  100. });
  101. return overrides;
  102. }
  103. ;;
  104. // exports
  105. FC.intersectRanges = intersectRanges;
  106. FC.applyAll = applyAll;
  107. FC.debounce = debounce;
  108. FC.isInt = isInt;
  109. FC.htmlEscape = htmlEscape;
  110. FC.cssToStr = cssToStr;
  111. FC.proxy = proxy;
  112. FC.capitaliseFirstLetter = capitaliseFirstLetter;
  113. /* FullCalendar-specific DOM Utilities
  114. ----------------------------------------------------------------------------------------------------------------------*/
  115. // Given the scrollbar widths of some other container, create borders/margins on rowEls in order to match the left
  116. // and right space that was offset by the scrollbars. A 1-pixel border first, then margin beyond that.
  117. function compensateScroll(rowEls, scrollbarWidths) {
  118. if (scrollbarWidths.left) {
  119. rowEls.css({
  120. 'border-left-width': 1,
  121. 'margin-left': scrollbarWidths.left - 1
  122. });
  123. }
  124. if (scrollbarWidths.right) {
  125. rowEls.css({
  126. 'border-right-width': 1,
  127. 'margin-right': scrollbarWidths.right - 1
  128. });
  129. }
  130. }
  131. // Undoes compensateScroll and restores all borders/margins
  132. function uncompensateScroll(rowEls) {
  133. rowEls.css({
  134. 'margin-left': '',
  135. 'margin-right': '',
  136. 'border-left-width': '',
  137. 'border-right-width': ''
  138. });
  139. }
  140. // Make the mouse cursor express that an event is not allowed in the current area
  141. function disableCursor() {
  142. $('body').addClass('fc-not-allowed');
  143. }
  144. // Returns the mouse cursor to its original look
  145. function enableCursor() {
  146. $('body').removeClass('fc-not-allowed');
  147. }
  148. // Given a total available height to fill, have `els` (essentially child rows) expand to accomodate.
  149. // By default, all elements that are shorter than the recommended height are expanded uniformly, not considering
  150. // any other els that are already too tall. if `shouldRedistribute` is on, it considers these tall rows and
  151. // reduces the available height.
  152. function distributeHeight(els, availableHeight, shouldRedistribute) {
  153. // *FLOORING NOTE*: we floor in certain places because zoom can give inaccurate floating-point dimensions,
  154. // and it is better to be shorter than taller, to avoid creating unnecessary scrollbars.
  155. var minOffset1 = Math.floor(availableHeight / els.length); // for non-last element
  156. var minOffset2 = Math.floor(availableHeight - minOffset1 * (els.length - 1)); // for last element *FLOORING NOTE*
  157. var flexEls = []; // elements that are allowed to expand. array of DOM nodes
  158. var flexOffsets = []; // amount of vertical space it takes up
  159. var flexHeights = []; // actual css height
  160. var usedHeight = 0;
  161. undistributeHeight(els); // give all elements their natural height
  162. // find elements that are below the recommended height (expandable).
  163. // important to query for heights in a single first pass (to avoid reflow oscillation).
  164. els.each(function(i, el) {
  165. var minOffset = i === els.length - 1 ? minOffset2 : minOffset1;
  166. var naturalOffset = $(el).outerHeight(true);
  167. if (naturalOffset < minOffset) {
  168. flexEls.push(el);
  169. flexOffsets.push(naturalOffset);
  170. flexHeights.push($(el).height());
  171. }
  172. else {
  173. // this element stretches past recommended height (non-expandable). mark the space as occupied.
  174. usedHeight += naturalOffset;
  175. }
  176. });
  177. // readjust the recommended height to only consider the height available to non-maxed-out rows.
  178. if (shouldRedistribute) {
  179. availableHeight -= usedHeight;
  180. minOffset1 = Math.floor(availableHeight / flexEls.length);
  181. minOffset2 = Math.floor(availableHeight - minOffset1 * (flexEls.length - 1)); // *FLOORING NOTE*
  182. }
  183. // assign heights to all expandable elements
  184. $(flexEls).each(function(i, el) {
  185. var minOffset = i === flexEls.length - 1 ? minOffset2 : minOffset1;
  186. var naturalOffset = flexOffsets[i];
  187. var naturalHeight = flexHeights[i];
  188. var newHeight = minOffset - (naturalOffset - naturalHeight); // subtract the margin/padding
  189. if (naturalOffset < minOffset) { // we check this again because redistribution might have changed things
  190. $(el).height(newHeight);
  191. }
  192. });
  193. }
  194. // Undoes distrubuteHeight, restoring all els to their natural height
  195. function undistributeHeight(els) {
  196. els.height('');
  197. }
  198. // Given `els`, a jQuery set of <td> cells, find the cell with the largest natural width and set the widths of all the
  199. // cells to be that width.
  200. // PREREQUISITE: if you want a cell to take up width, it needs to have a single inner element w/ display:inline
  201. function matchCellWidths(els) {
  202. var maxInnerWidth = 0;
  203. els.find('> span').each(function(i, innerEl) {
  204. var innerWidth = $(innerEl).outerWidth();
  205. if (innerWidth > maxInnerWidth) {
  206. maxInnerWidth = innerWidth;
  207. }
  208. });
  209. maxInnerWidth++; // sometimes not accurate of width the text needs to stay on one line. insurance
  210. els.width(maxInnerWidth);
  211. return maxInnerWidth;
  212. }
  213. // Given one element that resides inside another,
  214. // Subtracts the height of the inner element from the outer element.
  215. function subtractInnerElHeight(outerEl, innerEl) {
  216. var both = outerEl.add(innerEl);
  217. var diff;
  218. // effin' IE8/9/10/11 sometimes returns 0 for dimensions. this weird hack was the only thing that worked
  219. both.css({
  220. position: 'relative', // cause a reflow, which will force fresh dimension recalculation
  221. left: -1 // ensure reflow in case the el was already relative. negative is less likely to cause new scroll
  222. });
  223. diff = outerEl.outerHeight() - innerEl.outerHeight(); // grab the dimensions
  224. both.css({ position: '', left: '' }); // undo hack
  225. return diff;
  226. }
  227. /* Element Geom Utilities
  228. ----------------------------------------------------------------------------------------------------------------------*/
  229. FC.getOuterRect = getOuterRect;
  230. FC.getClientRect = getClientRect;
  231. FC.getContentRect = getContentRect;
  232. FC.getScrollbarWidths = getScrollbarWidths;
  233. // borrowed from https://github.com/jquery/jquery-ui/blob/1.11.0/ui/core.js#L51
  234. function getScrollParent(el) {
  235. var position = el.css('position'),
  236. scrollParent = el.parents().filter(function() {
  237. var parent = $(this);
  238. return (/(auto|scroll)/).test(
  239. parent.css('overflow') + parent.css('overflow-y') + parent.css('overflow-x')
  240. );
  241. }).eq(0);
  242. return position === 'fixed' || !scrollParent.length ? $(el[0].ownerDocument || document) : scrollParent;
  243. }
  244. // Queries the outer bounding area of a jQuery element.
  245. // Returns a rectangle with absolute coordinates: left, right (exclusive), top, bottom (exclusive).
  246. // Origin is optional.
  247. function getOuterRect(el, origin) {
  248. var offset = el.offset();
  249. var left = offset.left - (origin ? origin.left : 0);
  250. var top = offset.top - (origin ? origin.top : 0);
  251. return {
  252. left: left,
  253. right: left + el.outerWidth(),
  254. top: top,
  255. bottom: top + el.outerHeight()
  256. };
  257. }
  258. // Queries the area within the margin/border/scrollbars of a jQuery element. Does not go within the padding.
  259. // Returns a rectangle with absolute coordinates: left, right (exclusive), top, bottom (exclusive).
  260. // Origin is optional.
  261. // NOTE: should use clientLeft/clientTop, but very unreliable cross-browser.
  262. function getClientRect(el, origin) {
  263. var offset = el.offset();
  264. var scrollbarWidths = getScrollbarWidths(el);
  265. var left = offset.left + getCssFloat(el, 'border-left-width') + scrollbarWidths.left - (origin ? origin.left : 0);
  266. var top = offset.top + getCssFloat(el, 'border-top-width') + scrollbarWidths.top - (origin ? origin.top : 0);
  267. return {
  268. left: left,
  269. right: left + el[0].clientWidth, // clientWidth includes padding but NOT scrollbars
  270. top: top,
  271. bottom: top + el[0].clientHeight // clientHeight includes padding but NOT scrollbars
  272. };
  273. }
  274. // Queries the area within the margin/border/padding of a jQuery element. Assumed not to have scrollbars.
  275. // Returns a rectangle with absolute coordinates: left, right (exclusive), top, bottom (exclusive).
  276. // Origin is optional.
  277. function getContentRect(el, origin) {
  278. var offset = el.offset(); // just outside of border, margin not included
  279. var left = offset.left + getCssFloat(el, 'border-left-width') + getCssFloat(el, 'padding-left') -
  280. (origin ? origin.left : 0);
  281. var top = offset.top + getCssFloat(el, 'border-top-width') + getCssFloat(el, 'padding-top') -
  282. (origin ? origin.top : 0);
  283. return {
  284. left: left,
  285. right: left + el.width(),
  286. top: top,
  287. bottom: top + el.height()
  288. };
  289. }
  290. // Returns the computed left/right/top/bottom scrollbar widths for the given jQuery element.
  291. // NOTE: should use clientLeft/clientTop, but very unreliable cross-browser.
  292. function getScrollbarWidths(el) {
  293. var leftRightWidth = el.innerWidth() - el[0].clientWidth; // the paddings cancel out, leaving the scrollbars
  294. var widths = {
  295. left: 0,
  296. right: 0,
  297. top: 0,
  298. bottom: el.innerHeight() - el[0].clientHeight // the paddings cancel out, leaving the bottom scrollbar
  299. };
  300. if (getIsLeftRtlScrollbars() && el.css('direction') == 'rtl') { // is the scrollbar on the left side?
  301. widths.left = leftRightWidth;
  302. }
  303. else {
  304. widths.right = leftRightWidth;
  305. }
  306. return widths;
  307. }
  308. // Logic for determining if, when the element is right-to-left, the scrollbar appears on the left side
  309. var _isLeftRtlScrollbars = null;
  310. function getIsLeftRtlScrollbars() { // responsible for caching the computation
  311. if (_isLeftRtlScrollbars === null) {
  312. _isLeftRtlScrollbars = computeIsLeftRtlScrollbars();
  313. }
  314. return _isLeftRtlScrollbars;
  315. }
  316. function computeIsLeftRtlScrollbars() { // creates an offscreen test element, then removes it
  317. var el = $('<div><div/></div>')
  318. .css({
  319. position: 'absolute',
  320. top: -1000,
  321. left: 0,
  322. border: 0,
  323. padding: 0,
  324. overflow: 'scroll',
  325. direction: 'rtl'
  326. })
  327. .appendTo('body');
  328. var innerEl = el.children();
  329. var res = innerEl.offset().left > el.offset().left; // is the inner div shifted to accommodate a left scrollbar?
  330. el.remove();
  331. return res;
  332. }
  333. // Retrieves a jQuery element's computed CSS value as a floating-point number.
  334. // If the queried value is non-numeric (ex: IE can return "medium" for border width), will just return zero.
  335. function getCssFloat(el, prop) {
  336. return parseFloat(el.css(prop)) || 0;
  337. }
  338. /* Mouse / Touch Utilities
  339. ----------------------------------------------------------------------------------------------------------------------*/
  340. FC.preventDefault = preventDefault;
  341. // Returns a boolean whether this was a left mouse click and no ctrl key (which means right click on Mac)
  342. function isPrimaryMouseButton(ev) {
  343. return ev.which == 1 && !ev.ctrlKey;
  344. }
  345. function getEvX(ev) {
  346. if (ev.pageX !== undefined) {
  347. return ev.pageX;
  348. }
  349. var touches = ev.originalEvent.touches;
  350. if (touches) {
  351. return touches[0].pageX;
  352. }
  353. }
  354. function getEvY(ev) {
  355. if (ev.pageY !== undefined) {
  356. return ev.pageY;
  357. }
  358. var touches = ev.originalEvent.touches;
  359. if (touches) {
  360. return touches[0].pageY;
  361. }
  362. }
  363. function getEvIsTouch(ev) {
  364. return /^touch/.test(ev.type);
  365. }
  366. function preventSelection(el) {
  367. el.addClass('fc-unselectable')
  368. .on('selectstart', preventDefault);
  369. }
  370. // Stops a mouse/touch event from doing it's native browser action
  371. function preventDefault(ev) {
  372. ev.preventDefault();
  373. }
  374. // attach a handler to get called when ANY scroll action happens on the page.
  375. // this was impossible to do with normal on/off because 'scroll' doesn't bubble.
  376. // http://stackoverflow.com/a/32954565/96342
  377. // returns `true` on success.
  378. function bindAnyScroll(handler) {
  379. if (window.addEventListener) {
  380. window.addEventListener('scroll', handler, true); // useCapture=true
  381. return true;
  382. }
  383. return false;
  384. }
  385. // undoes bindAnyScroll. must pass in the original function.
  386. // returns `true` on success.
  387. function unbindAnyScroll(handler) {
  388. if (window.removeEventListener) {
  389. window.removeEventListener('scroll', handler, true); // useCapture=true
  390. return true;
  391. }
  392. return false;
  393. }
  394. /* General Geometry Utils
  395. ----------------------------------------------------------------------------------------------------------------------*/
  396. FC.intersectRects = intersectRects;
  397. // Returns a new rectangle that is the intersection of the two rectangles. If they don't intersect, returns false
  398. function intersectRects(rect1, rect2) {
  399. var res = {
  400. left: Math.max(rect1.left, rect2.left),
  401. right: Math.min(rect1.right, rect2.right),
  402. top: Math.max(rect1.top, rect2.top),
  403. bottom: Math.min(rect1.bottom, rect2.bottom)
  404. };
  405. if (res.left < res.right && res.top < res.bottom) {
  406. return res;
  407. }
  408. return false;
  409. }
  410. // Returns a new point that will have been moved to reside within the given rectangle
  411. function constrainPoint(point, rect) {
  412. return {
  413. left: Math.min(Math.max(point.left, rect.left), rect.right),
  414. top: Math.min(Math.max(point.top, rect.top), rect.bottom)
  415. };
  416. }
  417. // Returns a point that is the center of the given rectangle
  418. function getRectCenter(rect) {
  419. return {
  420. left: (rect.left + rect.right) / 2,
  421. top: (rect.top + rect.bottom) / 2
  422. };
  423. }
  424. // Subtracts point2's coordinates from point1's coordinates, returning a delta
  425. function diffPoints(point1, point2) {
  426. return {
  427. left: point1.left - point2.left,
  428. top: point1.top - point2.top
  429. };
  430. }
  431. /* Object Ordering by Field
  432. ----------------------------------------------------------------------------------------------------------------------*/
  433. FC.parseFieldSpecs = parseFieldSpecs;
  434. FC.compareByFieldSpecs = compareByFieldSpecs;
  435. FC.compareByFieldSpec = compareByFieldSpec;
  436. FC.flexibleCompare = flexibleCompare;
  437. function parseFieldSpecs(input) {
  438. var specs = [];
  439. var tokens = [];
  440. var i, token;
  441. if (typeof input === 'string') {
  442. tokens = input.split(/\s*,\s*/);
  443. }
  444. else if (typeof input === 'function') {
  445. tokens = [ input ];
  446. }
  447. else if ($.isArray(input)) {
  448. tokens = input;
  449. }
  450. for (i = 0; i < tokens.length; i++) {
  451. token = tokens[i];
  452. if (typeof token === 'string') {
  453. specs.push(
  454. token.charAt(0) == '-' ?
  455. { field: token.substring(1), order: -1 } :
  456. { field: token, order: 1 }
  457. );
  458. }
  459. else if (typeof token === 'function') {
  460. specs.push({ func: token });
  461. }
  462. }
  463. return specs;
  464. }
  465. function compareByFieldSpecs(obj1, obj2, fieldSpecs) {
  466. var i;
  467. var cmp;
  468. for (i = 0; i < fieldSpecs.length; i++) {
  469. cmp = compareByFieldSpec(obj1, obj2, fieldSpecs[i]);
  470. if (cmp) {
  471. return cmp;
  472. }
  473. }
  474. return 0;
  475. }
  476. function compareByFieldSpec(obj1, obj2, fieldSpec) {
  477. if (fieldSpec.func) {
  478. return fieldSpec.func(obj1, obj2);
  479. }
  480. return flexibleCompare(obj1[fieldSpec.field], obj2[fieldSpec.field]) *
  481. (fieldSpec.order || 1);
  482. }
  483. function flexibleCompare(a, b) {
  484. if (!a && !b) {
  485. return 0;
  486. }
  487. if (b == null) {
  488. return -1;
  489. }
  490. if (a == null) {
  491. return 1;
  492. }
  493. if ($.type(a) === 'string' || $.type(b) === 'string') {
  494. return String(a).localeCompare(String(b));
  495. }
  496. return a - b;
  497. }
  498. /* FullCalendar-specific Misc Utilities
  499. ----------------------------------------------------------------------------------------------------------------------*/
  500. // Computes the intersection of the two ranges. Returns undefined if no intersection.
  501. // Expects all dates to be normalized to the same timezone beforehand.
  502. // TODO: move to date section?
  503. function intersectRanges(subjectRange, constraintRange) {
  504. var subjectStart = subjectRange.start;
  505. var subjectEnd = subjectRange.end;
  506. var constraintStart = constraintRange.start;
  507. var constraintEnd = constraintRange.end;
  508. var segStart, segEnd;
  509. var isStart, isEnd;
  510. if (subjectEnd > constraintStart && subjectStart < constraintEnd) { // in bounds at all?
  511. if (subjectStart >= constraintStart) {
  512. segStart = subjectStart.clone();
  513. isStart = true;
  514. }
  515. else {
  516. segStart = constraintStart.clone();
  517. isStart = false;
  518. }
  519. if (subjectEnd <= constraintEnd) {
  520. segEnd = subjectEnd.clone();
  521. isEnd = true;
  522. }
  523. else {
  524. segEnd = constraintEnd.clone();
  525. isEnd = false;
  526. }
  527. return {
  528. start: segStart,
  529. end: segEnd,
  530. isStart: isStart,
  531. isEnd: isEnd
  532. };
  533. }
  534. }
  535. /* Date Utilities
  536. ----------------------------------------------------------------------------------------------------------------------*/
  537. FC.computeIntervalUnit = computeIntervalUnit;
  538. FC.divideRangeByDuration = divideRangeByDuration;
  539. FC.divideDurationByDuration = divideDurationByDuration;
  540. FC.multiplyDuration = multiplyDuration;
  541. FC.durationHasTime = durationHasTime;
  542. var dayIDs = [ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ];
  543. var intervalUnits = [ 'year', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond' ];
  544. // Diffs the two moments into a Duration where full-days are recorded first, then the remaining time.
  545. // Moments will have their timezones normalized.
  546. function diffDayTime(a, b) {
  547. return moment.duration({
  548. days: a.clone().stripTime().diff(b.clone().stripTime(), 'days'),
  549. ms: a.time() - b.time() // time-of-day from day start. disregards timezone
  550. });
  551. }
  552. // Diffs the two moments via their start-of-day (regardless of timezone). Produces whole-day durations.
  553. function diffDay(a, b) {
  554. return moment.duration({
  555. days: a.clone().stripTime().diff(b.clone().stripTime(), 'days')
  556. });
  557. }
  558. // Diffs two moments, producing a duration, made of a whole-unit-increment of the given unit. Uses rounding.
  559. function diffByUnit(a, b, unit) {
  560. return moment.duration(
  561. Math.round(a.diff(b, unit, true)), // returnFloat=true
  562. unit
  563. );
  564. }
  565. // Computes the unit name of the largest whole-unit period of time.
  566. // For example, 48 hours will be "days" whereas 49 hours will be "hours".
  567. // Accepts start/end, a range object, or an original duration object.
  568. function computeIntervalUnit(start, end) {
  569. var i, unit;
  570. var val;
  571. for (i = 0; i < intervalUnits.length; i++) {
  572. unit = intervalUnits[i];
  573. val = computeRangeAs(unit, start, end);
  574. if (val >= 1 && isInt(val)) {
  575. break;
  576. }
  577. }
  578. return unit; // will be "milliseconds" if nothing else matches
  579. }
  580. // Computes the number of units (like "hours") in the given range.
  581. // Range can be a {start,end} object, separate start/end args, or a Duration.
  582. // Results are based on Moment's .as() and .diff() methods, so results can depend on internal handling
  583. // of month-diffing logic (which tends to vary from version to version).
  584. function computeRangeAs(unit, start, end) {
  585. if (end != null) { // given start, end
  586. return end.diff(start, unit, true);
  587. }
  588. else if (moment.isDuration(start)) { // given duration
  589. return start.as(unit);
  590. }
  591. else { // given { start, end } range object
  592. return start.end.diff(start.start, unit, true);
  593. }
  594. }
  595. // Intelligently divides a range (specified by a start/end params) by a duration
  596. function divideRangeByDuration(start, end, dur) {
  597. var months;
  598. if (durationHasTime(dur)) {
  599. return (end - start) / dur;
  600. }
  601. months = dur.asMonths();
  602. if (Math.abs(months) >= 1 && isInt(months)) {
  603. return end.diff(start, 'months', true) / months;
  604. }
  605. return end.diff(start, 'days', true) / dur.asDays();
  606. }
  607. // Intelligently divides one duration by another
  608. function divideDurationByDuration(dur1, dur2) {
  609. var months1, months2;
  610. if (durationHasTime(dur1) || durationHasTime(dur2)) {
  611. return dur1 / dur2;
  612. }
  613. months1 = dur1.asMonths();
  614. months2 = dur2.asMonths();
  615. if (
  616. Math.abs(months1) >= 1 && isInt(months1) &&
  617. Math.abs(months2) >= 1 && isInt(months2)
  618. ) {
  619. return months1 / months2;
  620. }
  621. return dur1.asDays() / dur2.asDays();
  622. }
  623. // Intelligently multiplies a duration by a number
  624. function multiplyDuration(dur, n) {
  625. var months;
  626. if (durationHasTime(dur)) {
  627. return moment.duration(dur * n);
  628. }
  629. months = dur.asMonths();
  630. if (Math.abs(months) >= 1 && isInt(months)) {
  631. return moment.duration({ months: months * n });
  632. }
  633. return moment.duration({ days: dur.asDays() * n });
  634. }
  635. // Returns a boolean about whether the given duration has any time parts (hours/minutes/seconds/ms)
  636. function durationHasTime(dur) {
  637. return Boolean(dur.hours() || dur.minutes() || dur.seconds() || dur.milliseconds());
  638. }
  639. function isNativeDate(input) {
  640. return Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date;
  641. }
  642. // Returns a boolean about whether the given input is a time string, like "06:40:00" or "06:00"
  643. function isTimeString(str) {
  644. return /^\d+\:\d+(?:\:\d+\.?(?:\d{3})?)?$/.test(str);
  645. }
  646. /* Logging and Debug
  647. ----------------------------------------------------------------------------------------------------------------------*/
  648. FC.log = function() {
  649. var console = window.console;
  650. if (console && console.log) {
  651. return console.log.apply(console, arguments);
  652. }
  653. };
  654. FC.warn = function() {
  655. var console = window.console;
  656. if (console && console.warn) {
  657. return console.warn.apply(console, arguments);
  658. }
  659. else {
  660. return FC.log.apply(FC, arguments);
  661. }
  662. };
  663. /* General Utilities
  664. ----------------------------------------------------------------------------------------------------------------------*/
  665. var hasOwnPropMethod = {}.hasOwnProperty;
  666. // Merges an array of objects into a single object.
  667. // The second argument allows for an array of property names who's object values will be merged together.
  668. function mergeProps(propObjs, complexProps) {
  669. var dest = {};
  670. var i, name;
  671. var complexObjs;
  672. var j, val;
  673. var props;
  674. if (complexProps) {
  675. for (i = 0; i < complexProps.length; i++) {
  676. name = complexProps[i];
  677. complexObjs = [];
  678. // collect the trailing object values, stopping when a non-object is discovered
  679. for (j = propObjs.length - 1; j >= 0; j--) {
  680. val = propObjs[j][name];
  681. if (typeof val === 'object') {
  682. complexObjs.unshift(val);
  683. }
  684. else if (val !== undefined) {
  685. dest[name] = val; // if there were no objects, this value will be used
  686. break;
  687. }
  688. }
  689. // if the trailing values were objects, use the merged value
  690. if (complexObjs.length) {
  691. dest[name] = mergeProps(complexObjs);
  692. }
  693. }
  694. }
  695. // copy values into the destination, going from last to first
  696. for (i = propObjs.length - 1; i >= 0; i--) {
  697. props = propObjs[i];
  698. for (name in props) {
  699. if (!(name in dest)) { // if already assigned by previous props or complex props, don't reassign
  700. dest[name] = props[name];
  701. }
  702. }
  703. }
  704. return dest;
  705. }
  706. // Create an object that has the given prototype. Just like Object.create
  707. function createObject(proto) {
  708. var f = function() {};
  709. f.prototype = proto;
  710. return new f();
  711. }
  712. function copyOwnProps(src, dest) {
  713. for (var name in src) {
  714. if (hasOwnProp(src, name)) {
  715. dest[name] = src[name];
  716. }
  717. }
  718. }
  719. // Copies over certain methods with the same names as Object.prototype methods. Overcomes an IE<=8 bug:
  720. // https://developer.mozilla.org/en-US/docs/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug
  721. function copyNativeMethods(src, dest) {
  722. var names = [ 'constructor', 'toString', 'valueOf' ];
  723. var i, name;
  724. for (i = 0; i < names.length; i++) {
  725. name = names[i];
  726. if (src[name] !== Object.prototype[name]) {
  727. dest[name] = src[name];
  728. }
  729. }
  730. }
  731. function hasOwnProp(obj, name) {
  732. return hasOwnPropMethod.call(obj, name);
  733. }
  734. // Is the given value a non-object non-function value?
  735. function isAtomic(val) {
  736. return /undefined|null|boolean|number|string/.test($.type(val));
  737. }
  738. function applyAll(functions, thisObj, args) {
  739. if ($.isFunction(functions)) {
  740. functions = [ functions ];
  741. }
  742. if (functions) {
  743. var i;
  744. var ret;
  745. for (i=0; i<functions.length; i++) {
  746. ret = functions[i].apply(thisObj, args) || ret;
  747. }
  748. return ret;
  749. }
  750. }
  751. function firstDefined() {
  752. for (var i=0; i<arguments.length; i++) {
  753. if (arguments[i] !== undefined) {
  754. return arguments[i];
  755. }
  756. }
  757. }
  758. function htmlEscape(s) {
  759. return (s + '').replace(/&/g, '&amp;')
  760. .replace(/</g, '&lt;')
  761. .replace(/>/g, '&gt;')
  762. .replace(/'/g, '&#039;')
  763. .replace(/"/g, '&quot;')
  764. .replace(/\n/g, '<br />');
  765. }
  766. function stripHtmlEntities(text) {
  767. return text.replace(/&.*?;/g, '');
  768. }
  769. // Given a hash of CSS properties, returns a string of CSS.
  770. // Uses property names as-is (no camel-case conversion). Will not make statements for null/undefined values.
  771. function cssToStr(cssProps) {
  772. var statements = [];
  773. $.each(cssProps, function(name, val) {
  774. if (val != null) {
  775. statements.push(name + ':' + val);
  776. }
  777. });
  778. return statements.join(';');
  779. }
  780. function capitaliseFirstLetter(str) {
  781. return str.charAt(0).toUpperCase() + str.slice(1);
  782. }
  783. function compareNumbers(a, b) { // for .sort()
  784. return a - b;
  785. }
  786. function isInt(n) {
  787. return n % 1 === 0;
  788. }
  789. // Returns a method bound to the given object context.
  790. // Just like one of the jQuery.proxy signatures, but without the undesired behavior of treating the same method with
  791. // different contexts as identical when binding/unbinding events.
  792. function proxy(obj, methodName) {
  793. var method = obj[methodName];
  794. return function() {
  795. return method.apply(obj, arguments);
  796. };
  797. }
  798. // Returns a function, that, as long as it continues to be invoked, will not
  799. // be triggered. The function will be called after it stops being called for
  800. // N milliseconds. If `immediate` is passed, trigger the function on the
  801. // leading edge, instead of the trailing.
  802. // https://github.com/jashkenas/underscore/blob/1.6.0/underscore.js#L714
  803. function debounce(func, wait, immediate) {
  804. var timeout, args, context, timestamp, result;
  805. var later = function() {
  806. var last = +new Date() - timestamp;
  807. if (last < wait) {
  808. timeout = setTimeout(later, wait - last);
  809. }
  810. else {
  811. timeout = null;
  812. if (!immediate) {
  813. result = func.apply(context, args);
  814. context = args = null;
  815. }
  816. }
  817. };
  818. return function() {
  819. context = this;
  820. args = arguments;
  821. timestamp = +new Date();
  822. var callNow = immediate && !timeout;
  823. if (!timeout) {
  824. timeout = setTimeout(later, wait);
  825. }
  826. if (callNow) {
  827. result = func.apply(context, args);
  828. context = args = null;
  829. }
  830. return result;
  831. };
  832. }
  833. // HACK around jQuery's now A+ promises: execute callback synchronously if already resolved.
  834. // thenFunc shouldn't accept args.
  835. // similar to whenResources in Scheduler plugin.
  836. function syncThen(promise, thenFunc) {
  837. // not a promise, or an already-resolved promise?
  838. if (!promise || !promise.then || promise.state() === 'resolved') {
  839. return $.when(thenFunc()); // resolve immediately
  840. }
  841. else if (thenFunc) {
  842. return promise.then(thenFunc);
  843. }
  844. }
  845. ;;
  846. var ambigDateOfMonthRegex = /^\s*\d{4}-\d\d$/;
  847. var ambigTimeOrZoneRegex =
  848. /^\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+)?)?)?)?)?$/;
  849. var newMomentProto = moment.fn; // where we will attach our new methods
  850. var oldMomentProto = $.extend({}, newMomentProto); // copy of original moment methods
  851. var allowValueOptimization;
  852. var setUTCValues; // function defined below
  853. var setLocalValues; // function defined below
  854. // Creating
  855. // -------------------------------------------------------------------------------------------------
  856. // Creates a new moment, similar to the vanilla moment(...) constructor, but with
  857. // extra features (ambiguous time, enhanced formatting). When given an existing moment,
  858. // it will function as a clone (and retain the zone of the moment). Anything else will
  859. // result in a moment in the local zone.
  860. FC.moment = function() {
  861. return makeMoment(arguments);
  862. };
  863. // Sames as FC.moment, but forces the resulting moment to be in the UTC timezone.
  864. FC.moment.utc = function() {
  865. var mom = makeMoment(arguments, true);
  866. // Force it into UTC because makeMoment doesn't guarantee it
  867. // (if given a pre-existing moment for example)
  868. if (mom.hasTime()) { // don't give ambiguously-timed moments a UTC zone
  869. mom.utc();
  870. }
  871. return mom;
  872. };
  873. // Same as FC.moment, but when given an ISO8601 string, the timezone offset is preserved.
  874. // ISO8601 strings with no timezone offset will become ambiguously zoned.
  875. FC.moment.parseZone = function() {
  876. return makeMoment(arguments, true, true);
  877. };
  878. // Builds an enhanced moment from args. When given an existing moment, it clones. When given a
  879. // native Date, or called with no arguments (the current time), the resulting moment will be local.
  880. // Anything else needs to be "parsed" (a string or an array), and will be affected by:
  881. // parseAsUTC - if there is no zone information, should we parse the input in UTC?
  882. // parseZone - if there is zone information, should we force the zone of the moment?
  883. function makeMoment(args, parseAsUTC, parseZone) {
  884. var input = args[0];
  885. var isSingleString = args.length == 1 && typeof input === 'string';
  886. var isAmbigTime;
  887. var isAmbigZone;
  888. var ambigMatch;
  889. var mom;
  890. if (moment.isMoment(input)) {
  891. mom = moment.apply(null, args); // clone it
  892. transferAmbigs(input, mom); // the ambig flags weren't transfered with the clone
  893. }
  894. else if (isNativeDate(input) || input === undefined) {
  895. mom = moment.apply(null, args); // will be local
  896. }
  897. else { // "parsing" is required
  898. isAmbigTime = false;
  899. isAmbigZone = false;
  900. if (isSingleString) {
  901. if (ambigDateOfMonthRegex.test(input)) {
  902. // accept strings like '2014-05', but convert to the first of the month
  903. input += '-01';
  904. args = [ input ]; // for when we pass it on to moment's constructor
  905. isAmbigTime = true;
  906. isAmbigZone = true;
  907. }
  908. else if ((ambigMatch = ambigTimeOrZoneRegex.exec(input))) {
  909. isAmbigTime = !ambigMatch[5]; // no time part?
  910. isAmbigZone = true;
  911. }
  912. }
  913. else if ($.isArray(input)) {
  914. // arrays have no timezone information, so assume ambiguous zone
  915. isAmbigZone = true;
  916. }
  917. // otherwise, probably a string with a format
  918. if (parseAsUTC || isAmbigTime) {
  919. mom = moment.utc.apply(moment, args);
  920. }
  921. else {
  922. mom = moment.apply(null, args);
  923. }
  924. if (isAmbigTime) {
  925. mom._ambigTime = true;
  926. mom._ambigZone = true; // ambiguous time always means ambiguous zone
  927. }
  928. else if (parseZone) { // let's record the inputted zone somehow
  929. if (isAmbigZone) {
  930. mom._ambigZone = true;
  931. }
  932. else if (isSingleString) {
  933. if (mom.utcOffset) {
  934. mom.utcOffset(input); // if not a valid zone, will assign UTC
  935. }
  936. else {
  937. mom.zone(input); // for moment-pre-2.9
  938. }
  939. }
  940. }
  941. }
  942. mom._fullCalendar = true; // flag for extended functionality
  943. return mom;
  944. }
  945. // A clone method that works with the flags related to our enhanced functionality.
  946. // In the future, use moment.momentProperties
  947. newMomentProto.clone = function() {
  948. var mom = oldMomentProto.clone.apply(this, arguments);
  949. // these flags weren't transfered with the clone
  950. transferAmbigs(this, mom);
  951. if (this._fullCalendar) {
  952. mom._fullCalendar = true;
  953. }
  954. return mom;
  955. };
  956. // Week Number
  957. // -------------------------------------------------------------------------------------------------
  958. // Returns the week number, considering the locale's custom week number calcuation
  959. // `weeks` is an alias for `week`
  960. newMomentProto.week = newMomentProto.weeks = function(input) {
  961. var weekCalc = (this._locale || this._lang) // works pre-moment-2.8
  962. ._fullCalendar_weekCalc;
  963. if (input == null && typeof weekCalc === 'function') { // custom function only works for getter
  964. return weekCalc(this);
  965. }
  966. else if (weekCalc === 'ISO') {
  967. return oldMomentProto.isoWeek.apply(this, arguments); // ISO getter/setter
  968. }
  969. return oldMomentProto.week.apply(this, arguments); // local getter/setter
  970. };
  971. // Time-of-day
  972. // -------------------------------------------------------------------------------------------------
  973. // GETTER
  974. // Returns a Duration with the hours/minutes/seconds/ms values of the moment.
  975. // If the moment has an ambiguous time, a duration of 00:00 will be returned.
  976. //
  977. // SETTER
  978. // You can supply a Duration, a Moment, or a Duration-like argument.
  979. // When setting the time, and the moment has an ambiguous time, it then becomes unambiguous.
  980. newMomentProto.time = function(time) {
  981. // Fallback to the original method (if there is one) if this moment wasn't created via FullCalendar.
  982. // `time` is a generic enough method name where this precaution is necessary to avoid collisions w/ other plugins.
  983. if (!this._fullCalendar) {
  984. return oldMomentProto.time.apply(this, arguments);
  985. }
  986. if (time == null) { // getter
  987. return moment.duration({
  988. hours: this.hours(),
  989. minutes: this.minutes(),
  990. seconds: this.seconds(),
  991. milliseconds: this.milliseconds()
  992. });
  993. }
  994. else { // setter
  995. this._ambigTime = false; // mark that the moment now has a time
  996. if (!moment.isDuration(time) && !moment.isMoment(time)) {
  997. time = moment.duration(time);
  998. }
  999. // The day value should cause overflow (so 24 hours becomes 00:00:00 of next day).
  1000. // Only for Duration times, not Moment times.
  1001. var dayHours = 0;
  1002. if (moment.isDuration(time)) {
  1003. dayHours = Math.floor(time.asDays()) * 24;
  1004. }
  1005. // We need to set the individual fields.
  1006. // Can't use startOf('day') then add duration. In case of DST at start of day.
  1007. return this.hours(dayHours + time.hours())
  1008. .minutes(time.minutes())
  1009. .seconds(time.seconds())
  1010. .milliseconds(time.milliseconds());
  1011. }
  1012. };
  1013. // Converts the moment to UTC, stripping out its time-of-day and timezone offset,
  1014. // but preserving its YMD. A moment with a stripped time will display no time
  1015. // nor timezone offset when .format() is called.
  1016. newMomentProto.stripTime = function() {
  1017. var a;
  1018. if (!this._ambigTime) {
  1019. // get the values before any conversion happens
  1020. a = this.toArray(); // array of y/m/d/h/m/s/ms
  1021. // TODO: use keepLocalTime in the future
  1022. this.utc(); // set the internal UTC flag (will clear the ambig flags)
  1023. setUTCValues(this, a.slice(0, 3)); // set the year/month/date. time will be zero
  1024. // Mark the time as ambiguous. This needs to happen after the .utc() call, which might call .utcOffset(),
  1025. // which clears all ambig flags. Same with setUTCValues with moment-timezone.
  1026. this._ambigTime = true;
  1027. this._ambigZone = true; // if ambiguous time, also ambiguous timezone offset
  1028. }
  1029. return this; // for chaining
  1030. };
  1031. // Returns if the moment has a non-ambiguous time (boolean)
  1032. newMomentProto.hasTime = function() {
  1033. return !this._ambigTime;
  1034. };
  1035. // Timezone
  1036. // -------------------------------------------------------------------------------------------------
  1037. // Converts the moment to UTC, stripping out its timezone offset, but preserving its
  1038. // YMD and time-of-day. A moment with a stripped timezone offset will display no
  1039. // timezone offset when .format() is called.
  1040. // TODO: look into Moment's keepLocalTime functionality
  1041. newMomentProto.stripZone = function() {
  1042. var a, wasAmbigTime;
  1043. if (!this._ambigZone) {
  1044. // get the values before any conversion happens
  1045. a = this.toArray(); // array of y/m/d/h/m/s/ms
  1046. wasAmbigTime = this._ambigTime;
  1047. this.utc(); // set the internal UTC flag (might clear the ambig flags, depending on Moment internals)
  1048. setUTCValues(this, a); // will set the year/month/date/hours/minutes/seconds/ms
  1049. // the above call to .utc()/.utcOffset() unfortunately might clear the ambig flags, so restore
  1050. this._ambigTime = wasAmbigTime || false;
  1051. // Mark the zone as ambiguous. This needs to happen after the .utc() call, which might call .utcOffset(),
  1052. // which clears the ambig flags. Same with setUTCValues with moment-timezone.
  1053. this._ambigZone = true;
  1054. }
  1055. return this; // for chaining
  1056. };
  1057. // Returns of the moment has a non-ambiguous timezone offset (boolean)
  1058. newMomentProto.hasZone = function() {
  1059. return !this._ambigZone;
  1060. };
  1061. // this method implicitly marks a zone
  1062. newMomentProto.local = function() {
  1063. var a = this.toArray(); // year,month,date,hours,minutes,seconds,ms as an array
  1064. var wasAmbigZone = this._ambigZone;
  1065. oldMomentProto.local.apply(this, arguments);
  1066. // ensure non-ambiguous
  1067. // this probably already happened via local() -> utcOffset(), but don't rely on Moment's internals
  1068. this._ambigTime = false;
  1069. this._ambigZone = false;
  1070. if (wasAmbigZone) {
  1071. // If the moment was ambiguously zoned, the date fields were stored as UTC.
  1072. // We want to preserve these, but in local time.
  1073. // TODO: look into Moment's keepLocalTime functionality
  1074. setLocalValues(this, a);
  1075. }
  1076. return this; // for chaining
  1077. };
  1078. // implicitly marks a zone
  1079. newMomentProto.utc = function() {
  1080. oldMomentProto.utc.apply(this, arguments);
  1081. // ensure non-ambiguous
  1082. // this probably already happened via utc() -> utcOffset(), but don't rely on Moment's internals
  1083. this._ambigTime = false;
  1084. this._ambigZone = false;
  1085. return this;
  1086. };
  1087. // methods for arbitrarily manipulating timezone offset.
  1088. // should clear time/zone ambiguity when called.
  1089. $.each([
  1090. 'zone', // only in moment-pre-2.9. deprecated afterwards
  1091. 'utcOffset'
  1092. ], function(i, name) {
  1093. if (oldMomentProto[name]) { // original method exists?
  1094. // this method implicitly marks a zone (will probably get called upon .utc() and .local())
  1095. newMomentProto[name] = function(tzo) {
  1096. if (tzo != null) { // setter
  1097. // these assignments needs to happen before the original zone method is called.
  1098. // I forget why, something to do with a browser crash.
  1099. this._ambigTime = false;
  1100. this._ambigZone = false;
  1101. }
  1102. return oldMomentProto[name].apply(this, arguments);
  1103. };
  1104. }
  1105. });
  1106. // Formatting
  1107. // -------------------------------------------------------------------------------------------------
  1108. newMomentProto.format = function() {
  1109. if (this._fullCalendar && arguments[0]) { // an enhanced moment? and a format string provided?
  1110. return formatDate(this, arguments[0]); // our extended formatting
  1111. }
  1112. if (this._ambigTime) {
  1113. return oldMomentFormat(this, 'YYYY-MM-DD');
  1114. }
  1115. if (this._ambigZone) {
  1116. return oldMomentFormat(this, 'YYYY-MM-DD[T]HH:mm:ss');
  1117. }
  1118. return oldMomentProto.format.apply(this, arguments);
  1119. };
  1120. newMomentProto.toISOString = function() {
  1121. if (this._ambigTime) {
  1122. return oldMomentFormat(this, 'YYYY-MM-DD');
  1123. }
  1124. if (this._ambigZone) {
  1125. return oldMomentFormat(this, 'YYYY-MM-DD[T]HH:mm:ss');
  1126. }
  1127. return oldMomentProto.toISOString.apply(this, arguments);
  1128. };
  1129. // Querying
  1130. // -------------------------------------------------------------------------------------------------
  1131. // Is the moment within the specified range? `end` is exclusive.
  1132. // FYI, this method is not a standard Moment method, so always do our enhanced logic.
  1133. newMomentProto.isWithin = function(start, end) {
  1134. var a = commonlyAmbiguate([ this, start, end ]);
  1135. return a[0] >= a[1] && a[0] < a[2];
  1136. };
  1137. // When isSame is called with units, timezone ambiguity is normalized before the comparison happens.
  1138. // If no units specified, the two moments must be identically the same, with matching ambig flags.
  1139. newMomentProto.isSame = function(input, units) {
  1140. var a;
  1141. // only do custom logic if this is an enhanced moment
  1142. if (!this._fullCalendar) {
  1143. return oldMomentProto.isSame.apply(this, arguments);
  1144. }
  1145. if (units) {
  1146. a = commonlyAmbiguate([ this, input ], true); // normalize timezones but don't erase times
  1147. return oldMomentProto.isSame.call(a[0], a[1], units);
  1148. }
  1149. else {
  1150. input = FC.moment.parseZone(input); // normalize input
  1151. return oldMomentProto.isSame.call(this, input) &&
  1152. Boolean(this._ambigTime) === Boolean(input._ambigTime) &&
  1153. Boolean(this._ambigZone) === Boolean(input._ambigZone);
  1154. }
  1155. };
  1156. // Make these query methods work with ambiguous moments
  1157. $.each([
  1158. 'isBefore',
  1159. 'isAfter'
  1160. ], function(i, methodName) {
  1161. newMomentProto[methodName] = function(input, units) {
  1162. var a;
  1163. // only do custom logic if this is an enhanced moment
  1164. if (!this._fullCalendar) {
  1165. return oldMomentProto[methodName].apply(this, arguments);
  1166. }
  1167. a = commonlyAmbiguate([ this, input ]);
  1168. return oldMomentProto[methodName].call(a[0], a[1], units);
  1169. };
  1170. });
  1171. // Misc Internals
  1172. // -------------------------------------------------------------------------------------------------
  1173. // given an array of moment-like inputs, return a parallel array w/ moments similarly ambiguated.
  1174. // for example, of one moment has ambig time, but not others, all moments will have their time stripped.
  1175. // set `preserveTime` to `true` to keep times, but only normalize zone ambiguity.
  1176. // returns the original moments if no modifications are necessary.
  1177. function commonlyAmbiguate(inputs, preserveTime) {
  1178. var anyAmbigTime = false;
  1179. var anyAmbigZone = false;
  1180. var len = inputs.length;
  1181. var moms = [];
  1182. var i, mom;
  1183. // parse inputs into real moments and query their ambig flags
  1184. for (i = 0; i < len; i++) {
  1185. mom = inputs[i];
  1186. if (!moment.isMoment(mom)) {
  1187. mom = FC.moment.parseZone(mom);
  1188. }
  1189. anyAmbigTime = anyAmbigTime || mom._ambigTime;
  1190. anyAmbigZone = anyAmbigZone || mom._ambigZone;
  1191. moms.push(mom);
  1192. }
  1193. // strip each moment down to lowest common ambiguity
  1194. // use clones to avoid modifying the original moments
  1195. for (i = 0; i < len; i++) {
  1196. mom = moms[i];
  1197. if (!preserveTime && anyAmbigTime && !mom._ambigTime) {
  1198. moms[i] = mom.clone().stripTime();
  1199. }
  1200. else if (anyAmbigZone && !mom._ambigZone) {
  1201. moms[i] = mom.clone().stripZone();
  1202. }
  1203. }
  1204. return moms;
  1205. }
  1206. // Transfers all the flags related to ambiguous time/zone from the `src` moment to the `dest` moment
  1207. // TODO: look into moment.momentProperties for this.
  1208. function transferAmbigs(src, dest) {
  1209. if (src._ambigTime) {
  1210. dest._ambigTime = true;
  1211. }
  1212. else if (dest._ambigTime) {
  1213. dest._ambigTime = false;
  1214. }
  1215. if (src._ambigZone) {
  1216. dest._ambigZone = true;
  1217. }
  1218. else if (dest._ambigZone) {
  1219. dest._ambigZone = false;
  1220. }
  1221. }
  1222. // Sets the year/month/date/etc values of the moment from the given array.
  1223. // Inefficient because it calls each individual setter.
  1224. function setMomentValues(mom, a) {
  1225. mom.year(a[0] || 0)
  1226. .month(a[1] || 0)
  1227. .date(a[2] || 0)
  1228. .hours(a[3] || 0)
  1229. .minutes(a[4] || 0)
  1230. .seconds(a[5] || 0)
  1231. .milliseconds(a[6] || 0);
  1232. }
  1233. // Can we set the moment's internal date directly?
  1234. allowValueOptimization = '_d' in moment() && 'updateOffset' in moment;
  1235. // Utility function. Accepts a moment and an array of the UTC year/month/date/etc values to set.
  1236. // Assumes the given moment is already in UTC mode.
  1237. setUTCValues = allowValueOptimization ? function(mom, a) {
  1238. // simlate what moment's accessors do
  1239. mom._d.setTime(Date.UTC.apply(Date, a));
  1240. moment.updateOffset(mom, false); // keepTime=false
  1241. } : setMomentValues;
  1242. // Utility function. Accepts a moment and an array of the local year/month/date/etc values to set.
  1243. // Assumes the given moment is already in local mode.
  1244. setLocalValues = allowValueOptimization ? function(mom, a) {
  1245. // simlate what moment's accessors do
  1246. mom._d.setTime(+new Date( // FYI, there is now way to apply an array of args to a constructor
  1247. a[0] || 0,
  1248. a[1] || 0,
  1249. a[2] || 0,
  1250. a[3] || 0,
  1251. a[4] || 0,
  1252. a[5] || 0,
  1253. a[6] || 0
  1254. ));
  1255. moment.updateOffset(mom, false); // keepTime=false
  1256. } : setMomentValues;
  1257. ;;
  1258. // Single Date Formatting
  1259. // -------------------------------------------------------------------------------------------------
  1260. // call this if you want Moment's original format method to be used
  1261. function oldMomentFormat(mom, formatStr) {
  1262. return oldMomentProto.format.call(mom, formatStr); // oldMomentProto defined in moment-ext.js
  1263. }
  1264. // Formats `date` with a Moment formatting string, but allow our non-zero areas and
  1265. // additional token.
  1266. function formatDate(date, formatStr) {
  1267. return formatDateWithChunks(date, getFormatStringChunks(formatStr));
  1268. }
  1269. function formatDateWithChunks(date, chunks) {
  1270. var s = '';
  1271. var i;
  1272. for (i=0; i<chunks.length; i++) {
  1273. s += formatDateWithChunk(date, chunks[i]);
  1274. }
  1275. return s;
  1276. }
  1277. // addition formatting tokens we want recognized
  1278. var tokenOverrides = {
  1279. t: function(date) { // "a" or "p"
  1280. return oldMomentFormat(date, 'a').charAt(0);
  1281. },
  1282. T: function(date) { // "A" or "P"
  1283. return oldMomentFormat(date, 'A').charAt(0);
  1284. }
  1285. };
  1286. function formatDateWithChunk(date, chunk) {
  1287. var token;
  1288. var maybeStr;
  1289. if (typeof chunk === 'string') { // a literal string
  1290. return chunk;
  1291. }
  1292. else if ((token = chunk.token)) { // a token, like "YYYY"
  1293. if (tokenOverrides[token]) {
  1294. return tokenOverrides[token](date); // use our custom token
  1295. }
  1296. return oldMomentFormat(date, token);
  1297. }
  1298. else if (chunk.maybe) { // a grouping of other chunks that must be non-zero
  1299. maybeStr = formatDateWithChunks(date, chunk.maybe);
  1300. if (maybeStr.match(/[1-9]/)) {
  1301. return maybeStr;
  1302. }
  1303. }
  1304. return '';
  1305. }
  1306. // Date Range Formatting
  1307. // -------------------------------------------------------------------------------------------------
  1308. // TODO: make it work with timezone offset
  1309. // Using a formatting string meant for a single date, generate a range string, like
  1310. // "Sep 2 - 9 2013", that intelligently inserts a separator where the dates differ.
  1311. // If the dates are the same as far as the format string is concerned, just return a single
  1312. // rendering of one date, without any separator.
  1313. function formatRange(date1, date2, formatStr, separator, isRTL) {
  1314. var localeData;
  1315. date1 = FC.moment.parseZone(date1);
  1316. date2 = FC.moment.parseZone(date2);
  1317. localeData = (date1.localeData || date1.lang).call(date1); // works with moment-pre-2.8
  1318. // Expand localized format strings, like "LL" -> "MMMM D YYYY"
  1319. formatStr = localeData.longDateFormat(formatStr) || formatStr;
  1320. // BTW, this is not important for `formatDate` because it is impossible to put custom tokens
  1321. // or non-zero areas in Moment's localized format strings.
  1322. separator = separator || ' - ';
  1323. return formatRangeWithChunks(
  1324. date1,
  1325. date2,
  1326. getFormatStringChunks(formatStr),
  1327. separator,
  1328. isRTL
  1329. );
  1330. }
  1331. FC.formatRange = formatRange; // expose
  1332. function formatRangeWithChunks(date1, date2, chunks, separator, isRTL) {
  1333. var unzonedDate1 = date1.clone().stripZone(); // for formatSimilarChunk
  1334. var unzonedDate2 = date2.clone().stripZone(); // "
  1335. var chunkStr; // the rendering of the chunk
  1336. var leftI;
  1337. var leftStr = '';
  1338. var rightI;
  1339. var rightStr = '';
  1340. var middleI;
  1341. var middleStr1 = '';
  1342. var middleStr2 = '';
  1343. var middleStr = '';
  1344. // Start at the leftmost side of the formatting string and continue until you hit a token
  1345. // that is not the same between dates.
  1346. for (leftI=0; leftI<chunks.length; leftI++) {
  1347. chunkStr = formatSimilarChunk(date1, date2, unzonedDate1, unzonedDate2, chunks[leftI]);
  1348. if (chunkStr === false) {
  1349. break;
  1350. }
  1351. leftStr += chunkStr;
  1352. }
  1353. // Similarly, start at the rightmost side of the formatting string and move left
  1354. for (rightI=chunks.length-1; rightI>leftI; rightI--) {
  1355. chunkStr = formatSimilarChunk(date1, date2, unzonedDate1, unzonedDate2, chunks[rightI]);
  1356. if (chunkStr === false) {
  1357. break;
  1358. }
  1359. rightStr = chunkStr + rightStr;
  1360. }
  1361. // The area in the middle is different for both of the dates.
  1362. // Collect them distinctly so we can jam them together later.
  1363. for (middleI=leftI; middleI<=rightI; middleI++) {
  1364. middleStr1 += formatDateWithChunk(date1, chunks[middleI]);
  1365. middleStr2 += formatDateWithChunk(date2, chunks[middleI]);
  1366. }
  1367. if (middleStr1 || middleStr2) {
  1368. if (isRTL) {
  1369. middleStr = middleStr2 + separator + middleStr1;
  1370. }
  1371. else {
  1372. middleStr = middleStr1 + separator + middleStr2;
  1373. }
  1374. }
  1375. return leftStr + middleStr + rightStr;
  1376. }
  1377. var similarUnitMap = {
  1378. Y: 'year',
  1379. M: 'month',
  1380. D: 'day', // day of month
  1381. d: 'day', // day of week
  1382. // prevents a separator between anything time-related...
  1383. A: 'second', // AM/PM
  1384. a: 'second', // am/pm
  1385. T: 'second', // A/P
  1386. t: 'second', // a/p
  1387. H: 'second', // hour (24)
  1388. h: 'second', // hour (12)
  1389. m: 'second', // minute
  1390. s: 'second' // second
  1391. };
  1392. // TODO: week maybe?
  1393. // Given a formatting chunk, and given that both dates are similar in the regard the
  1394. // formatting chunk is concerned, format date1 against `chunk`. Otherwise, return `false`.
  1395. function formatSimilarChunk(date1, date2, unzonedDate1, unzonedDate2, chunk) {
  1396. var token;
  1397. var unit;
  1398. if (typeof chunk === 'string') { // a literal string
  1399. return chunk;
  1400. }
  1401. else if ((token = chunk.token)) {
  1402. unit = similarUnitMap[token.charAt(0)];
  1403. // are the dates the same for this unit of measurement?
  1404. // use the unzoned dates for this calculation because unreliable when near DST (bug #2396)
  1405. if (unit && unzonedDate1.isSame(unzonedDate2, unit)) {
  1406. return oldMomentFormat(date1, token); // would be the same if we used `date2`
  1407. // BTW, don't support custom tokens
  1408. }
  1409. }
  1410. return false; // the chunk is NOT the same for the two dates
  1411. // BTW, don't support splitting on non-zero areas
  1412. }
  1413. // Chunking Utils
  1414. // -------------------------------------------------------------------------------------------------
  1415. var formatStringChunkCache = {};
  1416. function getFormatStringChunks(formatStr) {
  1417. if (formatStr in formatStringChunkCache) {
  1418. return formatStringChunkCache[formatStr];
  1419. }
  1420. return (formatStringChunkCache[formatStr] = chunkFormatString(formatStr));
  1421. }
  1422. // Break the formatting string into an array of chunks
  1423. function chunkFormatString(formatStr) {
  1424. var chunks = [];
  1425. var chunker = /\[([^\]]*)\]|\(([^\)]*)\)|(LTS|LT|(\w)\4*o?)|([^\w\[\(]+)/g; // TODO: more descrimination
  1426. var match;
  1427. while ((match = chunker.exec(formatStr))) {
  1428. if (match[1]) { // a literal string inside [ ... ]
  1429. chunks.push(match[1]);
  1430. }
  1431. else if (match[2]) { // non-zero formatting inside ( ... )
  1432. chunks.push({ maybe: chunkFormatString(match[2]) });
  1433. }
  1434. else if (match[3]) { // a formatting token
  1435. chunks.push({ token: match[3] });
  1436. }
  1437. else if (match[5]) { // an unenclosed literal string
  1438. chunks.push(match[5]);
  1439. }
  1440. }
  1441. return chunks;
  1442. }
  1443. ;;
  1444. FC.Class = Class; // export
  1445. // Class that all other classes will inherit from
  1446. function Class() { }
  1447. // Called on a class to create a subclass.
  1448. // Last argument contains instance methods. Any argument before the last are considered mixins.
  1449. Class.extend = function() {
  1450. var len = arguments.length;
  1451. var i;
  1452. var members;
  1453. for (i = 0; i < len; i++) {
  1454. members = arguments[i];
  1455. if (i < len - 1) { // not the last argument?
  1456. mixIntoClass(this, members);
  1457. }
  1458. }
  1459. return extendClass(this, members || {}); // members will be undefined if no arguments
  1460. };
  1461. // Adds new member variables/methods to the class's prototype.
  1462. // Can be called with another class, or a plain object hash containing new members.
  1463. Class.mixin = function(members) {
  1464. mixIntoClass(this, members);
  1465. };
  1466. function extendClass(superClass, members) {
  1467. var subClass;
  1468. // ensure a constructor for the subclass, forwarding all arguments to the super-constructor if it doesn't exist
  1469. if (hasOwnProp(members, 'constructor')) {
  1470. subClass = members.constructor;
  1471. }
  1472. if (typeof subClass !== 'function') {
  1473. subClass = members.constructor = function() {
  1474. superClass.apply(this, arguments);
  1475. };
  1476. }
  1477. // build the base prototype for the subclass, which is an new object chained to the superclass's prototype
  1478. subClass.prototype = createObject(superClass.prototype);
  1479. // copy each member variable/method onto the the subclass's prototype
  1480. copyOwnProps(members, subClass.prototype);
  1481. copyNativeMethods(members, subClass.prototype); // hack for IE8
  1482. // copy over all class variables/methods to the subclass, such as `extend` and `mixin`
  1483. copyOwnProps(superClass, subClass);
  1484. return subClass;
  1485. }
  1486. function mixIntoClass(theClass, members) {
  1487. copyOwnProps(members, theClass.prototype); // TODO: copyNativeMethods?
  1488. }
  1489. ;;
  1490. var EmitterMixin = FC.EmitterMixin = {
  1491. // jQuery-ification via $(this) allows a non-DOM object to have
  1492. // the same event handling capabilities (including namespaces).
  1493. on: function(types, handler) {
  1494. // handlers are always called with an "event" object as their first param.
  1495. // sneak the `this` context and arguments into the extra parameter object
  1496. // and forward them on to the original handler.
  1497. var intercept = function(ev, extra) {
  1498. return handler.apply(
  1499. extra.context || this,
  1500. extra.args || []
  1501. );
  1502. };
  1503. // mimick jQuery's internal "proxy" system (risky, I know)
  1504. // causing all functions with the same .guid to appear to be the same.
  1505. // https://github.com/jquery/jquery/blob/2.2.4/src/core.js#L448
  1506. // this is needed for calling .off with the original non-intercept handler.
  1507. if (!handler.guid) {
  1508. handler.guid = $.guid++;
  1509. }
  1510. intercept.guid = handler.guid;
  1511. $(this).on(types, intercept);
  1512. return this; // for chaining
  1513. },
  1514. off: function(types, handler) {
  1515. $(this).off(types, handler);
  1516. return this; // for chaining
  1517. },
  1518. trigger: function(types) {
  1519. var args = Array.prototype.slice.call(arguments, 1); // arguments after the first
  1520. // pass in "extra" info to the intercept
  1521. $(this).triggerHandler(types, { args: args });
  1522. return this; // for chaining
  1523. },
  1524. triggerWith: function(types, context, args) {
  1525. // `triggerHandler` is less reliant on the DOM compared to `trigger`.
  1526. // pass in "extra" info to the intercept.
  1527. $(this).triggerHandler(types, { context: context, args: args });
  1528. return this; // for chaining
  1529. }
  1530. };
  1531. ;;
  1532. /*
  1533. Utility methods for easily listening to events on another object,
  1534. and more importantly, easily unlistening from them.
  1535. */
  1536. var ListenerMixin = FC.ListenerMixin = (function() {
  1537. var guid = 0;
  1538. var ListenerMixin = {
  1539. listenerId: null,
  1540. /*
  1541. Given an `other` object that has on/off methods, bind the given `callback` to an event by the given name.
  1542. The `callback` will be called with the `this` context of the object that .listenTo is being called on.
  1543. Can be called:
  1544. .listenTo(other, eventName, callback)
  1545. OR
  1546. .listenTo(other, {
  1547. eventName1: callback1,
  1548. eventName2: callback2
  1549. })
  1550. */
  1551. listenTo: function(other, arg, callback) {
  1552. if (typeof arg === 'object') { // given dictionary of callbacks
  1553. for (var eventName in arg) {
  1554. if (arg.hasOwnProperty(eventName)) {
  1555. this.listenTo(other, eventName, arg[eventName]);
  1556. }
  1557. }
  1558. }
  1559. else if (typeof arg === 'string') {
  1560. other.on(
  1561. arg + '.' + this.getListenerNamespace(), // use event namespacing to identify this object
  1562. $.proxy(callback, this) // always use `this` context
  1563. // the usually-undesired jQuery guid behavior doesn't matter,
  1564. // because we always unbind via namespace
  1565. );
  1566. }
  1567. },
  1568. /*
  1569. Causes the current object to stop listening to events on the `other` object.
  1570. `eventName` is optional. If omitted, will stop listening to ALL events on `other`.
  1571. */
  1572. stopListeningTo: function(other, eventName) {
  1573. other.off((eventName || '') + '.' + this.getListenerNamespace());
  1574. },
  1575. /*
  1576. Returns a string, unique to this object, to be used for event namespacing
  1577. */
  1578. getListenerNamespace: function() {
  1579. if (this.listenerId == null) {
  1580. this.listenerId = guid++;
  1581. }
  1582. return '_listener' + this.listenerId;
  1583. }
  1584. };
  1585. return ListenerMixin;
  1586. })();
  1587. ;;
  1588. // simple class for toggle a `isIgnoringMouse` flag on delay
  1589. // initMouseIgnoring must first be called, with a millisecond delay setting.
  1590. var MouseIgnorerMixin = {
  1591. isIgnoringMouse: false, // bool
  1592. delayUnignoreMouse: null, // method
  1593. initMouseIgnoring: function(delay) {
  1594. this.delayUnignoreMouse = debounce(proxy(this, 'unignoreMouse'), delay || 1000);
  1595. },
  1596. // temporarily ignore mouse actions on segments
  1597. tempIgnoreMouse: function() {
  1598. this.isIgnoringMouse = true;
  1599. this.delayUnignoreMouse();
  1600. },
  1601. // delayUnignoreMouse eventually calls this
  1602. unignoreMouse: function() {
  1603. this.isIgnoringMouse = false;
  1604. }
  1605. };
  1606. ;;
  1607. /* A rectangular panel that is absolutely positioned over other content
  1608. ------------------------------------------------------------------------------------------------------------------------
  1609. Options:
  1610. - className (string)
  1611. - content (HTML string or jQuery element set)
  1612. - parentEl
  1613. - top
  1614. - left
  1615. - right (the x coord of where the right edge should be. not a "CSS" right)
  1616. - autoHide (boolean)
  1617. - show (callback)
  1618. - hide (callback)
  1619. */
  1620. var Popover = Class.extend(ListenerMixin, {
  1621. isHidden: true,
  1622. options: null,
  1623. el: null, // the container element for the popover. generated by this object
  1624. margin: 10, // the space required between the popover and the edges of the scroll container
  1625. constructor: function(options) {
  1626. this.options = options || {};
  1627. },
  1628. // Shows the popover on the specified position. Renders it if not already
  1629. show: function() {
  1630. if (this.isHidden) {
  1631. if (!this.el) {
  1632. this.render();
  1633. }
  1634. this.el.show();
  1635. this.position();
  1636. this.isHidden = false;
  1637. this.trigger('show');
  1638. }
  1639. },
  1640. // Hides the popover, through CSS, but does not remove it from the DOM
  1641. hide: function() {
  1642. if (!this.isHidden) {
  1643. this.el.hide();
  1644. this.isHidden = true;
  1645. this.trigger('hide');
  1646. }
  1647. },
  1648. // Creates `this.el` and renders content inside of it
  1649. render: function() {
  1650. var _this = this;
  1651. var options = this.options;
  1652. this.el = $('<div class="fc-popover"/>')
  1653. .addClass(options.className || '')
  1654. .css({
  1655. // position initially to the top left to avoid creating scrollbars
  1656. top: 0,
  1657. left: 0
  1658. })
  1659. .append(options.content)
  1660. .appendTo(options.parentEl);
  1661. // when a click happens on anything inside with a 'fc-close' className, hide the popover
  1662. this.el.on('click', '.fc-close', function() {
  1663. _this.hide();
  1664. });
  1665. if (options.autoHide) {
  1666. this.listenTo($(document), 'mousedown', this.documentMousedown);
  1667. }
  1668. },
  1669. // Triggered when the user clicks *anywhere* in the document, for the autoHide feature
  1670. documentMousedown: function(ev) {
  1671. // only hide the popover if the click happened outside the popover
  1672. if (this.el && !$(ev.target).closest(this.el).length) {
  1673. this.hide();
  1674. }
  1675. },
  1676. // Hides and unregisters any handlers
  1677. removeElement: function() {
  1678. this.hide();
  1679. if (this.el) {
  1680. this.el.remove();
  1681. this.el = null;
  1682. }
  1683. this.stopListeningTo($(document), 'mousedown');
  1684. },
  1685. // Positions the popover optimally, using the top/left/right options
  1686. position: function() {
  1687. var options = this.options;
  1688. var origin = this.el.offsetParent().offset();
  1689. var width = this.el.outerWidth();
  1690. var height = this.el.outerHeight();
  1691. var windowEl = $(window);
  1692. var viewportEl = getScrollParent(this.el);
  1693. var viewportTop;
  1694. var viewportLeft;
  1695. var viewportOffset;
  1696. var top; // the "position" (not "offset") values for the popover
  1697. var left; //
  1698. // compute top and left
  1699. top = options.top || 0;
  1700. if (options.left !== undefined) {
  1701. left = options.left;
  1702. }
  1703. else if (options.right !== undefined) {
  1704. left = options.right - width; // derive the left value from the right value
  1705. }
  1706. else {
  1707. left = 0;
  1708. }
  1709. if (viewportEl.is(window) || viewportEl.is(document)) { // normalize getScrollParent's result
  1710. viewportEl = windowEl;
  1711. viewportTop = 0; // the window is always at the top left
  1712. viewportLeft = 0; // (and .offset() won't work if called here)
  1713. }
  1714. else {
  1715. viewportOffset = viewportEl.offset();
  1716. viewportTop = viewportOffset.top;
  1717. viewportLeft = viewportOffset.left;
  1718. }
  1719. // if the window is scrolled, it causes the visible area to be further down
  1720. viewportTop += windowEl.scrollTop();
  1721. viewportLeft += windowEl.scrollLeft();
  1722. // constrain to the view port. if constrained by two edges, give precedence to top/left
  1723. if (options.viewportConstrain !== false) {
  1724. top = Math.min(top, viewportTop + viewportEl.outerHeight() - height - this.margin);
  1725. top = Math.max(top, viewportTop + this.margin);
  1726. left = Math.min(left, viewportLeft + viewportEl.outerWidth() - width - this.margin);
  1727. left = Math.max(left, viewportLeft + this.margin);
  1728. }
  1729. this.el.css({
  1730. top: top - origin.top,
  1731. left: left - origin.left
  1732. });
  1733. },
  1734. // Triggers a callback. Calls a function in the option hash of the same name.
  1735. // Arguments beyond the first `name` are forwarded on.
  1736. // TODO: better code reuse for this. Repeat code
  1737. trigger: function(name) {
  1738. if (this.options[name]) {
  1739. this.options[name].apply(this, Array.prototype.slice.call(arguments, 1));
  1740. }
  1741. }
  1742. });
  1743. ;;
  1744. /*
  1745. A cache for the left/right/top/bottom/width/height values for one or more elements.
  1746. Works with both offset (from topleft document) and position (from offsetParent).
  1747. options:
  1748. - els
  1749. - isHorizontal
  1750. - isVertical
  1751. */
  1752. var CoordCache = FC.CoordCache = Class.extend({
  1753. els: null, // jQuery set (assumed to be siblings)
  1754. forcedOffsetParentEl: null, // options can override the natural offsetParent
  1755. origin: null, // {left,top} position of offsetParent of els
  1756. boundingRect: null, // constrain cordinates to this rectangle. {left,right,top,bottom} or null
  1757. isHorizontal: false, // whether to query for left/right/width
  1758. isVertical: false, // whether to query for top/bottom/height
  1759. // arrays of coordinates (offsets from topleft of document)
  1760. lefts: null,
  1761. rights: null,
  1762. tops: null,
  1763. bottoms: null,
  1764. constructor: function(options) {
  1765. this.els = $(options.els);
  1766. this.isHorizontal = options.isHorizontal;
  1767. this.isVertical = options.isVertical;
  1768. this.forcedOffsetParentEl = options.offsetParent ? $(options.offsetParent) : null;
  1769. },
  1770. // Queries the els for coordinates and stores them.
  1771. // Call this method before using and of the get* methods below.
  1772. build: function() {
  1773. var offsetParentEl = this.forcedOffsetParentEl || this.els.eq(0).offsetParent();
  1774. this.origin = offsetParentEl.offset();
  1775. this.boundingRect = this.queryBoundingRect();
  1776. if (this.isHorizontal) {
  1777. this.buildElHorizontals();
  1778. }
  1779. if (this.isVertical) {
  1780. this.buildElVerticals();
  1781. }
  1782. },
  1783. // Destroys all internal data about coordinates, freeing memory
  1784. clear: function() {
  1785. this.origin = null;
  1786. this.boundingRect = null;
  1787. this.lefts = null;
  1788. this.rights = null;
  1789. this.tops = null;
  1790. this.bottoms = null;
  1791. },
  1792. // When called, if coord caches aren't built, builds them
  1793. ensureBuilt: function() {
  1794. if (!this.origin) {
  1795. this.build();
  1796. }
  1797. },
  1798. // Populates the left/right internal coordinate arrays
  1799. buildElHorizontals: function() {
  1800. var lefts = [];
  1801. var rights = [];
  1802. this.els.each(function(i, node) {
  1803. var el = $(node);
  1804. var left = el.offset().left;
  1805. var width = el.outerWidth();
  1806. lefts.push(left);
  1807. rights.push(left + width);
  1808. });
  1809. this.lefts = lefts;
  1810. this.rights = rights;
  1811. },
  1812. // Populates the top/bottom internal coordinate arrays
  1813. buildElVerticals: function() {
  1814. var tops = [];
  1815. var bottoms = [];
  1816. this.els.each(function(i, node) {
  1817. var el = $(node);
  1818. var top = el.offset().top;
  1819. var height = el.outerHeight();
  1820. tops.push(top);
  1821. bottoms.push(top + height);
  1822. });
  1823. this.tops = tops;
  1824. this.bottoms = bottoms;
  1825. },
  1826. // Given a left offset (from document left), returns the index of the el that it horizontally intersects.
  1827. // If no intersection is made, returns undefined.
  1828. getHorizontalIndex: function(leftOffset) {
  1829. this.ensureBuilt();
  1830. var lefts = this.lefts;
  1831. var rights = this.rights;
  1832. var len = lefts.length;
  1833. var i;
  1834. for (i = 0; i < len; i++) {
  1835. if (leftOffset >= lefts[i] && leftOffset < rights[i]) {
  1836. return i;
  1837. }
  1838. }
  1839. },
  1840. // Given a top offset (from document top), returns the index of the el that it vertically intersects.
  1841. // If no intersection is made, returns undefined.
  1842. getVerticalIndex: function(topOffset) {
  1843. this.ensureBuilt();
  1844. var tops = this.tops;
  1845. var bottoms = this.bottoms;
  1846. var len = tops.length;
  1847. var i;
  1848. for (i = 0; i < len; i++) {
  1849. if (topOffset >= tops[i] && topOffset < bottoms[i]) {
  1850. return i;
  1851. }
  1852. }
  1853. },
  1854. // Gets the left offset (from document left) of the element at the given index
  1855. getLeftOffset: function(leftIndex) {
  1856. this.ensureBuilt();
  1857. return this.lefts[leftIndex];
  1858. },
  1859. // Gets the left position (from offsetParent left) of the element at the given index
  1860. getLeftPosition: function(leftIndex) {
  1861. this.ensureBuilt();
  1862. return this.lefts[leftIndex] - this.origin.left;
  1863. },
  1864. // Gets the right offset (from document left) of the element at the given index.
  1865. // This value is NOT relative to the document's right edge, like the CSS concept of "right" would be.
  1866. getRightOffset: function(leftIndex) {
  1867. this.ensureBuilt();
  1868. return this.rights[leftIndex];
  1869. },
  1870. // Gets the right position (from offsetParent left) of the element at the given index.
  1871. // This value is NOT relative to the offsetParent's right edge, like the CSS concept of "right" would be.
  1872. getRightPosition: function(leftIndex) {
  1873. this.ensureBuilt();
  1874. return this.rights[leftIndex] - this.origin.left;
  1875. },
  1876. // Gets the width of the element at the given index
  1877. getWidth: function(leftIndex) {
  1878. this.ensureBuilt();
  1879. return this.rights[leftIndex] - this.lefts[leftIndex];
  1880. },
  1881. // Gets the top offset (from document top) of the element at the given index
  1882. getTopOffset: function(topIndex) {
  1883. this.ensureBuilt();
  1884. return this.tops[topIndex];
  1885. },
  1886. // Gets the top position (from offsetParent top) of the element at the given position
  1887. getTopPosition: function(topIndex) {
  1888. this.ensureBuilt();
  1889. return this.tops[topIndex] - this.origin.top;
  1890. },
  1891. // Gets the bottom offset (from the document top) of the element at the given index.
  1892. // This value is NOT relative to the offsetParent's bottom edge, like the CSS concept of "bottom" would be.
  1893. getBottomOffset: function(topIndex) {
  1894. this.ensureBuilt();
  1895. return this.bottoms[topIndex];
  1896. },
  1897. // Gets the bottom position (from the offsetParent top) of the element at the given index.
  1898. // This value is NOT relative to the offsetParent's bottom edge, like the CSS concept of "bottom" would be.
  1899. getBottomPosition: function(topIndex) {
  1900. this.ensureBuilt();
  1901. return this.bottoms[topIndex] - this.origin.top;
  1902. },
  1903. // Gets the height of the element at the given index
  1904. getHeight: function(topIndex) {
  1905. this.ensureBuilt();
  1906. return this.bottoms[topIndex] - this.tops[topIndex];
  1907. },
  1908. // Bounding Rect
  1909. // TODO: decouple this from CoordCache
  1910. // Compute and return what the elements' bounding rectangle is, from the user's perspective.
  1911. // Right now, only returns a rectangle if constrained by an overflow:scroll element.
  1912. queryBoundingRect: function() {
  1913. var scrollParentEl = getScrollParent(this.els.eq(0));
  1914. if (!scrollParentEl.is(document)) {
  1915. return getClientRect(scrollParentEl);
  1916. }
  1917. },
  1918. isPointInBounds: function(leftOffset, topOffset) {
  1919. return this.isLeftInBounds(leftOffset) && this.isTopInBounds(topOffset);
  1920. },
  1921. isLeftInBounds: function(leftOffset) {
  1922. return !this.boundingRect || (leftOffset >= this.boundingRect.left && leftOffset < this.boundingRect.right);
  1923. },
  1924. isTopInBounds: function(topOffset) {
  1925. return !this.boundingRect || (topOffset >= this.boundingRect.top && topOffset < this.boundingRect.bottom);
  1926. }
  1927. });
  1928. ;;
  1929. /* Tracks a drag's mouse movement, firing various handlers
  1930. ----------------------------------------------------------------------------------------------------------------------*/
  1931. // TODO: use Emitter
  1932. var DragListener = FC.DragListener = Class.extend(ListenerMixin, MouseIgnorerMixin, {
  1933. options: null,
  1934. // for IE8 bug-fighting behavior
  1935. subjectEl: null,
  1936. subjectHref: null,
  1937. // coordinates of the initial mousedown
  1938. originX: null,
  1939. originY: null,
  1940. // the wrapping element that scrolls, or MIGHT scroll if there's overflow.
  1941. // TODO: do this for wrappers that have overflow:hidden as well.
  1942. scrollEl: null,
  1943. isInteracting: false,
  1944. isDistanceSurpassed: false,
  1945. isDelayEnded: false,
  1946. isDragging: false,
  1947. isTouch: false,
  1948. delay: null,
  1949. delayTimeoutId: null,
  1950. minDistance: null,
  1951. handleTouchScrollProxy: null, // calls handleTouchScroll, always bound to `this`
  1952. constructor: function(options) {
  1953. this.options = options || {};
  1954. this.handleTouchScrollProxy = proxy(this, 'handleTouchScroll');
  1955. this.initMouseIgnoring(500);
  1956. },
  1957. // Interaction (high-level)
  1958. // -----------------------------------------------------------------------------------------------------------------
  1959. startInteraction: function(ev, extraOptions) {
  1960. var isTouch = getEvIsTouch(ev);
  1961. if (ev.type === 'mousedown') {
  1962. if (this.isIgnoringMouse) {
  1963. return;
  1964. }
  1965. else if (!isPrimaryMouseButton(ev)) {
  1966. return;
  1967. }
  1968. else {
  1969. ev.preventDefault(); // prevents native selection in most browsers
  1970. }
  1971. }
  1972. if (!this.isInteracting) {
  1973. // process options
  1974. extraOptions = extraOptions || {};
  1975. this.delay = firstDefined(extraOptions.delay, this.options.delay, 0);
  1976. this.minDistance = firstDefined(extraOptions.distance, this.options.distance, 0);
  1977. this.subjectEl = this.options.subjectEl;
  1978. this.isInteracting = true;
  1979. this.isTouch = isTouch;
  1980. this.isDelayEnded = false;
  1981. this.isDistanceSurpassed = false;
  1982. this.originX = getEvX(ev);
  1983. this.originY = getEvY(ev);
  1984. this.scrollEl = getScrollParent($(ev.target));
  1985. this.bindHandlers();
  1986. this.initAutoScroll();
  1987. this.handleInteractionStart(ev);
  1988. this.startDelay(ev);
  1989. if (!this.minDistance) {
  1990. this.handleDistanceSurpassed(ev);
  1991. }
  1992. }
  1993. },
  1994. handleInteractionStart: function(ev) {
  1995. this.trigger('interactionStart', ev);
  1996. },
  1997. endInteraction: function(ev, isCancelled) {
  1998. if (this.isInteracting) {
  1999. this.endDrag(ev);
  2000. if (this.delayTimeoutId) {
  2001. clearTimeout(this.delayTimeoutId);
  2002. this.delayTimeoutId = null;
  2003. }
  2004. this.destroyAutoScroll();
  2005. this.unbindHandlers();
  2006. this.isInteracting = false;
  2007. this.handleInteractionEnd(ev, isCancelled);
  2008. // a touchstart+touchend on the same element will result in the following addition simulated events:
  2009. // mouseover + mouseout + click
  2010. // let's ignore these bogus events
  2011. if (this.isTouch) {
  2012. this.tempIgnoreMouse();
  2013. }
  2014. }
  2015. },
  2016. handleInteractionEnd: function(ev, isCancelled) {
  2017. this.trigger('interactionEnd', ev, isCancelled || false);
  2018. },
  2019. // Binding To DOM
  2020. // -----------------------------------------------------------------------------------------------------------------
  2021. bindHandlers: function() {
  2022. var _this = this;
  2023. var touchStartIgnores = 1;
  2024. if (this.isTouch) {
  2025. this.listenTo($(document), {
  2026. touchmove: this.handleTouchMove,
  2027. touchend: this.endInteraction,
  2028. touchcancel: this.endInteraction,
  2029. // Sometimes touchend doesn't fire
  2030. // (can't figure out why. touchcancel doesn't fire either. has to do with scrolling?)
  2031. // If another touchstart happens, we know it's bogus, so cancel the drag.
  2032. // touchend will continue to be broken until user does a shorttap/scroll, but this is best we can do.
  2033. touchstart: function(ev) {
  2034. if (touchStartIgnores) { // bindHandlers is called from within a touchstart,
  2035. touchStartIgnores--; // and we don't want this to fire immediately, so ignore.
  2036. }
  2037. else {
  2038. _this.endInteraction(ev, true); // isCancelled=true
  2039. }
  2040. }
  2041. });
  2042. // listen to ALL scroll actions on the page
  2043. if (
  2044. !bindAnyScroll(this.handleTouchScrollProxy) && // hopefully this works and short-circuits the rest
  2045. this.scrollEl // otherwise, attach a single handler to this
  2046. ) {
  2047. this.listenTo(this.scrollEl, 'scroll', this.handleTouchScroll);
  2048. }
  2049. }
  2050. else {
  2051. this.listenTo($(document), {
  2052. mousemove: this.handleMouseMove,
  2053. mouseup: this.endInteraction
  2054. });
  2055. }
  2056. this.listenTo($(document), {
  2057. selectstart: preventDefault, // don't allow selection while dragging
  2058. contextmenu: preventDefault // long taps would open menu on Chrome dev tools
  2059. });
  2060. },
  2061. unbindHandlers: function() {
  2062. this.stopListeningTo($(document));
  2063. // unbind scroll listening
  2064. unbindAnyScroll(this.handleTouchScrollProxy);
  2065. if (this.scrollEl) {
  2066. this.stopListeningTo(this.scrollEl, 'scroll');
  2067. }
  2068. },
  2069. // Drag (high-level)
  2070. // -----------------------------------------------------------------------------------------------------------------
  2071. // extraOptions ignored if drag already started
  2072. startDrag: function(ev, extraOptions) {
  2073. this.startInteraction(ev, extraOptions); // ensure interaction began
  2074. if (!this.isDragging) {
  2075. this.isDragging = true;
  2076. this.handleDragStart(ev);
  2077. }
  2078. },
  2079. handleDragStart: function(ev) {
  2080. this.trigger('dragStart', ev);
  2081. this.initHrefHack();
  2082. },
  2083. handleMove: function(ev) {
  2084. var dx = getEvX(ev) - this.originX;
  2085. var dy = getEvY(ev) - this.originY;
  2086. var minDistance = this.minDistance;
  2087. var distanceSq; // current distance from the origin, squared
  2088. if (!this.isDistanceSurpassed) {
  2089. distanceSq = dx * dx + dy * dy;
  2090. if (distanceSq >= minDistance * minDistance) { // use pythagorean theorem
  2091. this.handleDistanceSurpassed(ev);
  2092. }
  2093. }
  2094. if (this.isDragging) {
  2095. this.handleDrag(dx, dy, ev);
  2096. }
  2097. },
  2098. // Called while the mouse is being moved and when we know a legitimate drag is taking place
  2099. handleDrag: function(dx, dy, ev) {
  2100. this.trigger('drag', dx, dy, ev);
  2101. this.updateAutoScroll(ev); // will possibly cause scrolling
  2102. },
  2103. endDrag: function(ev) {
  2104. if (this.isDragging) {
  2105. this.isDragging = false;
  2106. this.handleDragEnd(ev);
  2107. }
  2108. },
  2109. handleDragEnd: function(ev) {
  2110. this.trigger('dragEnd', ev);
  2111. this.destroyHrefHack();
  2112. },
  2113. // Delay
  2114. // -----------------------------------------------------------------------------------------------------------------
  2115. startDelay: function(initialEv) {
  2116. var _this = this;
  2117. if (this.delay) {
  2118. this.delayTimeoutId = setTimeout(function() {
  2119. _this.handleDelayEnd(initialEv);
  2120. }, this.delay);
  2121. }
  2122. else {
  2123. this.handleDelayEnd(initialEv);
  2124. }
  2125. },
  2126. handleDelayEnd: function(initialEv) {
  2127. this.isDelayEnded = true;
  2128. if (this.isDistanceSurpassed) {
  2129. this.startDrag(initialEv);
  2130. }
  2131. },
  2132. // Distance
  2133. // -----------------------------------------------------------------------------------------------------------------
  2134. handleDistanceSurpassed: function(ev) {
  2135. this.isDistanceSurpassed = true;
  2136. if (this.isDelayEnded) {
  2137. this.startDrag(ev);
  2138. }
  2139. },
  2140. // Mouse / Touch
  2141. // -----------------------------------------------------------------------------------------------------------------
  2142. handleTouchMove: function(ev) {
  2143. // prevent inertia and touchmove-scrolling while dragging
  2144. if (this.isDragging) {
  2145. ev.preventDefault();
  2146. }
  2147. this.handleMove(ev);
  2148. },
  2149. handleMouseMove: function(ev) {
  2150. this.handleMove(ev);
  2151. },
  2152. // Scrolling (unrelated to auto-scroll)
  2153. // -----------------------------------------------------------------------------------------------------------------
  2154. handleTouchScroll: function(ev) {
  2155. // if the drag is being initiated by touch, but a scroll happens before
  2156. // the drag-initiating delay is over, cancel the drag
  2157. if (!this.isDragging) {
  2158. this.endInteraction(ev, true); // isCancelled=true
  2159. }
  2160. },
  2161. // <A> HREF Hack
  2162. // -----------------------------------------------------------------------------------------------------------------
  2163. initHrefHack: function() {
  2164. var subjectEl = this.subjectEl;
  2165. // remove a mousedown'd <a>'s href so it is not visited (IE8 bug)
  2166. if ((this.subjectHref = subjectEl ? subjectEl.attr('href') : null)) {
  2167. subjectEl.removeAttr('href');
  2168. }
  2169. },
  2170. destroyHrefHack: function() {
  2171. var subjectEl = this.subjectEl;
  2172. var subjectHref = this.subjectHref;
  2173. // restore a mousedown'd <a>'s href (for IE8 bug)
  2174. setTimeout(function() { // must be outside of the click's execution
  2175. if (subjectHref) {
  2176. subjectEl.attr('href', subjectHref);
  2177. }
  2178. }, 0);
  2179. },
  2180. // Utils
  2181. // -----------------------------------------------------------------------------------------------------------------
  2182. // Triggers a callback. Calls a function in the option hash of the same name.
  2183. // Arguments beyond the first `name` are forwarded on.
  2184. trigger: function(name) {
  2185. if (this.options[name]) {
  2186. this.options[name].apply(this, Array.prototype.slice.call(arguments, 1));
  2187. }
  2188. // makes _methods callable by event name. TODO: kill this
  2189. if (this['_' + name]) {
  2190. this['_' + name].apply(this, Array.prototype.slice.call(arguments, 1));
  2191. }
  2192. }
  2193. });
  2194. ;;
  2195. /*
  2196. this.scrollEl is set in DragListener
  2197. */
  2198. DragListener.mixin({
  2199. isAutoScroll: false,
  2200. scrollBounds: null, // { top, bottom, left, right }
  2201. scrollTopVel: null, // pixels per second
  2202. scrollLeftVel: null, // pixels per second
  2203. scrollIntervalId: null, // ID of setTimeout for scrolling animation loop
  2204. // defaults
  2205. scrollSensitivity: 30, // pixels from edge for scrolling to start
  2206. scrollSpeed: 200, // pixels per second, at maximum speed
  2207. scrollIntervalMs: 50, // millisecond wait between scroll increment
  2208. initAutoScroll: function() {
  2209. var scrollEl = this.scrollEl;
  2210. this.isAutoScroll =
  2211. this.options.scroll &&
  2212. scrollEl &&
  2213. !scrollEl.is(window) &&
  2214. !scrollEl.is(document);
  2215. if (this.isAutoScroll) {
  2216. // debounce makes sure rapid calls don't happen
  2217. this.listenTo(scrollEl, 'scroll', debounce(this.handleDebouncedScroll, 100));
  2218. }
  2219. },
  2220. destroyAutoScroll: function() {
  2221. this.endAutoScroll(); // kill any animation loop
  2222. // remove the scroll handler if there is a scrollEl
  2223. if (this.isAutoScroll) {
  2224. this.stopListeningTo(this.scrollEl, 'scroll'); // will probably get removed by unbindHandlers too :(
  2225. }
  2226. },
  2227. // Computes and stores the bounding rectangle of scrollEl
  2228. computeScrollBounds: function() {
  2229. if (this.isAutoScroll) {
  2230. this.scrollBounds = getOuterRect(this.scrollEl);
  2231. // TODO: use getClientRect in future. but prevents auto scrolling when on top of scrollbars
  2232. }
  2233. },
  2234. // Called when the dragging is in progress and scrolling should be updated
  2235. updateAutoScroll: function(ev) {
  2236. var sensitivity = this.scrollSensitivity;
  2237. var bounds = this.scrollBounds;
  2238. var topCloseness, bottomCloseness;
  2239. var leftCloseness, rightCloseness;
  2240. var topVel = 0;
  2241. var leftVel = 0;
  2242. if (bounds) { // only scroll if scrollEl exists
  2243. // compute closeness to edges. valid range is from 0.0 - 1.0
  2244. topCloseness = (sensitivity - (getEvY(ev) - bounds.top)) / sensitivity;
  2245. bottomCloseness = (sensitivity - (bounds.bottom - getEvY(ev))) / sensitivity;
  2246. leftCloseness = (sensitivity - (getEvX(ev) - bounds.left)) / sensitivity;
  2247. rightCloseness = (sensitivity - (bounds.right - getEvX(ev))) / sensitivity;
  2248. // translate vertical closeness into velocity.
  2249. // mouse must be completely in bounds for velocity to happen.
  2250. if (topCloseness >= 0 && topCloseness <= 1) {
  2251. topVel = topCloseness * this.scrollSpeed * -1; // negative. for scrolling up
  2252. }
  2253. else if (bottomCloseness >= 0 && bottomCloseness <= 1) {
  2254. topVel = bottomCloseness * this.scrollSpeed;
  2255. }
  2256. // translate horizontal closeness into velocity
  2257. if (leftCloseness >= 0 && leftCloseness <= 1) {
  2258. leftVel = leftCloseness * this.scrollSpeed * -1; // negative. for scrolling left
  2259. }
  2260. else if (rightCloseness >= 0 && rightCloseness <= 1) {
  2261. leftVel = rightCloseness * this.scrollSpeed;
  2262. }
  2263. }
  2264. this.setScrollVel(topVel, leftVel);
  2265. },
  2266. // Sets the speed-of-scrolling for the scrollEl
  2267. setScrollVel: function(topVel, leftVel) {
  2268. this.scrollTopVel = topVel;
  2269. this.scrollLeftVel = leftVel;
  2270. this.constrainScrollVel(); // massages into realistic values
  2271. // if there is non-zero velocity, and an animation loop hasn't already started, then START
  2272. if ((this.scrollTopVel || this.scrollLeftVel) && !this.scrollIntervalId) {
  2273. this.scrollIntervalId = setInterval(
  2274. proxy(this, 'scrollIntervalFunc'), // scope to `this`
  2275. this.scrollIntervalMs
  2276. );
  2277. }
  2278. },
  2279. // Forces scrollTopVel and scrollLeftVel to be zero if scrolling has already gone all the way
  2280. constrainScrollVel: function() {
  2281. var el = this.scrollEl;
  2282. if (this.scrollTopVel < 0) { // scrolling up?
  2283. if (el.scrollTop() <= 0) { // already scrolled all the way up?
  2284. this.scrollTopVel = 0;
  2285. }
  2286. }
  2287. else if (this.scrollTopVel > 0) { // scrolling down?
  2288. if (el.scrollTop() + el[0].clientHeight >= el[0].scrollHeight) { // already scrolled all the way down?
  2289. this.scrollTopVel = 0;
  2290. }
  2291. }
  2292. if (this.scrollLeftVel < 0) { // scrolling left?
  2293. if (el.scrollLeft() <= 0) { // already scrolled all the left?
  2294. this.scrollLeftVel = 0;
  2295. }
  2296. }
  2297. else if (this.scrollLeftVel > 0) { // scrolling right?
  2298. if (el.scrollLeft() + el[0].clientWidth >= el[0].scrollWidth) { // already scrolled all the way right?
  2299. this.scrollLeftVel = 0;
  2300. }
  2301. }
  2302. },
  2303. // This function gets called during every iteration of the scrolling animation loop
  2304. scrollIntervalFunc: function() {
  2305. var el = this.scrollEl;
  2306. var frac = this.scrollIntervalMs / 1000; // considering animation frequency, what the vel should be mult'd by
  2307. // change the value of scrollEl's scroll
  2308. if (this.scrollTopVel) {
  2309. el.scrollTop(el.scrollTop() + this.scrollTopVel * frac);
  2310. }
  2311. if (this.scrollLeftVel) {
  2312. el.scrollLeft(el.scrollLeft() + this.scrollLeftVel * frac);
  2313. }
  2314. this.constrainScrollVel(); // since the scroll values changed, recompute the velocities
  2315. // if scrolled all the way, which causes the vels to be zero, stop the animation loop
  2316. if (!this.scrollTopVel && !this.scrollLeftVel) {
  2317. this.endAutoScroll();
  2318. }
  2319. },
  2320. // Kills any existing scrolling animation loop
  2321. endAutoScroll: function() {
  2322. if (this.scrollIntervalId) {
  2323. clearInterval(this.scrollIntervalId);
  2324. this.scrollIntervalId = null;
  2325. this.handleScrollEnd();
  2326. }
  2327. },
  2328. // Get called when the scrollEl is scrolled (NOTE: this is delayed via debounce)
  2329. handleDebouncedScroll: function() {
  2330. // recompute all coordinates, but *only* if this is *not* part of our scrolling animation
  2331. if (!this.scrollIntervalId) {
  2332. this.handleScrollEnd();
  2333. }
  2334. },
  2335. // Called when scrolling has stopped, whether through auto scroll, or the user scrolling
  2336. handleScrollEnd: function() {
  2337. }
  2338. });
  2339. ;;
  2340. /* Tracks mouse movements over a component and raises events about which hit the mouse is over.
  2341. ------------------------------------------------------------------------------------------------------------------------
  2342. options:
  2343. - subjectEl
  2344. - subjectCenter
  2345. */
  2346. var HitDragListener = DragListener.extend({
  2347. component: null, // converts coordinates to hits
  2348. // methods: prepareHits, releaseHits, queryHit
  2349. origHit: null, // the hit the mouse was over when listening started
  2350. hit: null, // the hit the mouse is over
  2351. coordAdjust: null, // delta that will be added to the mouse coordinates when computing collisions
  2352. constructor: function(component, options) {
  2353. DragListener.call(this, options); // call the super-constructor
  2354. this.component = component;
  2355. },
  2356. // Called when drag listening starts (but a real drag has not necessarily began).
  2357. // ev might be undefined if dragging was started manually.
  2358. handleInteractionStart: function(ev) {
  2359. var subjectEl = this.subjectEl;
  2360. var subjectRect;
  2361. var origPoint;
  2362. var point;
  2363. this.computeCoords();
  2364. if (ev) {
  2365. origPoint = { left: getEvX(ev), top: getEvY(ev) };
  2366. point = origPoint;
  2367. // constrain the point to bounds of the element being dragged
  2368. if (subjectEl) {
  2369. subjectRect = getOuterRect(subjectEl); // used for centering as well
  2370. point = constrainPoint(point, subjectRect);
  2371. }
  2372. this.origHit = this.queryHit(point.left, point.top);
  2373. // treat the center of the subject as the collision point?
  2374. if (subjectEl && this.options.subjectCenter) {
  2375. // only consider the area the subject overlaps the hit. best for large subjects.
  2376. // TODO: skip this if hit didn't supply left/right/top/bottom
  2377. if (this.origHit) {
  2378. subjectRect = intersectRects(this.origHit, subjectRect) ||
  2379. subjectRect; // in case there is no intersection
  2380. }
  2381. point = getRectCenter(subjectRect);
  2382. }
  2383. this.coordAdjust = diffPoints(point, origPoint); // point - origPoint
  2384. }
  2385. else {
  2386. this.origHit = null;
  2387. this.coordAdjust = null;
  2388. }
  2389. // call the super-method. do it after origHit has been computed
  2390. DragListener.prototype.handleInteractionStart.apply(this, arguments);
  2391. },
  2392. // Recomputes the drag-critical positions of elements
  2393. computeCoords: function() {
  2394. this.component.prepareHits();
  2395. this.computeScrollBounds(); // why is this here??????
  2396. },
  2397. // Called when the actual drag has started
  2398. handleDragStart: function(ev) {
  2399. var hit;
  2400. DragListener.prototype.handleDragStart.apply(this, arguments); // call the super-method
  2401. // might be different from this.origHit if the min-distance is large
  2402. hit = this.queryHit(getEvX(ev), getEvY(ev));
  2403. // report the initial hit the mouse is over
  2404. // especially important if no min-distance and drag starts immediately
  2405. if (hit) {
  2406. this.handleHitOver(hit);
  2407. }
  2408. },
  2409. // Called when the drag moves
  2410. handleDrag: function(dx, dy, ev) {
  2411. var hit;
  2412. DragListener.prototype.handleDrag.apply(this, arguments); // call the super-method
  2413. hit = this.queryHit(getEvX(ev), getEvY(ev));
  2414. if (!isHitsEqual(hit, this.hit)) { // a different hit than before?
  2415. if (this.hit) {
  2416. this.handleHitOut();
  2417. }
  2418. if (hit) {
  2419. this.handleHitOver(hit);
  2420. }
  2421. }
  2422. },
  2423. // Called when dragging has been stopped
  2424. handleDragEnd: function() {
  2425. this.handleHitDone();
  2426. DragListener.prototype.handleDragEnd.apply(this, arguments); // call the super-method
  2427. },
  2428. // Called when a the mouse has just moved over a new hit
  2429. handleHitOver: function(hit) {
  2430. var isOrig = isHitsEqual(hit, this.origHit);
  2431. this.hit = hit;
  2432. this.trigger('hitOver', this.hit, isOrig, this.origHit);
  2433. },
  2434. // Called when the mouse has just moved out of a hit
  2435. handleHitOut: function() {
  2436. if (this.hit) {
  2437. this.trigger('hitOut', this.hit);
  2438. this.handleHitDone();
  2439. this.hit = null;
  2440. }
  2441. },
  2442. // Called after a hitOut. Also called before a dragStop
  2443. handleHitDone: function() {
  2444. if (this.hit) {
  2445. this.trigger('hitDone', this.hit);
  2446. }
  2447. },
  2448. // Called when the interaction ends, whether there was a real drag or not
  2449. handleInteractionEnd: function() {
  2450. DragListener.prototype.handleInteractionEnd.apply(this, arguments); // call the super-method
  2451. this.origHit = null;
  2452. this.hit = null;
  2453. this.component.releaseHits();
  2454. },
  2455. // Called when scrolling has stopped, whether through auto scroll, or the user scrolling
  2456. handleScrollEnd: function() {
  2457. DragListener.prototype.handleScrollEnd.apply(this, arguments); // call the super-method
  2458. this.computeCoords(); // hits' absolute positions will be in new places. recompute
  2459. },
  2460. // Gets the hit underneath the coordinates for the given mouse event
  2461. queryHit: function(left, top) {
  2462. if (this.coordAdjust) {
  2463. left += this.coordAdjust.left;
  2464. top += this.coordAdjust.top;
  2465. }
  2466. return this.component.queryHit(left, top);
  2467. }
  2468. });
  2469. // Returns `true` if the hits are identically equal. `false` otherwise. Must be from the same component.
  2470. // Two null values will be considered equal, as two "out of the component" states are the same.
  2471. function isHitsEqual(hit0, hit1) {
  2472. if (!hit0 && !hit1) {
  2473. return true;
  2474. }
  2475. if (hit0 && hit1) {
  2476. return hit0.component === hit1.component &&
  2477. isHitPropsWithin(hit0, hit1) &&
  2478. isHitPropsWithin(hit1, hit0); // ensures all props are identical
  2479. }
  2480. return false;
  2481. }
  2482. // Returns true if all of subHit's non-standard properties are within superHit
  2483. function isHitPropsWithin(subHit, superHit) {
  2484. for (var propName in subHit) {
  2485. if (!/^(component|left|right|top|bottom)$/.test(propName)) {
  2486. if (subHit[propName] !== superHit[propName]) {
  2487. return false;
  2488. }
  2489. }
  2490. }
  2491. return true;
  2492. }
  2493. ;;
  2494. /* Creates a clone of an element and lets it track the mouse as it moves
  2495. ----------------------------------------------------------------------------------------------------------------------*/
  2496. var MouseFollower = Class.extend(ListenerMixin, {
  2497. options: null,
  2498. sourceEl: null, // the element that will be cloned and made to look like it is dragging
  2499. el: null, // the clone of `sourceEl` that will track the mouse
  2500. parentEl: null, // the element that `el` (the clone) will be attached to
  2501. // the initial position of el, relative to the offset parent. made to match the initial offset of sourceEl
  2502. top0: null,
  2503. left0: null,
  2504. // the absolute coordinates of the initiating touch/mouse action
  2505. y0: null,
  2506. x0: null,
  2507. // the number of pixels the mouse has moved from its initial position
  2508. topDelta: null,
  2509. leftDelta: null,
  2510. isFollowing: false,
  2511. isHidden: false,
  2512. isAnimating: false, // doing the revert animation?
  2513. constructor: function(sourceEl, options) {
  2514. this.options = options = options || {};
  2515. this.sourceEl = sourceEl;
  2516. this.parentEl = options.parentEl ? $(options.parentEl) : sourceEl.parent(); // default to sourceEl's parent
  2517. },
  2518. // Causes the element to start following the mouse
  2519. start: function(ev) {
  2520. if (!this.isFollowing) {
  2521. this.isFollowing = true;
  2522. this.y0 = getEvY(ev);
  2523. this.x0 = getEvX(ev);
  2524. this.topDelta = 0;
  2525. this.leftDelta = 0;
  2526. if (!this.isHidden) {
  2527. this.updatePosition();
  2528. }
  2529. if (getEvIsTouch(ev)) {
  2530. this.listenTo($(document), 'touchmove', this.handleMove);
  2531. }
  2532. else {
  2533. this.listenTo($(document), 'mousemove', this.handleMove);
  2534. }
  2535. }
  2536. },
  2537. // Causes the element to stop following the mouse. If shouldRevert is true, will animate back to original position.
  2538. // `callback` gets invoked when the animation is complete. If no animation, it is invoked immediately.
  2539. stop: function(shouldRevert, callback) {
  2540. var _this = this;
  2541. var revertDuration = this.options.revertDuration;
  2542. function complete() { // might be called by .animate(), which might change `this` context
  2543. _this.isAnimating = false;
  2544. _this.removeElement();
  2545. _this.top0 = _this.left0 = null; // reset state for future updatePosition calls
  2546. if (callback) {
  2547. callback();
  2548. }
  2549. }
  2550. if (this.isFollowing && !this.isAnimating) { // disallow more than one stop animation at a time
  2551. this.isFollowing = false;
  2552. this.stopListeningTo($(document));
  2553. if (shouldRevert && revertDuration && !this.isHidden) { // do a revert animation?
  2554. this.isAnimating = true;
  2555. this.el.animate({
  2556. top: this.top0,
  2557. left: this.left0
  2558. }, {
  2559. duration: revertDuration,
  2560. complete: complete
  2561. });
  2562. }
  2563. else {
  2564. complete();
  2565. }
  2566. }
  2567. },
  2568. // Gets the tracking element. Create it if necessary
  2569. getEl: function() {
  2570. var el = this.el;
  2571. if (!el) {
  2572. this.sourceEl.width(); // hack to force IE8 to compute correct bounding box
  2573. el = this.el = this.sourceEl.clone()
  2574. .addClass(this.options.additionalClass || '')
  2575. .css({
  2576. position: 'absolute',
  2577. visibility: '', // in case original element was hidden (commonly through hideEvents())
  2578. display: this.isHidden ? 'none' : '', // for when initially hidden
  2579. margin: 0,
  2580. right: 'auto', // erase and set width instead
  2581. bottom: 'auto', // erase and set height instead
  2582. width: this.sourceEl.width(), // explicit height in case there was a 'right' value
  2583. height: this.sourceEl.height(), // explicit width in case there was a 'bottom' value
  2584. opacity: this.options.opacity || '',
  2585. zIndex: this.options.zIndex
  2586. });
  2587. // we don't want long taps or any mouse interaction causing selection/menus.
  2588. // would use preventSelection(), but that prevents selectstart, causing problems.
  2589. el.addClass('fc-unselectable');
  2590. el.appendTo(this.parentEl);
  2591. }
  2592. return el;
  2593. },
  2594. // Removes the tracking element if it has already been created
  2595. removeElement: function() {
  2596. if (this.el) {
  2597. this.el.remove();
  2598. this.el = null;
  2599. }
  2600. },
  2601. // Update the CSS position of the tracking element
  2602. updatePosition: function() {
  2603. var sourceOffset;
  2604. var origin;
  2605. this.getEl(); // ensure this.el
  2606. // make sure origin info was computed
  2607. if (this.top0 === null) {
  2608. this.sourceEl.width(); // hack to force IE8 to compute correct bounding box
  2609. sourceOffset = this.sourceEl.offset();
  2610. origin = this.el.offsetParent().offset();
  2611. this.top0 = sourceOffset.top - origin.top;
  2612. this.left0 = sourceOffset.left - origin.left;
  2613. }
  2614. this.el.css({
  2615. top: this.top0 + this.topDelta,
  2616. left: this.left0 + this.leftDelta
  2617. });
  2618. },
  2619. // Gets called when the user moves the mouse
  2620. handleMove: function(ev) {
  2621. this.topDelta = getEvY(ev) - this.y0;
  2622. this.leftDelta = getEvX(ev) - this.x0;
  2623. if (!this.isHidden) {
  2624. this.updatePosition();
  2625. }
  2626. },
  2627. // Temporarily makes the tracking element invisible. Can be called before following starts
  2628. hide: function() {
  2629. if (!this.isHidden) {
  2630. this.isHidden = true;
  2631. if (this.el) {
  2632. this.el.hide();
  2633. }
  2634. }
  2635. },
  2636. // Show the tracking element after it has been temporarily hidden
  2637. show: function() {
  2638. if (this.isHidden) {
  2639. this.isHidden = false;
  2640. this.updatePosition();
  2641. this.getEl().show();
  2642. }
  2643. }
  2644. });
  2645. ;;
  2646. /* An abstract class comprised of a "grid" of areas that each represent a specific datetime
  2647. ----------------------------------------------------------------------------------------------------------------------*/
  2648. var Grid = FC.Grid = Class.extend(ListenerMixin, MouseIgnorerMixin, {
  2649. view: null, // a View object
  2650. isRTL: null, // shortcut to the view's isRTL option
  2651. start: null,
  2652. end: null,
  2653. el: null, // the containing element
  2654. elsByFill: null, // a hash of jQuery element sets used for rendering each fill. Keyed by fill name.
  2655. // derived from options
  2656. eventTimeFormat: null,
  2657. displayEventTime: null,
  2658. displayEventEnd: null,
  2659. minResizeDuration: null, // TODO: hack. set by subclasses. minumum event resize duration
  2660. // if defined, holds the unit identified (ex: "year" or "month") that determines the level of granularity
  2661. // of the date areas. if not defined, assumes to be day and time granularity.
  2662. // TODO: port isTimeScale into same system?
  2663. largeUnit: null,
  2664. dayDragListener: null,
  2665. segDragListener: null,
  2666. segResizeListener: null,
  2667. externalDragListener: null,
  2668. constructor: function(view) {
  2669. this.view = view;
  2670. this.isRTL = view.opt('isRTL');
  2671. this.elsByFill = {};
  2672. this.dayDragListener = this.buildDayDragListener();
  2673. this.initMouseIgnoring();
  2674. },
  2675. /* Options
  2676. ------------------------------------------------------------------------------------------------------------------*/
  2677. // Generates the format string used for event time text, if not explicitly defined by 'timeFormat'
  2678. computeEventTimeFormat: function() {
  2679. return this.view.opt('smallTimeFormat');
  2680. },
  2681. // Determines whether events should have their end times displayed, if not explicitly defined by 'displayEventTime'.
  2682. // Only applies to non-all-day events.
  2683. computeDisplayEventTime: function() {
  2684. return true;
  2685. },
  2686. // Determines whether events should have their end times displayed, if not explicitly defined by 'displayEventEnd'
  2687. computeDisplayEventEnd: function() {
  2688. return true;
  2689. },
  2690. /* Dates
  2691. ------------------------------------------------------------------------------------------------------------------*/
  2692. // Tells the grid about what period of time to display.
  2693. // Any date-related internal data should be generated.
  2694. setRange: function(range) {
  2695. this.start = range.start.clone();
  2696. this.end = range.end.clone();
  2697. this.rangeUpdated();
  2698. this.processRangeOptions();
  2699. },
  2700. // Called when internal variables that rely on the range should be updated
  2701. rangeUpdated: function() {
  2702. },
  2703. // Updates values that rely on options and also relate to range
  2704. processRangeOptions: function() {
  2705. var view = this.view;
  2706. var displayEventTime;
  2707. var displayEventEnd;
  2708. this.eventTimeFormat =
  2709. view.opt('eventTimeFormat') ||
  2710. view.opt('timeFormat') || // deprecated
  2711. this.computeEventTimeFormat();
  2712. displayEventTime = view.opt('displayEventTime');
  2713. if (displayEventTime == null) {
  2714. displayEventTime = this.computeDisplayEventTime(); // might be based off of range
  2715. }
  2716. displayEventEnd = view.opt('displayEventEnd');
  2717. if (displayEventEnd == null) {
  2718. displayEventEnd = this.computeDisplayEventEnd(); // might be based off of range
  2719. }
  2720. this.displayEventTime = displayEventTime;
  2721. this.displayEventEnd = displayEventEnd;
  2722. },
  2723. // Converts a span (has unzoned start/end and any other grid-specific location information)
  2724. // into an array of segments (pieces of events whose format is decided by the grid).
  2725. spanToSegs: function(span) {
  2726. // subclasses must implement
  2727. },
  2728. // Diffs the two dates, returning a duration, based on granularity of the grid
  2729. // TODO: port isTimeScale into this system?
  2730. diffDates: function(a, b) {
  2731. if (this.largeUnit) {
  2732. return diffByUnit(a, b, this.largeUnit);
  2733. }
  2734. else {
  2735. return diffDayTime(a, b);
  2736. }
  2737. },
  2738. /* Hit Area
  2739. ------------------------------------------------------------------------------------------------------------------*/
  2740. // Called before one or more queryHit calls might happen. Should prepare any cached coordinates for queryHit
  2741. prepareHits: function() {
  2742. },
  2743. // Called when queryHit calls have subsided. Good place to clear any coordinate caches.
  2744. releaseHits: function() {
  2745. },
  2746. // Given coordinates from the topleft of the document, return data about the date-related area underneath.
  2747. // Can return an object with arbitrary properties (although top/right/left/bottom are encouraged).
  2748. // Must have a `grid` property, a reference to this current grid. TODO: avoid this
  2749. // The returned object will be processed by getHitSpan and getHitEl.
  2750. queryHit: function(leftOffset, topOffset) {
  2751. },
  2752. // Given position-level information about a date-related area within the grid,
  2753. // should return an object with at least a start/end date. Can provide other information as well.
  2754. getHitSpan: function(hit) {
  2755. },
  2756. // Given position-level information about a date-related area within the grid,
  2757. // should return a jQuery element that best represents it. passed to dayClick callback.
  2758. getHitEl: function(hit) {
  2759. },
  2760. /* Rendering
  2761. ------------------------------------------------------------------------------------------------------------------*/
  2762. // Sets the container element that the grid should render inside of.
  2763. // Does other DOM-related initializations.
  2764. setElement: function(el) {
  2765. this.el = el;
  2766. preventSelection(el);
  2767. this.bindDayHandler('touchstart', this.dayTouchStart);
  2768. this.bindDayHandler('mousedown', this.dayMousedown);
  2769. // attach event-element-related handlers. in Grid.events
  2770. // same garbage collection note as above.
  2771. this.bindSegHandlers();
  2772. this.bindGlobalHandlers();
  2773. },
  2774. bindDayHandler: function(name, handler) {
  2775. var _this = this;
  2776. // attach a handler to the grid's root element.
  2777. // jQuery will take care of unregistering them when removeElement gets called.
  2778. this.el.on(name, function(ev) {
  2779. if (
  2780. !$(ev.target).is('.fc-event-container *, .fc-more') // not an an event element, or "more.." link
  2781. ) {
  2782. return handler.call(_this, ev);
  2783. }
  2784. });
  2785. },
  2786. // Removes the grid's container element from the DOM. Undoes any other DOM-related attachments.
  2787. // DOES NOT remove any content beforehand (doesn't clear events or call unrenderDates), unlike View
  2788. removeElement: function() {
  2789. this.unbindGlobalHandlers();
  2790. this.clearDragListeners();
  2791. this.el.remove();
  2792. // NOTE: we don't null-out this.el for the same reasons we don't do it within View::removeElement
  2793. },
  2794. // Renders the basic structure of grid view before any content is rendered
  2795. renderSkeleton: function() {
  2796. // subclasses should implement
  2797. },
  2798. // Renders the grid's date-related content (like areas that represent days/times).
  2799. // Assumes setRange has already been called and the skeleton has already been rendered.
  2800. renderDates: function() {
  2801. // subclasses should implement
  2802. },
  2803. // Unrenders the grid's date-related content
  2804. unrenderDates: function() {
  2805. // subclasses should implement
  2806. },
  2807. /* Handlers
  2808. ------------------------------------------------------------------------------------------------------------------*/
  2809. // Binds DOM handlers to elements that reside outside the grid, such as the document
  2810. bindGlobalHandlers: function() {
  2811. this.listenTo($(document), {
  2812. dragstart: this.externalDragStart, // jqui
  2813. sortstart: this.externalDragStart // jqui
  2814. });
  2815. },
  2816. // Unbinds DOM handlers from elements that reside outside the grid
  2817. unbindGlobalHandlers: function() {
  2818. this.stopListeningTo($(document));
  2819. },
  2820. // Process a mousedown on an element that represents a day. For day clicking and selecting.
  2821. dayMousedown: function(ev) {
  2822. if (!this.isIgnoringMouse) {
  2823. this.dayDragListener.startInteraction(ev, {
  2824. //distance: 5, // needs more work if we want dayClick to fire correctly
  2825. });
  2826. }
  2827. },
  2828. dayTouchStart: function(ev) {
  2829. var view = this.view;
  2830. // HACK to prevent a user's clickaway for unselecting a range or an event
  2831. // from causing a dayClick.
  2832. if (view.isSelected || view.selectedEvent) {
  2833. this.tempIgnoreMouse();
  2834. }
  2835. this.dayDragListener.startInteraction(ev, {
  2836. delay: this.view.opt('longPressDelay')
  2837. });
  2838. },
  2839. // Creates a listener that tracks the user's drag across day elements.
  2840. // For day clicking and selecting.
  2841. buildDayDragListener: function() {
  2842. var _this = this;
  2843. var view = this.view;
  2844. var isSelectable = view.opt('selectable');
  2845. var dayClickHit; // null if invalid dayClick
  2846. var selectionSpan; // null if invalid selection
  2847. // this listener tracks a mousedown on a day element, and a subsequent drag.
  2848. // if the drag ends on the same day, it is a 'dayClick'.
  2849. // if 'selectable' is enabled, this listener also detects selections.
  2850. var dragListener = new HitDragListener(this, {
  2851. scroll: view.opt('dragScroll'),
  2852. interactionStart: function() {
  2853. dayClickHit = dragListener.origHit; // for dayClick, where no dragging happens
  2854. selectionSpan = null;
  2855. },
  2856. dragStart: function() {
  2857. view.unselect(); // since we could be rendering a new selection, we want to clear any old one
  2858. },
  2859. hitOver: function(hit, isOrig, origHit) {
  2860. if (origHit) { // click needs to have started on a hit
  2861. // if user dragged to another cell at any point, it can no longer be a dayClick
  2862. if (!isOrig) {
  2863. dayClickHit = null;
  2864. }
  2865. if (isSelectable) {
  2866. selectionSpan = _this.computeSelection(
  2867. _this.getHitSpan(origHit),
  2868. _this.getHitSpan(hit)
  2869. );
  2870. if (selectionSpan) {
  2871. _this.renderSelection(selectionSpan);
  2872. }
  2873. else if (selectionSpan === false) {
  2874. disableCursor();
  2875. }
  2876. }
  2877. }
  2878. },
  2879. hitOut: function() { // called before mouse moves to a different hit OR moved out of all hits
  2880. dayClickHit = null;
  2881. selectionSpan = null;
  2882. _this.unrenderSelection();
  2883. },
  2884. hitDone: function() { // called after a hitOut OR before a dragEnd
  2885. enableCursor();
  2886. },
  2887. interactionEnd: function(ev, isCancelled) {
  2888. if (!isCancelled) {
  2889. if (
  2890. dayClickHit &&
  2891. !_this.isIgnoringMouse // see hack in dayTouchStart
  2892. ) {
  2893. view.triggerDayClick(
  2894. _this.getHitSpan(dayClickHit),
  2895. _this.getHitEl(dayClickHit),
  2896. ev
  2897. );
  2898. }
  2899. if (selectionSpan) {
  2900. // the selection will already have been rendered. just report it
  2901. view.reportSelection(selectionSpan, ev);
  2902. }
  2903. }
  2904. }
  2905. });
  2906. return dragListener;
  2907. },
  2908. // Kills all in-progress dragging.
  2909. // Useful for when public API methods that result in re-rendering are invoked during a drag.
  2910. // Also useful for when touch devices misbehave and don't fire their touchend.
  2911. clearDragListeners: function() {
  2912. this.dayDragListener.endInteraction();
  2913. if (this.segDragListener) {
  2914. this.segDragListener.endInteraction(); // will clear this.segDragListener
  2915. }
  2916. if (this.segResizeListener) {
  2917. this.segResizeListener.endInteraction(); // will clear this.segResizeListener
  2918. }
  2919. if (this.externalDragListener) {
  2920. this.externalDragListener.endInteraction(); // will clear this.externalDragListener
  2921. }
  2922. },
  2923. /* Event Helper
  2924. ------------------------------------------------------------------------------------------------------------------*/
  2925. // TODO: should probably move this to Grid.events, like we did event dragging / resizing
  2926. // Renders a mock event at the given event location, which contains zoned start/end properties.
  2927. // Returns all mock event elements.
  2928. renderEventLocationHelper: function(eventLocation, sourceSeg) {
  2929. var fakeEvent = this.fabricateHelperEvent(eventLocation, sourceSeg);
  2930. return this.renderHelper(fakeEvent, sourceSeg); // do the actual rendering
  2931. },
  2932. // Builds a fake event given zoned event date properties and a segment is should be inspired from.
  2933. // The range's end can be null, in which case the mock event that is rendered will have a null end time.
  2934. // `sourceSeg` is the internal segment object involved in the drag. If null, something external is dragging.
  2935. fabricateHelperEvent: function(eventLocation, sourceSeg) {
  2936. var fakeEvent = sourceSeg ? createObject(sourceSeg.event) : {}; // mask the original event object if possible
  2937. fakeEvent.start = eventLocation.start.clone();
  2938. fakeEvent.end = eventLocation.end ? eventLocation.end.clone() : null;
  2939. fakeEvent.allDay = null; // force it to be freshly computed by normalizeEventDates
  2940. this.view.calendar.normalizeEventDates(fakeEvent);
  2941. // this extra className will be useful for differentiating real events from mock events in CSS
  2942. fakeEvent.className = (fakeEvent.className || []).concat('fc-helper');
  2943. // if something external is being dragged in, don't render a resizer
  2944. if (!sourceSeg) {
  2945. fakeEvent.editable = false;
  2946. }
  2947. return fakeEvent;
  2948. },
  2949. // Renders a mock event. Given zoned event date properties.
  2950. // Must return all mock event elements.
  2951. renderHelper: function(eventLocation, sourceSeg) {
  2952. // subclasses must implement
  2953. },
  2954. // Unrenders a mock event
  2955. unrenderHelper: function() {
  2956. // subclasses must implement
  2957. },
  2958. /* Selection
  2959. ------------------------------------------------------------------------------------------------------------------*/
  2960. // Renders a visual indication of a selection. Will highlight by default but can be overridden by subclasses.
  2961. // Given a span (unzoned start/end and other misc data)
  2962. renderSelection: function(span) {
  2963. this.renderHighlight(span);
  2964. },
  2965. // Unrenders any visual indications of a selection. Will unrender a highlight by default.
  2966. unrenderSelection: function() {
  2967. this.unrenderHighlight();
  2968. },
  2969. // Given the first and last date-spans of a selection, returns another date-span object.
  2970. // Subclasses can override and provide additional data in the span object. Will be passed to renderSelection().
  2971. // Will return false if the selection is invalid and this should be indicated to the user.
  2972. // Will return null/undefined if a selection invalid but no error should be reported.
  2973. computeSelection: function(span0, span1) {
  2974. var span = this.computeSelectionSpan(span0, span1);
  2975. if (span && !this.view.calendar.isSelectionSpanAllowed(span)) {
  2976. return false;
  2977. }
  2978. return span;
  2979. },
  2980. // Given two spans, must return the combination of the two.
  2981. // TODO: do this separation of concerns (combining VS validation) for event dnd/resize too.
  2982. computeSelectionSpan: function(span0, span1) {
  2983. var dates = [ span0.start, span0.end, span1.start, span1.end ];
  2984. dates.sort(compareNumbers); // sorts chronologically. works with Moments
  2985. return { start: dates[0].clone(), end: dates[3].clone() };
  2986. },
  2987. /* Highlight
  2988. ------------------------------------------------------------------------------------------------------------------*/
  2989. // Renders an emphasis on the given date range. Given a span (unzoned start/end and other misc data)
  2990. renderHighlight: function(span) {
  2991. this.renderFill('highlight', this.spanToSegs(span));
  2992. },
  2993. // Unrenders the emphasis on a date range
  2994. unrenderHighlight: function() {
  2995. this.unrenderFill('highlight');
  2996. },
  2997. // Generates an array of classNames for rendering the highlight. Used by the fill system.
  2998. highlightSegClasses: function() {
  2999. return [ 'fc-highlight' ];
  3000. },
  3001. /* Business Hours
  3002. ------------------------------------------------------------------------------------------------------------------*/
  3003. renderBusinessHours: function() {
  3004. },
  3005. unrenderBusinessHours: function() {
  3006. },
  3007. /* Now Indicator
  3008. ------------------------------------------------------------------------------------------------------------------*/
  3009. getNowIndicatorUnit: function() {
  3010. },
  3011. renderNowIndicator: function(date) {
  3012. },
  3013. unrenderNowIndicator: function() {
  3014. },
  3015. /* Fill System (highlight, background events, business hours)
  3016. --------------------------------------------------------------------------------------------------------------------
  3017. TODO: remove this system. like we did in TimeGrid
  3018. */
  3019. // Renders a set of rectangles over the given segments of time.
  3020. // MUST RETURN a subset of segs, the segs that were actually rendered.
  3021. // Responsible for populating this.elsByFill. TODO: better API for expressing this requirement
  3022. renderFill: function(type, segs) {
  3023. // subclasses must implement
  3024. },
  3025. // Unrenders a specific type of fill that is currently rendered on the grid
  3026. unrenderFill: function(type) {
  3027. var el = this.elsByFill[type];
  3028. if (el) {
  3029. el.remove();
  3030. delete this.elsByFill[type];
  3031. }
  3032. },
  3033. // Renders and assigns an `el` property for each fill segment. Generic enough to work with different types.
  3034. // Only returns segments that successfully rendered.
  3035. // To be harnessed by renderFill (implemented by subclasses).
  3036. // Analagous to renderFgSegEls.
  3037. renderFillSegEls: function(type, segs) {
  3038. var _this = this;
  3039. var segElMethod = this[type + 'SegEl'];
  3040. var html = '';
  3041. var renderedSegs = [];
  3042. var i;
  3043. if (segs.length) {
  3044. // build a large concatenation of segment HTML
  3045. for (i = 0; i < segs.length; i++) {
  3046. html += this.fillSegHtml(type, segs[i]);
  3047. }
  3048. // Grab individual elements from the combined HTML string. Use each as the default rendering.
  3049. // Then, compute the 'el' for each segment.
  3050. $(html).each(function(i, node) {
  3051. var seg = segs[i];
  3052. var el = $(node);
  3053. // allow custom filter methods per-type
  3054. if (segElMethod) {
  3055. el = segElMethod.call(_this, seg, el);
  3056. }
  3057. if (el) { // custom filters did not cancel the render
  3058. el = $(el); // allow custom filter to return raw DOM node
  3059. // correct element type? (would be bad if a non-TD were inserted into a table for example)
  3060. if (el.is(_this.fillSegTag)) {
  3061. seg.el = el;
  3062. renderedSegs.push(seg);
  3063. }
  3064. }
  3065. });
  3066. }
  3067. return renderedSegs;
  3068. },
  3069. fillSegTag: 'div', // subclasses can override
  3070. // Builds the HTML needed for one fill segment. Generic enough to work with different types.
  3071. fillSegHtml: function(type, seg) {
  3072. // custom hooks per-type
  3073. var classesMethod = this[type + 'SegClasses'];
  3074. var cssMethod = this[type + 'SegCss'];
  3075. var classes = classesMethod ? classesMethod.call(this, seg) : [];
  3076. var css = cssToStr(cssMethod ? cssMethod.call(this, seg) : {});
  3077. return '<' + this.fillSegTag +
  3078. (classes.length ? ' class="' + classes.join(' ') + '"' : '') +
  3079. (css ? ' style="' + css + '"' : '') +
  3080. ' />';
  3081. },
  3082. /* Generic rendering utilities for subclasses
  3083. ------------------------------------------------------------------------------------------------------------------*/
  3084. // Computes HTML classNames for a single-day element
  3085. getDayClasses: function(date) {
  3086. var view = this.view;
  3087. var today = view.calendar.getNow();
  3088. var classes = [ 'fc-' + dayIDs[date.day()] ];
  3089. if (
  3090. view.intervalDuration.as('months') == 1 &&
  3091. date.month() != view.intervalStart.month()
  3092. ) {
  3093. classes.push('fc-other-month');
  3094. }
  3095. if (date.isSame(today, 'day')) {
  3096. classes.push(
  3097. 'fc-today',
  3098. view.highlightStateClass
  3099. );
  3100. }
  3101. else if (date < today) {
  3102. classes.push('fc-past');
  3103. }
  3104. else {
  3105. classes.push('fc-future');
  3106. }
  3107. return classes;
  3108. }
  3109. });
  3110. ;;
  3111. /* Event-rendering and event-interaction methods for the abstract Grid class
  3112. ----------------------------------------------------------------------------------------------------------------------*/
  3113. Grid.mixin({
  3114. mousedOverSeg: null, // the segment object the user's mouse is over. null if over nothing
  3115. isDraggingSeg: false, // is a segment being dragged? boolean
  3116. isResizingSeg: false, // is a segment being resized? boolean
  3117. isDraggingExternal: false, // jqui-dragging an external element? boolean
  3118. segs: null, // the *event* segments currently rendered in the grid. TODO: rename to `eventSegs`
  3119. // Renders the given events onto the grid
  3120. renderEvents: function(events) {
  3121. var bgEvents = [];
  3122. var fgEvents = [];
  3123. var i;
  3124. for (i = 0; i < events.length; i++) {
  3125. (isBgEvent(events[i]) ? bgEvents : fgEvents).push(events[i]);
  3126. }
  3127. this.segs = [].concat( // record all segs
  3128. this.renderBgEvents(bgEvents),
  3129. this.renderFgEvents(fgEvents)
  3130. );
  3131. },
  3132. renderBgEvents: function(events) {
  3133. var segs = this.eventsToSegs(events);
  3134. // renderBgSegs might return a subset of segs, segs that were actually rendered
  3135. return this.renderBgSegs(segs) || segs;
  3136. },
  3137. renderFgEvents: function(events) {
  3138. var segs = this.eventsToSegs(events);
  3139. // renderFgSegs might return a subset of segs, segs that were actually rendered
  3140. return this.renderFgSegs(segs) || segs;
  3141. },
  3142. // Unrenders all events currently rendered on the grid
  3143. unrenderEvents: function() {
  3144. this.handleSegMouseout(); // trigger an eventMouseout if user's mouse is over an event
  3145. this.clearDragListeners();
  3146. this.unrenderFgSegs();
  3147. this.unrenderBgSegs();
  3148. this.segs = null;
  3149. },
  3150. // Retrieves all rendered segment objects currently rendered on the grid
  3151. getEventSegs: function() {
  3152. return this.segs || [];
  3153. },
  3154. /* Foreground Segment Rendering
  3155. ------------------------------------------------------------------------------------------------------------------*/
  3156. // Renders foreground event segments onto the grid. May return a subset of segs that were rendered.
  3157. renderFgSegs: function(segs) {
  3158. // subclasses must implement
  3159. },
  3160. // Unrenders all currently rendered foreground segments
  3161. unrenderFgSegs: function() {
  3162. // subclasses must implement
  3163. },
  3164. // Renders and assigns an `el` property for each foreground event segment.
  3165. // Only returns segments that successfully rendered.
  3166. // A utility that subclasses may use.
  3167. renderFgSegEls: function(segs, disableResizing) {
  3168. var view = this.view;
  3169. var html = '';
  3170. var renderedSegs = [];
  3171. var i;
  3172. if (segs.length) { // don't build an empty html string
  3173. // build a large concatenation of event segment HTML
  3174. for (i = 0; i < segs.length; i++) {
  3175. html += this.fgSegHtml(segs[i], disableResizing);
  3176. }
  3177. // Grab individual elements from the combined HTML string. Use each as the default rendering.
  3178. // Then, compute the 'el' for each segment. An el might be null if the eventRender callback returned false.
  3179. $(html).each(function(i, node) {
  3180. var seg = segs[i];
  3181. var el = view.resolveEventEl(seg.event, $(node));
  3182. if (el) {
  3183. el.data('fc-seg', seg); // used by handlers
  3184. seg.el = el;
  3185. renderedSegs.push(seg);
  3186. }
  3187. });
  3188. }
  3189. return renderedSegs;
  3190. },
  3191. // Generates the HTML for the default rendering of a foreground event segment. Used by renderFgSegEls()
  3192. fgSegHtml: function(seg, disableResizing) {
  3193. // subclasses should implement
  3194. },
  3195. /* Background Segment Rendering
  3196. ------------------------------------------------------------------------------------------------------------------*/
  3197. // Renders the given background event segments onto the grid.
  3198. // Returns a subset of the segs that were actually rendered.
  3199. renderBgSegs: function(segs) {
  3200. return this.renderFill('bgEvent', segs);
  3201. },
  3202. // Unrenders all the currently rendered background event segments
  3203. unrenderBgSegs: function() {
  3204. this.unrenderFill('bgEvent');
  3205. },
  3206. // Renders a background event element, given the default rendering. Called by the fill system.
  3207. bgEventSegEl: function(seg, el) {
  3208. return this.view.resolveEventEl(seg.event, el); // will filter through eventRender
  3209. },
  3210. // Generates an array of classNames to be used for the default rendering of a background event.
  3211. // Called by fillSegHtml.
  3212. bgEventSegClasses: function(seg) {
  3213. var event = seg.event;
  3214. var source = event.source || {};
  3215. return [ 'fc-bgevent' ].concat(
  3216. event.className,
  3217. source.className || []
  3218. );
  3219. },
  3220. // Generates a semicolon-separated CSS string to be used for the default rendering of a background event.
  3221. // Called by fillSegHtml.
  3222. bgEventSegCss: function(seg) {
  3223. return {
  3224. 'background-color': this.getSegSkinCss(seg)['background-color']
  3225. };
  3226. },
  3227. // Generates an array of classNames to be used for the rendering business hours overlay. Called by the fill system.
  3228. // Called by fillSegHtml.
  3229. businessHoursSegClasses: function(seg) {
  3230. return [ 'fc-nonbusiness', 'fc-bgevent' ];
  3231. },
  3232. /* Business Hours
  3233. ------------------------------------------------------------------------------------------------------------------*/
  3234. // Compute business hour segs for the grid's current date range.
  3235. // Caller must ask if whole-day business hours are needed.
  3236. buildBusinessHourSegs: function(wholeDay) {
  3237. var events = this.view.calendar.getCurrentBusinessHourEvents(wholeDay);
  3238. // HACK. Eventually refactor business hours "events" system.
  3239. // If no events are given, but businessHours is activated, this means the entire visible range should be
  3240. // marked as *not* business-hours, via inverse-background rendering.
  3241. if (
  3242. !events.length &&
  3243. this.view.calendar.options.businessHours // don't access view option. doesn't update with dynamic options
  3244. ) {
  3245. events = [
  3246. $.extend({}, BUSINESS_HOUR_EVENT_DEFAULTS, {
  3247. start: this.view.end, // guaranteed out-of-range
  3248. end: this.view.end, // "
  3249. dow: null
  3250. })
  3251. ];
  3252. }
  3253. return this.eventsToSegs(events);
  3254. },
  3255. /* Handlers
  3256. ------------------------------------------------------------------------------------------------------------------*/
  3257. // Attaches event-element-related handlers for *all* rendered event segments of the view.
  3258. bindSegHandlers: function() {
  3259. this.bindSegHandlersToEl(this.el);
  3260. },
  3261. // Attaches event-element-related handlers to an arbitrary container element. leverages bubbling.
  3262. bindSegHandlersToEl: function(el) {
  3263. this.bindSegHandlerToEl(el, 'touchstart', this.handleSegTouchStart);
  3264. this.bindSegHandlerToEl(el, 'touchend', this.handleSegTouchEnd);
  3265. this.bindSegHandlerToEl(el, 'mouseenter', this.handleSegMouseover);
  3266. this.bindSegHandlerToEl(el, 'mouseleave', this.handleSegMouseout);
  3267. this.bindSegHandlerToEl(el, 'mousedown', this.handleSegMousedown);
  3268. this.bindSegHandlerToEl(el, 'click', this.handleSegClick);
  3269. },
  3270. // Executes a handler for any a user-interaction on a segment.
  3271. // Handler gets called with (seg, ev), and with the `this` context of the Grid
  3272. bindSegHandlerToEl: function(el, name, handler) {
  3273. var _this = this;
  3274. el.on(name, '.fc-event-container > *', function(ev) {
  3275. var seg = $(this).data('fc-seg'); // grab segment data. put there by View::renderEvents
  3276. // only call the handlers if there is not a drag/resize in progress
  3277. if (seg && !_this.isDraggingSeg && !_this.isResizingSeg) {
  3278. return handler.call(_this, seg, ev); // context will be the Grid
  3279. }
  3280. });
  3281. },
  3282. handleSegClick: function(seg, ev) {
  3283. return this.view.trigger('eventClick', seg.el[0], seg.event, ev); // can return `false` to cancel
  3284. },
  3285. // Updates internal state and triggers handlers for when an event element is moused over
  3286. handleSegMouseover: function(seg, ev) {
  3287. if (
  3288. !this.isIgnoringMouse &&
  3289. !this.mousedOverSeg
  3290. ) {
  3291. this.mousedOverSeg = seg;
  3292. seg.el.addClass('fc-allow-mouse-resize');
  3293. this.view.trigger('eventMouseover', seg.el[0], seg.event, ev);
  3294. }
  3295. },
  3296. // Updates internal state and triggers handlers for when an event element is moused out.
  3297. // Can be given no arguments, in which case it will mouseout the segment that was previously moused over.
  3298. handleSegMouseout: function(seg, ev) {
  3299. ev = ev || {}; // if given no args, make a mock mouse event
  3300. if (this.mousedOverSeg) {
  3301. seg = seg || this.mousedOverSeg; // if given no args, use the currently moused-over segment
  3302. this.mousedOverSeg = null;
  3303. seg.el.removeClass('fc-allow-mouse-resize');
  3304. this.view.trigger('eventMouseout', seg.el[0], seg.event, ev);
  3305. }
  3306. },
  3307. handleSegMousedown: function(seg, ev) {
  3308. var isResizing = this.startSegResize(seg, ev, { distance: 5 });
  3309. if (!isResizing && this.view.isEventDraggable(seg.event)) {
  3310. this.buildSegDragListener(seg)
  3311. .startInteraction(ev, {
  3312. distance: 5
  3313. });
  3314. }
  3315. },
  3316. handleSegTouchStart: function(seg, ev) {
  3317. var view = this.view;
  3318. var event = seg.event;
  3319. var isSelected = view.isEventSelected(event);
  3320. var isDraggable = view.isEventDraggable(event);
  3321. var isResizable = view.isEventResizable(event);
  3322. var isResizing = false;
  3323. var dragListener;
  3324. if (isSelected && isResizable) {
  3325. // only allow resizing of the event is selected
  3326. isResizing = this.startSegResize(seg, ev);
  3327. }
  3328. if (!isResizing && (isDraggable || isResizable)) { // allowed to be selected?
  3329. dragListener = isDraggable ?
  3330. this.buildSegDragListener(seg) :
  3331. this.buildSegSelectListener(seg); // seg isn't draggable, but still needs to be selected
  3332. dragListener.startInteraction(ev, { // won't start if already started
  3333. delay: isSelected ? 0 : this.view.opt('longPressDelay') // do delay if not already selected
  3334. });
  3335. }
  3336. // a long tap simulates a mouseover. ignore this bogus mouseover.
  3337. this.tempIgnoreMouse();
  3338. },
  3339. handleSegTouchEnd: function(seg, ev) {
  3340. // touchstart+touchend = click, which simulates a mouseover.
  3341. // ignore this bogus mouseover.
  3342. this.tempIgnoreMouse();
  3343. },
  3344. // returns boolean whether resizing actually started or not.
  3345. // assumes the seg allows resizing.
  3346. // `dragOptions` are optional.
  3347. startSegResize: function(seg, ev, dragOptions) {
  3348. if ($(ev.target).is('.fc-resizer')) {
  3349. this.buildSegResizeListener(seg, $(ev.target).is('.fc-start-resizer'))
  3350. .startInteraction(ev, dragOptions);
  3351. return true;
  3352. }
  3353. return false;
  3354. },
  3355. /* Event Dragging
  3356. ------------------------------------------------------------------------------------------------------------------*/
  3357. // Builds a listener that will track user-dragging on an event segment.
  3358. // Generic enough to work with any type of Grid.
  3359. // Has side effect of setting/unsetting `segDragListener`
  3360. buildSegDragListener: function(seg) {
  3361. var _this = this;
  3362. var view = this.view;
  3363. var calendar = view.calendar;
  3364. var el = seg.el;
  3365. var event = seg.event;
  3366. var isDragging;
  3367. var mouseFollower; // A clone of the original element that will move with the mouse
  3368. var dropLocation; // zoned event date properties
  3369. if (this.segDragListener) {
  3370. return this.segDragListener;
  3371. }
  3372. // Tracks mouse movement over the *view's* coordinate map. Allows dragging and dropping between subcomponents
  3373. // of the view.
  3374. var dragListener = this.segDragListener = new HitDragListener(view, {
  3375. scroll: view.opt('dragScroll'),
  3376. subjectEl: el,
  3377. subjectCenter: true,
  3378. interactionStart: function(ev) {
  3379. seg.component = _this; // for renderDrag
  3380. isDragging = false;
  3381. mouseFollower = new MouseFollower(seg.el, {
  3382. additionalClass: 'fc-dragging',
  3383. parentEl: view.el,
  3384. opacity: dragListener.isTouch ? null : view.opt('dragOpacity'),
  3385. revertDuration: view.opt('dragRevertDuration'),
  3386. zIndex: 2 // one above the .fc-view
  3387. });
  3388. mouseFollower.hide(); // don't show until we know this is a real drag
  3389. mouseFollower.start(ev);
  3390. },
  3391. dragStart: function(ev) {
  3392. if (dragListener.isTouch && !view.isEventSelected(event)) {
  3393. // if not previously selected, will fire after a delay. then, select the event
  3394. view.selectEvent(event);
  3395. }
  3396. isDragging = true;
  3397. _this.handleSegMouseout(seg, ev); // ensure a mouseout on the manipulated event has been reported
  3398. _this.segDragStart(seg, ev);
  3399. view.hideEvent(event); // hide all event segments. our mouseFollower will take over
  3400. },
  3401. hitOver: function(hit, isOrig, origHit) {
  3402. var dragHelperEls;
  3403. // starting hit could be forced (DayGrid.limit)
  3404. if (seg.hit) {
  3405. origHit = seg.hit;
  3406. }
  3407. // since we are querying the parent view, might not belong to this grid
  3408. dropLocation = _this.computeEventDrop(
  3409. origHit.component.getHitSpan(origHit),
  3410. hit.component.getHitSpan(hit),
  3411. event
  3412. );
  3413. if (dropLocation && !calendar.isEventSpanAllowed(_this.eventToSpan(dropLocation), event)) {
  3414. disableCursor();
  3415. dropLocation = null;
  3416. }
  3417. // if a valid drop location, have the subclass render a visual indication
  3418. if (dropLocation && (dragHelperEls = view.renderDrag(dropLocation, seg))) {
  3419. dragHelperEls.addClass('fc-dragging');
  3420. if (!dragListener.isTouch) {
  3421. _this.applyDragOpacity(dragHelperEls);
  3422. }
  3423. mouseFollower.hide(); // if the subclass is already using a mock event "helper", hide our own
  3424. }
  3425. else {
  3426. mouseFollower.show(); // otherwise, have the helper follow the mouse (no snapping)
  3427. }
  3428. if (isOrig) {
  3429. dropLocation = null; // needs to have moved hits to be a valid drop
  3430. }
  3431. },
  3432. hitOut: function() { // called before mouse moves to a different hit OR moved out of all hits
  3433. view.unrenderDrag(); // unrender whatever was done in renderDrag
  3434. mouseFollower.show(); // show in case we are moving out of all hits
  3435. dropLocation = null;
  3436. },
  3437. hitDone: function() { // Called after a hitOut OR before a dragEnd
  3438. enableCursor();
  3439. },
  3440. interactionEnd: function(ev) {
  3441. delete seg.component; // prevent side effects
  3442. // do revert animation if hasn't changed. calls a callback when finished (whether animation or not)
  3443. mouseFollower.stop(!dropLocation, function() {
  3444. if (isDragging) {
  3445. view.unrenderDrag();
  3446. view.showEvent(event);
  3447. _this.segDragStop(seg, ev);
  3448. }
  3449. if (dropLocation) {
  3450. view.reportEventDrop(event, dropLocation, this.largeUnit, el, ev);
  3451. }
  3452. });
  3453. _this.segDragListener = null;
  3454. }
  3455. });
  3456. return dragListener;
  3457. },
  3458. // seg isn't draggable, but let's use a generic DragListener
  3459. // simply for the delay, so it can be selected.
  3460. // Has side effect of setting/unsetting `segDragListener`
  3461. buildSegSelectListener: function(seg) {
  3462. var _this = this;
  3463. var view = this.view;
  3464. var event = seg.event;
  3465. if (this.segDragListener) {
  3466. return this.segDragListener;
  3467. }
  3468. var dragListener = this.segDragListener = new DragListener({
  3469. dragStart: function(ev) {
  3470. if (dragListener.isTouch && !view.isEventSelected(event)) {
  3471. // if not previously selected, will fire after a delay. then, select the event
  3472. view.selectEvent(event);
  3473. }
  3474. },
  3475. interactionEnd: function(ev) {
  3476. _this.segDragListener = null;
  3477. }
  3478. });
  3479. return dragListener;
  3480. },
  3481. // Called before event segment dragging starts
  3482. segDragStart: function(seg, ev) {
  3483. this.isDraggingSeg = true;
  3484. this.view.trigger('eventDragStart', seg.el[0], seg.event, ev, {}); // last argument is jqui dummy
  3485. },
  3486. // Called after event segment dragging stops
  3487. segDragStop: function(seg, ev) {
  3488. this.isDraggingSeg = false;
  3489. this.view.trigger('eventDragStop', seg.el[0], seg.event, ev, {}); // last argument is jqui dummy
  3490. },
  3491. // Given the spans an event drag began, and the span event was dropped, calculates the new zoned start/end/allDay
  3492. // values for the event. Subclasses may override and set additional properties to be used by renderDrag.
  3493. // A falsy returned value indicates an invalid drop.
  3494. // DOES NOT consider overlap/constraint.
  3495. computeEventDrop: function(startSpan, endSpan, event) {
  3496. var calendar = this.view.calendar;
  3497. var dragStart = startSpan.start;
  3498. var dragEnd = endSpan.start;
  3499. var delta;
  3500. var dropLocation; // zoned event date properties
  3501. if (dragStart.hasTime() === dragEnd.hasTime()) {
  3502. delta = this.diffDates(dragEnd, dragStart);
  3503. // if an all-day event was in a timed area and it was dragged to a different time,
  3504. // guarantee an end and adjust start/end to have times
  3505. if (event.allDay && durationHasTime(delta)) {
  3506. dropLocation = {
  3507. start: event.start.clone(),
  3508. end: calendar.getEventEnd(event), // will be an ambig day
  3509. allDay: false // for normalizeEventTimes
  3510. };
  3511. calendar.normalizeEventTimes(dropLocation);
  3512. }
  3513. // othewise, work off existing values
  3514. else {
  3515. dropLocation = {
  3516. start: event.start.clone(),
  3517. end: event.end ? event.end.clone() : null,
  3518. allDay: event.allDay // keep it the same
  3519. };
  3520. }
  3521. dropLocation.start.add(delta);
  3522. if (dropLocation.end) {
  3523. dropLocation.end.add(delta);
  3524. }
  3525. }
  3526. else {
  3527. // if switching from day <-> timed, start should be reset to the dropped date, and the end cleared
  3528. dropLocation = {
  3529. start: dragEnd.clone(),
  3530. end: null, // end should be cleared
  3531. allDay: !dragEnd.hasTime()
  3532. };
  3533. }
  3534. return dropLocation;
  3535. },
  3536. // Utility for apply dragOpacity to a jQuery set
  3537. applyDragOpacity: function(els) {
  3538. var opacity = this.view.opt('dragOpacity');
  3539. if (opacity != null) {
  3540. els.each(function(i, node) {
  3541. // Don't use jQuery (will set an IE filter), do it the old fashioned way.
  3542. // In IE8, a helper element will disappears if there's a filter.
  3543. node.style.opacity = opacity;
  3544. });
  3545. }
  3546. },
  3547. /* External Element Dragging
  3548. ------------------------------------------------------------------------------------------------------------------*/
  3549. // Called when a jQuery UI drag is initiated anywhere in the DOM
  3550. externalDragStart: function(ev, ui) {
  3551. var view = this.view;
  3552. var el;
  3553. var accept;
  3554. if (view.opt('droppable')) { // only listen if this setting is on
  3555. el = $((ui ? ui.item : null) || ev.target);
  3556. // Test that the dragged element passes the dropAccept selector or filter function.
  3557. // FYI, the default is "*" (matches all)
  3558. accept = view.opt('dropAccept');
  3559. if ($.isFunction(accept) ? accept.call(el[0], el) : el.is(accept)) {
  3560. if (!this.isDraggingExternal) { // prevent double-listening if fired twice
  3561. this.listenToExternalDrag(el, ev, ui);
  3562. }
  3563. }
  3564. }
  3565. },
  3566. // Called when a jQuery UI drag starts and it needs to be monitored for dropping
  3567. listenToExternalDrag: function(el, ev, ui) {
  3568. var _this = this;
  3569. var calendar = this.view.calendar;
  3570. var meta = getDraggedElMeta(el); // extra data about event drop, including possible event to create
  3571. var dropLocation; // a null value signals an unsuccessful drag
  3572. // listener that tracks mouse movement over date-associated pixel regions
  3573. var dragListener = _this.externalDragListener = new HitDragListener(this, {
  3574. interactionStart: function() {
  3575. _this.isDraggingExternal = true;
  3576. },
  3577. hitOver: function(hit) {
  3578. dropLocation = _this.computeExternalDrop(
  3579. hit.component.getHitSpan(hit), // since we are querying the parent view, might not belong to this grid
  3580. meta
  3581. );
  3582. if ( // invalid hit?
  3583. dropLocation &&
  3584. !calendar.isExternalSpanAllowed(_this.eventToSpan(dropLocation), dropLocation, meta.eventProps)
  3585. ) {
  3586. disableCursor();
  3587. dropLocation = null;
  3588. }
  3589. if (dropLocation) {
  3590. _this.renderDrag(dropLocation); // called without a seg parameter
  3591. }
  3592. },
  3593. hitOut: function() {
  3594. dropLocation = null; // signal unsuccessful
  3595. },
  3596. hitDone: function() { // Called after a hitOut OR before a dragEnd
  3597. enableCursor();
  3598. _this.unrenderDrag();
  3599. },
  3600. interactionEnd: function(ev) {
  3601. if (dropLocation) { // element was dropped on a valid hit
  3602. _this.view.reportExternalDrop(meta, dropLocation, el, ev, ui);
  3603. }
  3604. _this.isDraggingExternal = false;
  3605. _this.externalDragListener = null;
  3606. }
  3607. });
  3608. dragListener.startDrag(ev); // start listening immediately
  3609. },
  3610. // Given a hit to be dropped upon, and misc data associated with the jqui drag (guaranteed to be a plain object),
  3611. // returns the zoned start/end dates for the event that would result from the hypothetical drop. end might be null.
  3612. // Returning a null value signals an invalid drop hit.
  3613. // DOES NOT consider overlap/constraint.
  3614. computeExternalDrop: function(span, meta) {
  3615. var calendar = this.view.calendar;
  3616. var dropLocation = {
  3617. start: calendar.applyTimezone(span.start), // simulate a zoned event start date
  3618. end: null
  3619. };
  3620. // if dropped on an all-day span, and element's metadata specified a time, set it
  3621. if (meta.startTime && !dropLocation.start.hasTime()) {
  3622. dropLocation.start.time(meta.startTime);
  3623. }
  3624. if (meta.duration) {
  3625. dropLocation.end = dropLocation.start.clone().add(meta.duration);
  3626. }
  3627. return dropLocation;
  3628. },
  3629. /* Drag Rendering (for both events and an external elements)
  3630. ------------------------------------------------------------------------------------------------------------------*/
  3631. // Renders a visual indication of an event or external element being dragged.
  3632. // `dropLocation` contains hypothetical start/end/allDay values the event would have if dropped. end can be null.
  3633. // `seg` is the internal segment object that is being dragged. If dragging an external element, `seg` is null.
  3634. // A truthy returned value indicates this method has rendered a helper element.
  3635. // Must return elements used for any mock events.
  3636. renderDrag: function(dropLocation, seg) {
  3637. // subclasses must implement
  3638. },
  3639. // Unrenders a visual indication of an event or external element being dragged
  3640. unrenderDrag: function() {
  3641. // subclasses must implement
  3642. },
  3643. /* Resizing
  3644. ------------------------------------------------------------------------------------------------------------------*/
  3645. // Creates a listener that tracks the user as they resize an event segment.
  3646. // Generic enough to work with any type of Grid.
  3647. buildSegResizeListener: function(seg, isStart) {
  3648. var _this = this;
  3649. var view = this.view;
  3650. var calendar = view.calendar;
  3651. var el = seg.el;
  3652. var event = seg.event;
  3653. var eventEnd = calendar.getEventEnd(event);
  3654. var isDragging;
  3655. var resizeLocation; // zoned event date properties. falsy if invalid resize
  3656. // Tracks mouse movement over the *grid's* coordinate map
  3657. var dragListener = this.segResizeListener = new HitDragListener(this, {
  3658. scroll: view.opt('dragScroll'),
  3659. subjectEl: el,
  3660. interactionStart: function() {
  3661. isDragging = false;
  3662. },
  3663. dragStart: function(ev) {
  3664. isDragging = true;
  3665. _this.handleSegMouseout(seg, ev); // ensure a mouseout on the manipulated event has been reported
  3666. _this.segResizeStart(seg, ev);
  3667. },
  3668. hitOver: function(hit, isOrig, origHit) {
  3669. var origHitSpan = _this.getHitSpan(origHit);
  3670. var hitSpan = _this.getHitSpan(hit);
  3671. resizeLocation = isStart ?
  3672. _this.computeEventStartResize(origHitSpan, hitSpan, event) :
  3673. _this.computeEventEndResize(origHitSpan, hitSpan, event);
  3674. if (resizeLocation) {
  3675. if (!calendar.isEventSpanAllowed(_this.eventToSpan(resizeLocation), event)) {
  3676. disableCursor();
  3677. resizeLocation = null;
  3678. }
  3679. // no change? (TODO: how does this work with timezones?)
  3680. else if (resizeLocation.start.isSame(event.start) && resizeLocation.end.isSame(eventEnd)) {
  3681. resizeLocation = null;
  3682. }
  3683. }
  3684. if (resizeLocation) {
  3685. view.hideEvent(event);
  3686. _this.renderEventResize(resizeLocation, seg);
  3687. }
  3688. },
  3689. hitOut: function() { // called before mouse moves to a different hit OR moved out of all hits
  3690. resizeLocation = null;
  3691. },
  3692. hitDone: function() { // resets the rendering to show the original event
  3693. _this.unrenderEventResize();
  3694. view.showEvent(event);
  3695. enableCursor();
  3696. },
  3697. interactionEnd: function(ev) {
  3698. if (isDragging) {
  3699. _this.segResizeStop(seg, ev);
  3700. }
  3701. if (resizeLocation) { // valid date to resize to?
  3702. view.reportEventResize(event, resizeLocation, this.largeUnit, el, ev);
  3703. }
  3704. _this.segResizeListener = null;
  3705. }
  3706. });
  3707. return dragListener;
  3708. },
  3709. // Called before event segment resizing starts
  3710. segResizeStart: function(seg, ev) {
  3711. this.isResizingSeg = true;
  3712. this.view.trigger('eventResizeStart', seg.el[0], seg.event, ev, {}); // last argument is jqui dummy
  3713. },
  3714. // Called after event segment resizing stops
  3715. segResizeStop: function(seg, ev) {
  3716. this.isResizingSeg = false;
  3717. this.view.trigger('eventResizeStop', seg.el[0], seg.event, ev, {}); // last argument is jqui dummy
  3718. },
  3719. // Returns new date-information for an event segment being resized from its start
  3720. computeEventStartResize: function(startSpan, endSpan, event) {
  3721. return this.computeEventResize('start', startSpan, endSpan, event);
  3722. },
  3723. // Returns new date-information for an event segment being resized from its end
  3724. computeEventEndResize: function(startSpan, endSpan, event) {
  3725. return this.computeEventResize('end', startSpan, endSpan, event);
  3726. },
  3727. // Returns new zoned date information for an event segment being resized from its start OR end
  3728. // `type` is either 'start' or 'end'.
  3729. // DOES NOT consider overlap/constraint.
  3730. computeEventResize: function(type, startSpan, endSpan, event) {
  3731. var calendar = this.view.calendar;
  3732. var delta = this.diffDates(endSpan[type], startSpan[type]);
  3733. var resizeLocation; // zoned event date properties
  3734. var defaultDuration;
  3735. // build original values to work from, guaranteeing a start and end
  3736. resizeLocation = {
  3737. start: event.start.clone(),
  3738. end: calendar.getEventEnd(event),
  3739. allDay: event.allDay
  3740. };
  3741. // if an all-day event was in a timed area and was resized to a time, adjust start/end to have times
  3742. if (resizeLocation.allDay && durationHasTime(delta)) {
  3743. resizeLocation.allDay = false;
  3744. calendar.normalizeEventTimes(resizeLocation);
  3745. }
  3746. resizeLocation[type].add(delta); // apply delta to start or end
  3747. // if the event was compressed too small, find a new reasonable duration for it
  3748. if (!resizeLocation.start.isBefore(resizeLocation.end)) {
  3749. defaultDuration =
  3750. this.minResizeDuration || // TODO: hack
  3751. (event.allDay ?
  3752. calendar.defaultAllDayEventDuration :
  3753. calendar.defaultTimedEventDuration);
  3754. if (type == 'start') { // resizing the start?
  3755. resizeLocation.start = resizeLocation.end.clone().subtract(defaultDuration);
  3756. }
  3757. else { // resizing the end?
  3758. resizeLocation.end = resizeLocation.start.clone().add(defaultDuration);
  3759. }
  3760. }
  3761. return resizeLocation;
  3762. },
  3763. // Renders a visual indication of an event being resized.
  3764. // `range` has the updated dates of the event. `seg` is the original segment object involved in the drag.
  3765. // Must return elements used for any mock events.
  3766. renderEventResize: function(range, seg) {
  3767. // subclasses must implement
  3768. },
  3769. // Unrenders a visual indication of an event being resized.
  3770. unrenderEventResize: function() {
  3771. // subclasses must implement
  3772. },
  3773. /* Rendering Utils
  3774. ------------------------------------------------------------------------------------------------------------------*/
  3775. // Compute the text that should be displayed on an event's element.
  3776. // `range` can be the Event object itself, or something range-like, with at least a `start`.
  3777. // If event times are disabled, or the event has no time, will return a blank string.
  3778. // If not specified, formatStr will default to the eventTimeFormat setting,
  3779. // and displayEnd will default to the displayEventEnd setting.
  3780. getEventTimeText: function(range, formatStr, displayEnd) {
  3781. if (formatStr == null) {
  3782. formatStr = this.eventTimeFormat;
  3783. }
  3784. if (displayEnd == null) {
  3785. displayEnd = this.displayEventEnd;
  3786. }
  3787. if (this.displayEventTime && range.start.hasTime()) {
  3788. if (displayEnd && range.end) {
  3789. return this.view.formatRange(range, formatStr);
  3790. }
  3791. else {
  3792. return range.start.format(formatStr);
  3793. }
  3794. }
  3795. return '';
  3796. },
  3797. // Generic utility for generating the HTML classNames for an event segment's element
  3798. getSegClasses: function(seg, isDraggable, isResizable) {
  3799. var view = this.view;
  3800. var event = seg.event;
  3801. var classes = [
  3802. 'fc-event',
  3803. seg.isStart ? 'fc-start' : 'fc-not-start',
  3804. seg.isEnd ? 'fc-end' : 'fc-not-end'
  3805. ].concat(
  3806. event.className,
  3807. event.source ? event.source.className : []
  3808. );
  3809. if (isDraggable) {
  3810. classes.push('fc-draggable');
  3811. }
  3812. if (isResizable) {
  3813. classes.push('fc-resizable');
  3814. }
  3815. // event is currently selected? attach a className.
  3816. if (view.isEventSelected(event)) {
  3817. classes.push('fc-selected');
  3818. }
  3819. return classes;
  3820. },
  3821. // Utility for generating event skin-related CSS properties
  3822. getSegSkinCss: function(seg) {
  3823. var event = seg.event;
  3824. var view = this.view;
  3825. var source = event.source || {};
  3826. var eventColor = event.color;
  3827. var sourceColor = source.color;
  3828. var optionColor = view.opt('eventColor');
  3829. return {
  3830. 'background-color':
  3831. event.backgroundColor ||
  3832. eventColor ||
  3833. source.backgroundColor ||
  3834. sourceColor ||
  3835. view.opt('eventBackgroundColor') ||
  3836. optionColor,
  3837. 'border-color':
  3838. event.borderColor ||
  3839. eventColor ||
  3840. source.borderColor ||
  3841. sourceColor ||
  3842. view.opt('eventBorderColor') ||
  3843. optionColor,
  3844. color:
  3845. event.textColor ||
  3846. source.textColor ||
  3847. view.opt('eventTextColor')
  3848. };
  3849. },
  3850. /* Converting events -> eventRange -> eventSpan -> eventSegs
  3851. ------------------------------------------------------------------------------------------------------------------*/
  3852. // Generates an array of segments for the given single event
  3853. // Can accept an event "location" as well (which only has start/end and no allDay)
  3854. eventToSegs: function(event) {
  3855. return this.eventsToSegs([ event ]);
  3856. },
  3857. eventToSpan: function(event) {
  3858. return this.eventToSpans(event)[0];
  3859. },
  3860. // Generates spans (always unzoned) for the given event.
  3861. // Does not do any inverting for inverse-background events.
  3862. // Can accept an event "location" as well (which only has start/end and no allDay)
  3863. eventToSpans: function(event) {
  3864. var range = this.eventToRange(event);
  3865. return this.eventRangeToSpans(range, event);
  3866. },
  3867. // Converts an array of event objects into an array of event segment objects.
  3868. // A custom `segSliceFunc` may be given for arbitrarily slicing up events.
  3869. // Doesn't guarantee an order for the resulting array.
  3870. eventsToSegs: function(allEvents, segSliceFunc) {
  3871. var _this = this;
  3872. var eventsById = groupEventsById(allEvents);
  3873. var segs = [];
  3874. $.each(eventsById, function(id, events) {
  3875. var ranges = [];
  3876. var i;
  3877. for (i = 0; i < events.length; i++) {
  3878. ranges.push(_this.eventToRange(events[i]));
  3879. }
  3880. // inverse-background events (utilize only the first event in calculations)
  3881. if (isInverseBgEvent(events[0])) {
  3882. ranges = _this.invertRanges(ranges);
  3883. for (i = 0; i < ranges.length; i++) {
  3884. segs.push.apply(segs, // append to
  3885. _this.eventRangeToSegs(ranges[i], events[0], segSliceFunc));
  3886. }
  3887. }
  3888. // normal event ranges
  3889. else {
  3890. for (i = 0; i < ranges.length; i++) {
  3891. segs.push.apply(segs, // append to
  3892. _this.eventRangeToSegs(ranges[i], events[i], segSliceFunc));
  3893. }
  3894. }
  3895. });
  3896. return segs;
  3897. },
  3898. // Generates the unzoned start/end dates an event appears to occupy
  3899. // Can accept an event "location" as well (which only has start/end and no allDay)
  3900. eventToRange: function(event) {
  3901. return {
  3902. start: event.start.clone().stripZone(),
  3903. end: (
  3904. event.end ?
  3905. event.end.clone() :
  3906. // derive the end from the start and allDay. compute allDay if necessary
  3907. this.view.calendar.getDefaultEventEnd(
  3908. event.allDay != null ?
  3909. event.allDay :
  3910. !event.start.hasTime(),
  3911. event.start
  3912. )
  3913. ).stripZone()
  3914. };
  3915. },
  3916. // Given an event's range (unzoned start/end), and the event itself,
  3917. // slice into segments (using the segSliceFunc function if specified)
  3918. eventRangeToSegs: function(range, event, segSliceFunc) {
  3919. var spans = this.eventRangeToSpans(range, event);
  3920. var segs = [];
  3921. var i;
  3922. for (i = 0; i < spans.length; i++) {
  3923. segs.push.apply(segs, // append to
  3924. this.eventSpanToSegs(spans[i], event, segSliceFunc));
  3925. }
  3926. return segs;
  3927. },
  3928. // Given an event's unzoned date range, return an array of "span" objects.
  3929. // Subclasses can override.
  3930. eventRangeToSpans: function(range, event) {
  3931. return [ $.extend({}, range) ]; // copy into a single-item array
  3932. },
  3933. // Given an event's span (unzoned start/end and other misc data), and the event itself,
  3934. // slices into segments and attaches event-derived properties to them.
  3935. eventSpanToSegs: function(span, event, segSliceFunc) {
  3936. var segs = segSliceFunc ? segSliceFunc(span) : this.spanToSegs(span);
  3937. var i, seg;
  3938. for (i = 0; i < segs.length; i++) {
  3939. seg = segs[i];
  3940. seg.event = event;
  3941. seg.eventStartMS = +span.start; // TODO: not the best name after making spans unzoned
  3942. seg.eventDurationMS = span.end - span.start;
  3943. }
  3944. return segs;
  3945. },
  3946. // Produces a new array of range objects that will cover all the time NOT covered by the given ranges.
  3947. // SIDE EFFECT: will mutate the given array and will use its date references.
  3948. invertRanges: function(ranges) {
  3949. var view = this.view;
  3950. var viewStart = view.start.clone(); // need a copy
  3951. var viewEnd = view.end.clone(); // need a copy
  3952. var inverseRanges = [];
  3953. var start = viewStart; // the end of the previous range. the start of the new range
  3954. var i, range;
  3955. // ranges need to be in order. required for our date-walking algorithm
  3956. ranges.sort(compareRanges);
  3957. for (i = 0; i < ranges.length; i++) {
  3958. range = ranges[i];
  3959. // add the span of time before the event (if there is any)
  3960. if (range.start > start) { // compare millisecond time (skip any ambig logic)
  3961. inverseRanges.push({
  3962. start: start,
  3963. end: range.start
  3964. });
  3965. }
  3966. start = range.end;
  3967. }
  3968. // add the span of time after the last event (if there is any)
  3969. if (start < viewEnd) { // compare millisecond time (skip any ambig logic)
  3970. inverseRanges.push({
  3971. start: start,
  3972. end: viewEnd
  3973. });
  3974. }
  3975. return inverseRanges;
  3976. },
  3977. sortEventSegs: function(segs) {
  3978. segs.sort(proxy(this, 'compareEventSegs'));
  3979. },
  3980. // A cmp function for determining which segments should take visual priority
  3981. compareEventSegs: function(seg1, seg2) {
  3982. return seg1.eventStartMS - seg2.eventStartMS || // earlier events go first
  3983. seg2.eventDurationMS - seg1.eventDurationMS || // tie? longer events go first
  3984. seg2.event.allDay - seg1.event.allDay || // tie? put all-day events first (booleans cast to 0/1)
  3985. compareByFieldSpecs(seg1.event, seg2.event, this.view.eventOrderSpecs);
  3986. }
  3987. });
  3988. /* Utilities
  3989. ----------------------------------------------------------------------------------------------------------------------*/
  3990. function isBgEvent(event) { // returns true if background OR inverse-background
  3991. var rendering = getEventRendering(event);
  3992. return rendering === 'background' || rendering === 'inverse-background';
  3993. }
  3994. FC.isBgEvent = isBgEvent; // export
  3995. function isInverseBgEvent(event) {
  3996. return getEventRendering(event) === 'inverse-background';
  3997. }
  3998. function getEventRendering(event) {
  3999. return firstDefined((event.source || {}).rendering, event.rendering);
  4000. }
  4001. function groupEventsById(events) {
  4002. var eventsById = {};
  4003. var i, event;
  4004. for (i = 0; i < events.length; i++) {
  4005. event = events[i];
  4006. (eventsById[event._id] || (eventsById[event._id] = [])).push(event);
  4007. }
  4008. return eventsById;
  4009. }
  4010. // A cmp function for determining which non-inverted "ranges" (see above) happen earlier
  4011. function compareRanges(range1, range2) {
  4012. return range1.start - range2.start; // earlier ranges go first
  4013. }
  4014. /* External-Dragging-Element Data
  4015. ----------------------------------------------------------------------------------------------------------------------*/
  4016. // Require all HTML5 data-* attributes used by FullCalendar to have this prefix.
  4017. // A value of '' will query attributes like data-event. A value of 'fc' will query attributes like data-fc-event.
  4018. FC.dataAttrPrefix = '';
  4019. // Given a jQuery element that might represent a dragged FullCalendar event, returns an intermediate data structure
  4020. // to be used for Event Object creation.
  4021. // A defined `.eventProps`, even when empty, indicates that an event should be created.
  4022. function getDraggedElMeta(el) {
  4023. var prefix = FC.dataAttrPrefix;
  4024. var eventProps; // properties for creating the event, not related to date/time
  4025. var startTime; // a Duration
  4026. var duration;
  4027. var stick;
  4028. if (prefix) { prefix += '-'; }
  4029. eventProps = el.data(prefix + 'event') || null;
  4030. if (eventProps) {
  4031. if (typeof eventProps === 'object') {
  4032. eventProps = $.extend({}, eventProps); // make a copy
  4033. }
  4034. else { // something like 1 or true. still signal event creation
  4035. eventProps = {};
  4036. }
  4037. // pluck special-cased date/time properties
  4038. startTime = eventProps.start;
  4039. if (startTime == null) { startTime = eventProps.time; } // accept 'time' as well
  4040. duration = eventProps.duration;
  4041. stick = eventProps.stick;
  4042. delete eventProps.start;
  4043. delete eventProps.time;
  4044. delete eventProps.duration;
  4045. delete eventProps.stick;
  4046. }
  4047. // fallback to standalone attribute values for each of the date/time properties
  4048. if (startTime == null) { startTime = el.data(prefix + 'start'); }
  4049. if (startTime == null) { startTime = el.data(prefix + 'time'); } // accept 'time' as well
  4050. if (duration == null) { duration = el.data(prefix + 'duration'); }
  4051. if (stick == null) { stick = el.data(prefix + 'stick'); }
  4052. // massage into correct data types
  4053. startTime = startTime != null ? moment.duration(startTime) : null;
  4054. duration = duration != null ? moment.duration(duration) : null;
  4055. stick = Boolean(stick);
  4056. return { eventProps: eventProps, startTime: startTime, duration: duration, stick: stick };
  4057. }
  4058. ;;
  4059. /*
  4060. A set of rendering and date-related methods for a visual component comprised of one or more rows of day columns.
  4061. Prerequisite: the object being mixed into needs to be a *Grid*
  4062. */
  4063. var DayTableMixin = FC.DayTableMixin = {
  4064. breakOnWeeks: false, // should create a new row for each week?
  4065. dayDates: null, // whole-day dates for each column. left to right
  4066. dayIndices: null, // for each day from start, the offset
  4067. daysPerRow: null,
  4068. rowCnt: null,
  4069. colCnt: null,
  4070. colHeadFormat: null,
  4071. // Populates internal variables used for date calculation and rendering
  4072. updateDayTable: function() {
  4073. var view = this.view;
  4074. var date = this.start.clone();
  4075. var dayIndex = -1;
  4076. var dayIndices = [];
  4077. var dayDates = [];
  4078. var daysPerRow;
  4079. var firstDay;
  4080. var rowCnt;
  4081. while (date.isBefore(this.end)) { // loop each day from start to end
  4082. if (view.isHiddenDay(date)) {
  4083. dayIndices.push(dayIndex + 0.5); // mark that it's between indices
  4084. }
  4085. else {
  4086. dayIndex++;
  4087. dayIndices.push(dayIndex);
  4088. dayDates.push(date.clone());
  4089. }
  4090. date.add(1, 'days');
  4091. }
  4092. if (this.breakOnWeeks) {
  4093. // count columns until the day-of-week repeats
  4094. firstDay = dayDates[0].day();
  4095. for (daysPerRow = 1; daysPerRow < dayDates.length; daysPerRow++) {
  4096. if (dayDates[daysPerRow].day() == firstDay) {
  4097. break;
  4098. }
  4099. }
  4100. rowCnt = Math.ceil(dayDates.length / daysPerRow);
  4101. }
  4102. else {
  4103. rowCnt = 1;
  4104. daysPerRow = dayDates.length;
  4105. }
  4106. this.dayDates = dayDates;
  4107. this.dayIndices = dayIndices;
  4108. this.daysPerRow = daysPerRow;
  4109. this.rowCnt = rowCnt;
  4110. this.updateDayTableCols();
  4111. },
  4112. // Computes and assigned the colCnt property and updates any options that may be computed from it
  4113. updateDayTableCols: function() {
  4114. this.colCnt = this.computeColCnt();
  4115. this.colHeadFormat = this.view.opt('columnFormat') || this.computeColHeadFormat();
  4116. },
  4117. // Determines how many columns there should be in the table
  4118. computeColCnt: function() {
  4119. return this.daysPerRow;
  4120. },
  4121. // Computes the ambiguously-timed moment for the given cell
  4122. getCellDate: function(row, col) {
  4123. return this.dayDates[
  4124. this.getCellDayIndex(row, col)
  4125. ].clone();
  4126. },
  4127. // Computes the ambiguously-timed date range for the given cell
  4128. getCellRange: function(row, col) {
  4129. var start = this.getCellDate(row, col);
  4130. var end = start.clone().add(1, 'days');
  4131. return { start: start, end: end };
  4132. },
  4133. // Returns the number of day cells, chronologically, from the first of the grid (0-based)
  4134. getCellDayIndex: function(row, col) {
  4135. return row * this.daysPerRow + this.getColDayIndex(col);
  4136. },
  4137. // Returns the numner of day cells, chronologically, from the first cell in *any given row*
  4138. getColDayIndex: function(col) {
  4139. if (this.isRTL) {
  4140. return this.colCnt - 1 - col;
  4141. }
  4142. else {
  4143. return col;
  4144. }
  4145. },
  4146. // Given a date, returns its chronolocial cell-index from the first cell of the grid.
  4147. // If the date lies between cells (because of hiddenDays), returns a floating-point value between offsets.
  4148. // If before the first offset, returns a negative number.
  4149. // If after the last offset, returns an offset past the last cell offset.
  4150. // Only works for *start* dates of cells. Will not work for exclusive end dates for cells.
  4151. getDateDayIndex: function(date) {
  4152. var dayIndices = this.dayIndices;
  4153. var dayOffset = date.diff(this.start, 'days');
  4154. if (dayOffset < 0) {
  4155. return dayIndices[0] - 1;
  4156. }
  4157. else if (dayOffset >= dayIndices.length) {
  4158. return dayIndices[dayIndices.length - 1] + 1;
  4159. }
  4160. else {
  4161. return dayIndices[dayOffset];
  4162. }
  4163. },
  4164. /* Options
  4165. ------------------------------------------------------------------------------------------------------------------*/
  4166. // Computes a default column header formatting string if `colFormat` is not explicitly defined
  4167. computeColHeadFormat: function() {
  4168. // if more than one week row, or if there are a lot of columns with not much space,
  4169. // put just the day numbers will be in each cell
  4170. if (this.rowCnt > 1 || this.colCnt > 10) {
  4171. return 'ddd'; // "Sat"
  4172. }
  4173. // multiple days, so full single date string WON'T be in title text
  4174. else if (this.colCnt > 1) {
  4175. return this.view.opt('dayOfMonthFormat'); // "Sat 12/10"
  4176. }
  4177. // single day, so full single date string will probably be in title text
  4178. else {
  4179. return 'dddd'; // "Saturday"
  4180. }
  4181. },
  4182. /* Slicing
  4183. ------------------------------------------------------------------------------------------------------------------*/
  4184. // Slices up a date range into a segment for every week-row it intersects with
  4185. sliceRangeByRow: function(range) {
  4186. var daysPerRow = this.daysPerRow;
  4187. var normalRange = this.view.computeDayRange(range); // make whole-day range, considering nextDayThreshold
  4188. var rangeFirst = this.getDateDayIndex(normalRange.start); // inclusive first index
  4189. var rangeLast = this.getDateDayIndex(normalRange.end.clone().subtract(1, 'days')); // inclusive last index
  4190. var segs = [];
  4191. var row;
  4192. var rowFirst, rowLast; // inclusive day-index range for current row
  4193. var segFirst, segLast; // inclusive day-index range for segment
  4194. for (row = 0; row < this.rowCnt; row++) {
  4195. rowFirst = row * daysPerRow;
  4196. rowLast = rowFirst + daysPerRow - 1;
  4197. // intersect segment's offset range with the row's
  4198. segFirst = Math.max(rangeFirst, rowFirst);
  4199. segLast = Math.min(rangeLast, rowLast);
  4200. // deal with in-between indices
  4201. segFirst = Math.ceil(segFirst); // in-between starts round to next cell
  4202. segLast = Math.floor(segLast); // in-between ends round to prev cell
  4203. if (segFirst <= segLast) { // was there any intersection with the current row?
  4204. segs.push({
  4205. row: row,
  4206. // normalize to start of row
  4207. firstRowDayIndex: segFirst - rowFirst,
  4208. lastRowDayIndex: segLast - rowFirst,
  4209. // must be matching integers to be the segment's start/end
  4210. isStart: segFirst === rangeFirst,
  4211. isEnd: segLast === rangeLast
  4212. });
  4213. }
  4214. }
  4215. return segs;
  4216. },
  4217. // Slices up a date range into a segment for every day-cell it intersects with.
  4218. // TODO: make more DRY with sliceRangeByRow somehow.
  4219. sliceRangeByDay: function(range) {
  4220. var daysPerRow = this.daysPerRow;
  4221. var normalRange = this.view.computeDayRange(range); // make whole-day range, considering nextDayThreshold
  4222. var rangeFirst = this.getDateDayIndex(normalRange.start); // inclusive first index
  4223. var rangeLast = this.getDateDayIndex(normalRange.end.clone().subtract(1, 'days')); // inclusive last index
  4224. var segs = [];
  4225. var row;
  4226. var rowFirst, rowLast; // inclusive day-index range for current row
  4227. var i;
  4228. var segFirst, segLast; // inclusive day-index range for segment
  4229. for (row = 0; row < this.rowCnt; row++) {
  4230. rowFirst = row * daysPerRow;
  4231. rowLast = rowFirst + daysPerRow - 1;
  4232. for (i = rowFirst; i <= rowLast; i++) {
  4233. // intersect segment's offset range with the row's
  4234. segFirst = Math.max(rangeFirst, i);
  4235. segLast = Math.min(rangeLast, i);
  4236. // deal with in-between indices
  4237. segFirst = Math.ceil(segFirst); // in-between starts round to next cell
  4238. segLast = Math.floor(segLast); // in-between ends round to prev cell
  4239. if (segFirst <= segLast) { // was there any intersection with the current row?
  4240. segs.push({
  4241. row: row,
  4242. // normalize to start of row
  4243. firstRowDayIndex: segFirst - rowFirst,
  4244. lastRowDayIndex: segLast - rowFirst,
  4245. // must be matching integers to be the segment's start/end
  4246. isStart: segFirst === rangeFirst,
  4247. isEnd: segLast === rangeLast
  4248. });
  4249. }
  4250. }
  4251. }
  4252. return segs;
  4253. },
  4254. /* Header Rendering
  4255. ------------------------------------------------------------------------------------------------------------------*/
  4256. renderHeadHtml: function() {
  4257. var view = this.view;
  4258. return '' +
  4259. '<div class="fc-row ' + view.widgetHeaderClass + '">' +
  4260. '<table>' +
  4261. '<thead>' +
  4262. this.renderHeadTrHtml() +
  4263. '</thead>' +
  4264. '</table>' +
  4265. '</div>';
  4266. },
  4267. renderHeadIntroHtml: function() {
  4268. return this.renderIntroHtml(); // fall back to generic
  4269. },
  4270. renderHeadTrHtml: function() {
  4271. return '' +
  4272. '<tr>' +
  4273. (this.isRTL ? '' : this.renderHeadIntroHtml()) +
  4274. this.renderHeadDateCellsHtml() +
  4275. (this.isRTL ? this.renderHeadIntroHtml() : '') +
  4276. '</tr>';
  4277. },
  4278. renderHeadDateCellsHtml: function() {
  4279. var htmls = [];
  4280. var col, date;
  4281. for (col = 0; col < this.colCnt; col++) {
  4282. date = this.getCellDate(0, col);
  4283. htmls.push(this.renderHeadDateCellHtml(date));
  4284. }
  4285. return htmls.join('');
  4286. },
  4287. // TODO: when internalApiVersion, accept an object for HTML attributes
  4288. // (colspan should be no different)
  4289. renderHeadDateCellHtml: function(date, colspan, otherAttrs) {
  4290. var view = this.view;
  4291. return '' +
  4292. '<th class="fc-day-header ' + view.widgetHeaderClass + ' fc-' + dayIDs[date.day()] + '"' +
  4293. (this.rowCnt == 1 ?
  4294. ' data-date="' + date.format('YYYY-MM-DD') + '"' :
  4295. '') +
  4296. (colspan > 1 ?
  4297. ' colspan="' + colspan + '"' :
  4298. '') +
  4299. (otherAttrs ?
  4300. ' ' + otherAttrs :
  4301. '') +
  4302. '>' +
  4303. htmlEscape(date.format(this.colHeadFormat)) +
  4304. '</th>';
  4305. },
  4306. /* Background Rendering
  4307. ------------------------------------------------------------------------------------------------------------------*/
  4308. renderBgTrHtml: function(row) {
  4309. return '' +
  4310. '<tr>' +
  4311. (this.isRTL ? '' : this.renderBgIntroHtml(row)) +
  4312. this.renderBgCellsHtml(row) +
  4313. (this.isRTL ? this.renderBgIntroHtml(row) : '') +
  4314. '</tr>';
  4315. },
  4316. renderBgIntroHtml: function(row) {
  4317. return this.renderIntroHtml(); // fall back to generic
  4318. },
  4319. renderBgCellsHtml: function(row) {
  4320. var htmls = [];
  4321. var col, date;
  4322. for (col = 0; col < this.colCnt; col++) {
  4323. date = this.getCellDate(row, col);
  4324. htmls.push(this.renderBgCellHtml(date));
  4325. }
  4326. return htmls.join('');
  4327. },
  4328. renderBgCellHtml: function(date, otherAttrs) {
  4329. var view = this.view;
  4330. var classes = this.getDayClasses(date);
  4331. classes.unshift('fc-day', view.widgetContentClass);
  4332. return '<td class="' + classes.join(' ') + '"' +
  4333. ' data-date="' + date.format('YYYY-MM-DD') + '"' + // if date has a time, won't format it
  4334. (otherAttrs ?
  4335. ' ' + otherAttrs :
  4336. '') +
  4337. '></td>';
  4338. },
  4339. /* Generic
  4340. ------------------------------------------------------------------------------------------------------------------*/
  4341. // Generates the default HTML intro for any row. User classes should override
  4342. renderIntroHtml: function() {
  4343. },
  4344. // TODO: a generic method for dealing with <tr>, RTL, intro
  4345. // when increment internalApiVersion
  4346. // wrapTr (scheduler)
  4347. /* Utils
  4348. ------------------------------------------------------------------------------------------------------------------*/
  4349. // Applies the generic "intro" and "outro" HTML to the given cells.
  4350. // Intro means the leftmost cell when the calendar is LTR and the rightmost cell when RTL. Vice-versa for outro.
  4351. bookendCells: function(trEl) {
  4352. var introHtml = this.renderIntroHtml();
  4353. if (introHtml) {
  4354. if (this.isRTL) {
  4355. trEl.append(introHtml);
  4356. }
  4357. else {
  4358. trEl.prepend(introHtml);
  4359. }
  4360. }
  4361. }
  4362. };
  4363. ;;
  4364. /* A component that renders a grid of whole-days that runs horizontally. There can be multiple rows, one per week.
  4365. ----------------------------------------------------------------------------------------------------------------------*/
  4366. var DayGrid = FC.DayGrid = Grid.extend(DayTableMixin, {
  4367. numbersVisible: false, // should render a row for day/week numbers? set by outside view. TODO: make internal
  4368. bottomCoordPadding: 0, // hack for extending the hit area for the last row of the coordinate grid
  4369. rowEls: null, // set of fake row elements
  4370. cellEls: null, // set of whole-day elements comprising the row's background
  4371. helperEls: null, // set of cell skeleton elements for rendering the mock event "helper"
  4372. rowCoordCache: null,
  4373. colCoordCache: null,
  4374. // Renders the rows and columns into the component's `this.el`, which should already be assigned.
  4375. // isRigid determins whether the individual rows should ignore the contents and be a constant height.
  4376. // Relies on the view's colCnt and rowCnt. In the future, this component should probably be self-sufficient.
  4377. renderDates: function(isRigid) {
  4378. var view = this.view;
  4379. var rowCnt = this.rowCnt;
  4380. var colCnt = this.colCnt;
  4381. var html = '';
  4382. var row;
  4383. var col;
  4384. for (row = 0; row < rowCnt; row++) {
  4385. html += this.renderDayRowHtml(row, isRigid);
  4386. }
  4387. this.el.html(html);
  4388. this.rowEls = this.el.find('.fc-row');
  4389. this.cellEls = this.el.find('.fc-day');
  4390. this.rowCoordCache = new CoordCache({
  4391. els: this.rowEls,
  4392. isVertical: true
  4393. });
  4394. this.colCoordCache = new CoordCache({
  4395. els: this.cellEls.slice(0, this.colCnt), // only the first row
  4396. isHorizontal: true
  4397. });
  4398. // trigger dayRender with each cell's element
  4399. for (row = 0; row < rowCnt; row++) {
  4400. for (col = 0; col < colCnt; col++) {
  4401. view.trigger(
  4402. 'dayRender',
  4403. null,
  4404. this.getCellDate(row, col),
  4405. this.getCellEl(row, col)
  4406. );
  4407. }
  4408. }
  4409. },
  4410. unrenderDates: function() {
  4411. this.removeSegPopover();
  4412. },
  4413. renderBusinessHours: function() {
  4414. var segs = this.buildBusinessHourSegs(true); // wholeDay=true
  4415. this.renderFill('businessHours', segs, 'bgevent');
  4416. },
  4417. unrenderBusinessHours: function() {
  4418. this.unrenderFill('businessHours');
  4419. },
  4420. // Generates the HTML for a single row, which is a div that wraps a table.
  4421. // `row` is the row number.
  4422. renderDayRowHtml: function(row, isRigid) {
  4423. var view = this.view;
  4424. var classes = [ 'fc-row', 'fc-week', view.widgetContentClass ];
  4425. if (isRigid) {
  4426. classes.push('fc-rigid');
  4427. }
  4428. return '' +
  4429. '<div class="' + classes.join(' ') + '">' +
  4430. '<div class="fc-bg">' +
  4431. '<table>' +
  4432. this.renderBgTrHtml(row) +
  4433. '</table>' +
  4434. '</div>' +
  4435. '<div class="fc-content-skeleton">' +
  4436. '<table>' +
  4437. (this.numbersVisible ?
  4438. '<thead>' +
  4439. this.renderNumberTrHtml(row) +
  4440. '</thead>' :
  4441. ''
  4442. ) +
  4443. '</table>' +
  4444. '</div>' +
  4445. '</div>';
  4446. },
  4447. /* Grid Number Rendering
  4448. ------------------------------------------------------------------------------------------------------------------*/
  4449. renderNumberTrHtml: function(row) {
  4450. return '' +
  4451. '<tr>' +
  4452. (this.isRTL ? '' : this.renderNumberIntroHtml(row)) +
  4453. this.renderNumberCellsHtml(row) +
  4454. (this.isRTL ? this.renderNumberIntroHtml(row) : '') +
  4455. '</tr>';
  4456. },
  4457. renderNumberIntroHtml: function(row) {
  4458. return this.renderIntroHtml();
  4459. },
  4460. renderNumberCellsHtml: function(row) {
  4461. var htmls = [];
  4462. var col, date;
  4463. for (col = 0; col < this.colCnt; col++) {
  4464. date = this.getCellDate(row, col);
  4465. htmls.push(this.renderNumberCellHtml(date));
  4466. }
  4467. return htmls.join('');
  4468. },
  4469. // Generates the HTML for the <td>s of the "number" row in the DayGrid's content skeleton.
  4470. // The number row will only exist if either day numbers or week numbers are turned on.
  4471. renderNumberCellHtml: function(date) {
  4472. var classes;
  4473. if (!this.view.dayNumbersVisible) { // if there are week numbers but not day numbers
  4474. return '<td/>'; // will create an empty space above events :(
  4475. }
  4476. classes = this.getDayClasses(date);
  4477. classes.unshift('fc-day-number');
  4478. return '' +
  4479. '<td class="' + classes.join(' ') + '" data-date="' + date.format() + '">' +
  4480. date.date() +
  4481. '</td>';
  4482. },
  4483. /* Options
  4484. ------------------------------------------------------------------------------------------------------------------*/
  4485. // Computes a default event time formatting string if `timeFormat` is not explicitly defined
  4486. computeEventTimeFormat: function() {
  4487. return this.view.opt('extraSmallTimeFormat'); // like "6p" or "6:30p"
  4488. },
  4489. // Computes a default `displayEventEnd` value if one is not expliclty defined
  4490. computeDisplayEventEnd: function() {
  4491. return this.colCnt == 1; // we'll likely have space if there's only one day
  4492. },
  4493. /* Dates
  4494. ------------------------------------------------------------------------------------------------------------------*/
  4495. rangeUpdated: function() {
  4496. this.updateDayTable();
  4497. },
  4498. // Slices up the given span (unzoned start/end with other misc data) into an array of segments
  4499. spanToSegs: function(span) {
  4500. var segs = this.sliceRangeByRow(span);
  4501. var i, seg;
  4502. for (i = 0; i < segs.length; i++) {
  4503. seg = segs[i];
  4504. if (this.isRTL) {
  4505. seg.leftCol = this.daysPerRow - 1 - seg.lastRowDayIndex;
  4506. seg.rightCol = this.daysPerRow - 1 - seg.firstRowDayIndex;
  4507. }
  4508. else {
  4509. seg.leftCol = seg.firstRowDayIndex;
  4510. seg.rightCol = seg.lastRowDayIndex;
  4511. }
  4512. }
  4513. return segs;
  4514. },
  4515. /* Hit System
  4516. ------------------------------------------------------------------------------------------------------------------*/
  4517. prepareHits: function() {
  4518. this.colCoordCache.build();
  4519. this.rowCoordCache.build();
  4520. this.rowCoordCache.bottoms[this.rowCnt - 1] += this.bottomCoordPadding; // hack
  4521. },
  4522. releaseHits: function() {
  4523. this.colCoordCache.clear();
  4524. this.rowCoordCache.clear();
  4525. },
  4526. queryHit: function(leftOffset, topOffset) {
  4527. if (this.colCoordCache.isLeftInBounds(leftOffset) && this.rowCoordCache.isTopInBounds(topOffset)) {
  4528. var col = this.colCoordCache.getHorizontalIndex(leftOffset);
  4529. var row = this.rowCoordCache.getVerticalIndex(topOffset);
  4530. if (row != null && col != null) {
  4531. return this.getCellHit(row, col);
  4532. }
  4533. }
  4534. },
  4535. getHitSpan: function(hit) {
  4536. return this.getCellRange(hit.row, hit.col);
  4537. },
  4538. getHitEl: function(hit) {
  4539. return this.getCellEl(hit.row, hit.col);
  4540. },
  4541. /* Cell System
  4542. ------------------------------------------------------------------------------------------------------------------*/
  4543. // FYI: the first column is the leftmost column, regardless of date
  4544. getCellHit: function(row, col) {
  4545. return {
  4546. row: row,
  4547. col: col,
  4548. component: this, // needed unfortunately :(
  4549. left: this.colCoordCache.getLeftOffset(col),
  4550. right: this.colCoordCache.getRightOffset(col),
  4551. top: this.rowCoordCache.getTopOffset(row),
  4552. bottom: this.rowCoordCache.getBottomOffset(row)
  4553. };
  4554. },
  4555. getCellEl: function(row, col) {
  4556. return this.cellEls.eq(row * this.colCnt + col);
  4557. },
  4558. /* Event Drag Visualization
  4559. ------------------------------------------------------------------------------------------------------------------*/
  4560. // TODO: move to DayGrid.event, similar to what we did with Grid's drag methods
  4561. // Renders a visual indication of an event or external element being dragged.
  4562. // `eventLocation` has zoned start and end (optional)
  4563. renderDrag: function(eventLocation, seg) {
  4564. // always render a highlight underneath
  4565. this.renderHighlight(this.eventToSpan(eventLocation));
  4566. // if a segment from the same calendar but another component is being dragged, render a helper event
  4567. if (seg && seg.component !== this) {
  4568. return this.renderEventLocationHelper(eventLocation, seg); // returns mock event elements
  4569. }
  4570. },
  4571. // Unrenders any visual indication of a hovering event
  4572. unrenderDrag: function() {
  4573. this.unrenderHighlight();
  4574. this.unrenderHelper();
  4575. },
  4576. /* Event Resize Visualization
  4577. ------------------------------------------------------------------------------------------------------------------*/
  4578. // Renders a visual indication of an event being resized
  4579. renderEventResize: function(eventLocation, seg) {
  4580. this.renderHighlight(this.eventToSpan(eventLocation));
  4581. return this.renderEventLocationHelper(eventLocation, seg); // returns mock event elements
  4582. },
  4583. // Unrenders a visual indication of an event being resized
  4584. unrenderEventResize: function() {
  4585. this.unrenderHighlight();
  4586. this.unrenderHelper();
  4587. },
  4588. /* Event Helper
  4589. ------------------------------------------------------------------------------------------------------------------*/
  4590. // Renders a mock "helper" event. `sourceSeg` is the associated internal segment object. It can be null.
  4591. renderHelper: function(event, sourceSeg) {
  4592. var helperNodes = [];
  4593. var segs = this.eventToSegs(event);
  4594. var rowStructs;
  4595. segs = this.renderFgSegEls(segs); // assigns each seg's el and returns a subset of segs that were rendered
  4596. rowStructs = this.renderSegRows(segs);
  4597. // inject each new event skeleton into each associated row
  4598. this.rowEls.each(function(row, rowNode) {
  4599. var rowEl = $(rowNode); // the .fc-row
  4600. var skeletonEl = $('<div class="fc-helper-skeleton"><table/></div>'); // will be absolutely positioned
  4601. var skeletonTop;
  4602. // If there is an original segment, match the top position. Otherwise, put it at the row's top level
  4603. if (sourceSeg && sourceSeg.row === row) {
  4604. skeletonTop = sourceSeg.el.position().top;
  4605. }
  4606. else {
  4607. skeletonTop = rowEl.find('.fc-content-skeleton tbody').position().top;
  4608. }
  4609. skeletonEl.css('top', skeletonTop)
  4610. .find('table')
  4611. .append(rowStructs[row].tbodyEl);
  4612. rowEl.append(skeletonEl);
  4613. helperNodes.push(skeletonEl[0]);
  4614. });
  4615. return ( // must return the elements rendered
  4616. this.helperEls = $(helperNodes) // array -> jQuery set
  4617. );
  4618. },
  4619. // Unrenders any visual indication of a mock helper event
  4620. unrenderHelper: function() {
  4621. if (this.helperEls) {
  4622. this.helperEls.remove();
  4623. this.helperEls = null;
  4624. }
  4625. },
  4626. /* Fill System (highlight, background events, business hours)
  4627. ------------------------------------------------------------------------------------------------------------------*/
  4628. fillSegTag: 'td', // override the default tag name
  4629. // Renders a set of rectangles over the given segments of days.
  4630. // Only returns segments that successfully rendered.
  4631. renderFill: function(type, segs, className) {
  4632. var nodes = [];
  4633. var i, seg;
  4634. var skeletonEl;
  4635. segs = this.renderFillSegEls(type, segs); // assignes `.el` to each seg. returns successfully rendered segs
  4636. for (i = 0; i < segs.length; i++) {
  4637. seg = segs[i];
  4638. skeletonEl = this.renderFillRow(type, seg, className);
  4639. this.rowEls.eq(seg.row).append(skeletonEl);
  4640. nodes.push(skeletonEl[0]);
  4641. }
  4642. this.elsByFill[type] = $(nodes);
  4643. return segs;
  4644. },
  4645. // Generates the HTML needed for one row of a fill. Requires the seg's el to be rendered.
  4646. renderFillRow: function(type, seg, className) {
  4647. var colCnt = this.colCnt;
  4648. var startCol = seg.leftCol;
  4649. var endCol = seg.rightCol + 1;
  4650. var skeletonEl;
  4651. var trEl;
  4652. className = className || type.toLowerCase();
  4653. skeletonEl = $(
  4654. '<div class="fc-' + className + '-skeleton">' +
  4655. '<table><tr/></table>' +
  4656. '</div>'
  4657. );
  4658. trEl = skeletonEl.find('tr');
  4659. if (startCol > 0) {
  4660. trEl.append('<td colspan="' + startCol + '"/>');
  4661. }
  4662. trEl.append(
  4663. seg.el.attr('colspan', endCol - startCol)
  4664. );
  4665. if (endCol < colCnt) {
  4666. trEl.append('<td colspan="' + (colCnt - endCol) + '"/>');
  4667. }
  4668. this.bookendCells(trEl);
  4669. return skeletonEl;
  4670. }
  4671. });
  4672. ;;
  4673. /* Event-rendering methods for the DayGrid class
  4674. ----------------------------------------------------------------------------------------------------------------------*/
  4675. DayGrid.mixin({
  4676. rowStructs: null, // an array of objects, each holding information about a row's foreground event-rendering
  4677. // Unrenders all events currently rendered on the grid
  4678. unrenderEvents: function() {
  4679. this.removeSegPopover(); // removes the "more.." events popover
  4680. Grid.prototype.unrenderEvents.apply(this, arguments); // calls the super-method
  4681. },
  4682. // Retrieves all rendered segment objects currently rendered on the grid
  4683. getEventSegs: function() {
  4684. return Grid.prototype.getEventSegs.call(this) // get the segments from the super-method
  4685. .concat(this.popoverSegs || []); // append the segments from the "more..." popover
  4686. },
  4687. // Renders the given background event segments onto the grid
  4688. renderBgSegs: function(segs) {
  4689. // don't render timed background events
  4690. var allDaySegs = $.grep(segs, function(seg) {
  4691. return seg.event.allDay;
  4692. });
  4693. return Grid.prototype.renderBgSegs.call(this, allDaySegs); // call the super-method
  4694. },
  4695. // Renders the given foreground event segments onto the grid
  4696. renderFgSegs: function(segs) {
  4697. var rowStructs;
  4698. // render an `.el` on each seg
  4699. // returns a subset of the segs. segs that were actually rendered
  4700. segs = this.renderFgSegEls(segs);
  4701. rowStructs = this.rowStructs = this.renderSegRows(segs);
  4702. // append to each row's content skeleton
  4703. this.rowEls.each(function(i, rowNode) {
  4704. $(rowNode).find('.fc-content-skeleton > table').append(
  4705. rowStructs[i].tbodyEl
  4706. );
  4707. });
  4708. return segs; // return only the segs that were actually rendered
  4709. },
  4710. // Unrenders all currently rendered foreground event segments
  4711. unrenderFgSegs: function() {
  4712. var rowStructs = this.rowStructs || [];
  4713. var rowStruct;
  4714. while ((rowStruct = rowStructs.pop())) {
  4715. rowStruct.tbodyEl.remove();
  4716. }
  4717. this.rowStructs = null;
  4718. },
  4719. // Uses the given events array to generate <tbody> elements that should be appended to each row's content skeleton.
  4720. // Returns an array of rowStruct objects (see the bottom of `renderSegRow`).
  4721. // PRECONDITION: each segment shoud already have a rendered and assigned `.el`
  4722. renderSegRows: function(segs) {
  4723. var rowStructs = [];
  4724. var segRows;
  4725. var row;
  4726. segRows = this.groupSegRows(segs); // group into nested arrays
  4727. // iterate each row of segment groupings
  4728. for (row = 0; row < segRows.length; row++) {
  4729. rowStructs.push(
  4730. this.renderSegRow(row, segRows[row])
  4731. );
  4732. }
  4733. return rowStructs;
  4734. },
  4735. // Builds the HTML to be used for the default element for an individual segment
  4736. fgSegHtml: function(seg, disableResizing) {
  4737. var view = this.view;
  4738. var event = seg.event;
  4739. var isDraggable = view.isEventDraggable(event);
  4740. var isResizableFromStart = !disableResizing && event.allDay &&
  4741. seg.isStart && view.isEventResizableFromStart(event);
  4742. var isResizableFromEnd = !disableResizing && event.allDay &&
  4743. seg.isEnd && view.isEventResizableFromEnd(event);
  4744. var classes = this.getSegClasses(seg, isDraggable, isResizableFromStart || isResizableFromEnd);
  4745. var skinCss = cssToStr(this.getSegSkinCss(seg));
  4746. var timeHtml = '';
  4747. var timeText;
  4748. var titleHtml;
  4749. classes.unshift('fc-day-grid-event', 'fc-h-event');
  4750. // Only display a timed events time if it is the starting segment
  4751. if (seg.isStart) {
  4752. timeText = this.getEventTimeText(event);
  4753. if (timeText) {
  4754. timeHtml = '<span class="fc-time">' + htmlEscape(timeText) + '</span>';
  4755. }
  4756. }
  4757. titleHtml =
  4758. '<span class="fc-title">' +
  4759. (htmlEscape(event.title || '') || '&nbsp;') + // we always want one line of height
  4760. '</span>';
  4761. return '<a class="' + classes.join(' ') + '"' +
  4762. (event.url ?
  4763. ' href="' + htmlEscape(event.url) + '"' :
  4764. ''
  4765. ) +
  4766. (skinCss ?
  4767. ' style="' + skinCss + '"' :
  4768. ''
  4769. ) +
  4770. '>' +
  4771. '<div class="fc-content">' +
  4772. (this.isRTL ?
  4773. titleHtml + ' ' + timeHtml : // put a natural space in between
  4774. timeHtml + ' ' + titleHtml //
  4775. ) +
  4776. '</div>' +
  4777. (isResizableFromStart ?
  4778. '<div class="fc-resizer fc-start-resizer" />' :
  4779. ''
  4780. ) +
  4781. (isResizableFromEnd ?
  4782. '<div class="fc-resizer fc-end-resizer" />' :
  4783. ''
  4784. ) +
  4785. '</a>';
  4786. },
  4787. // Given a row # and an array of segments all in the same row, render a <tbody> element, a skeleton that contains
  4788. // the segments. Returns object with a bunch of internal data about how the render was calculated.
  4789. // NOTE: modifies rowSegs
  4790. renderSegRow: function(row, rowSegs) {
  4791. var colCnt = this.colCnt;
  4792. var segLevels = this.buildSegLevels(rowSegs); // group into sub-arrays of levels
  4793. var levelCnt = Math.max(1, segLevels.length); // ensure at least one level
  4794. var tbody = $('<tbody/>');
  4795. var segMatrix = []; // lookup for which segments are rendered into which level+col cells
  4796. var cellMatrix = []; // lookup for all <td> elements of the level+col matrix
  4797. var loneCellMatrix = []; // lookup for <td> elements that only take up a single column
  4798. var i, levelSegs;
  4799. var col;
  4800. var tr;
  4801. var j, seg;
  4802. var td;
  4803. // populates empty cells from the current column (`col`) to `endCol`
  4804. function emptyCellsUntil(endCol) {
  4805. while (col < endCol) {
  4806. // try to grab a cell from the level above and extend its rowspan. otherwise, create a fresh cell
  4807. td = (loneCellMatrix[i - 1] || [])[col];
  4808. if (td) {
  4809. td.attr(
  4810. 'rowspan',
  4811. parseInt(td.attr('rowspan') || 1, 10) + 1
  4812. );
  4813. }
  4814. else {
  4815. td = $('<td/>');
  4816. tr.append(td);
  4817. }
  4818. cellMatrix[i][col] = td;
  4819. loneCellMatrix[i][col] = td;
  4820. col++;
  4821. }
  4822. }
  4823. for (i = 0; i < levelCnt; i++) { // iterate through all levels
  4824. levelSegs = segLevels[i];
  4825. col = 0;
  4826. tr = $('<tr/>');
  4827. segMatrix.push([]);
  4828. cellMatrix.push([]);
  4829. loneCellMatrix.push([]);
  4830. // levelCnt might be 1 even though there are no actual levels. protect against this.
  4831. // this single empty row is useful for styling.
  4832. if (levelSegs) {
  4833. for (j = 0; j < levelSegs.length; j++) { // iterate through segments in level
  4834. seg = levelSegs[j];
  4835. emptyCellsUntil(seg.leftCol);
  4836. // create a container that occupies or more columns. append the event element.
  4837. td = $('<td class="fc-event-container"/>').append(seg.el);
  4838. if (seg.leftCol != seg.rightCol) {
  4839. td.attr('colspan', seg.rightCol - seg.leftCol + 1);
  4840. }
  4841. else { // a single-column segment
  4842. loneCellMatrix[i][col] = td;
  4843. }
  4844. while (col <= seg.rightCol) {
  4845. cellMatrix[i][col] = td;
  4846. segMatrix[i][col] = seg;
  4847. col++;
  4848. }
  4849. tr.append(td);
  4850. }
  4851. }
  4852. emptyCellsUntil(colCnt); // finish off the row
  4853. this.bookendCells(tr);
  4854. tbody.append(tr);
  4855. }
  4856. return { // a "rowStruct"
  4857. row: row, // the row number
  4858. tbodyEl: tbody,
  4859. cellMatrix: cellMatrix,
  4860. segMatrix: segMatrix,
  4861. segLevels: segLevels,
  4862. segs: rowSegs
  4863. };
  4864. },
  4865. // Stacks a flat array of segments, which are all assumed to be in the same row, into subarrays of vertical levels.
  4866. // NOTE: modifies segs
  4867. buildSegLevels: function(segs) {
  4868. var levels = [];
  4869. var i, seg;
  4870. var j;
  4871. // Give preference to elements with certain criteria, so they have
  4872. // a chance to be closer to the top.
  4873. this.sortEventSegs(segs);
  4874. for (i = 0; i < segs.length; i++) {
  4875. seg = segs[i];
  4876. // loop through levels, starting with the topmost, until the segment doesn't collide with other segments
  4877. for (j = 0; j < levels.length; j++) {
  4878. if (!isDaySegCollision(seg, levels[j])) {
  4879. break;
  4880. }
  4881. }
  4882. // `j` now holds the desired subrow index
  4883. seg.level = j;
  4884. // create new level array if needed and append segment
  4885. (levels[j] || (levels[j] = [])).push(seg);
  4886. }
  4887. // order segments left-to-right. very important if calendar is RTL
  4888. for (j = 0; j < levels.length; j++) {
  4889. levels[j].sort(compareDaySegCols);
  4890. }
  4891. return levels;
  4892. },
  4893. // Given a flat array of segments, return an array of sub-arrays, grouped by each segment's row
  4894. groupSegRows: function(segs) {
  4895. var segRows = [];
  4896. var i;
  4897. for (i = 0; i < this.rowCnt; i++) {
  4898. segRows.push([]);
  4899. }
  4900. for (i = 0; i < segs.length; i++) {
  4901. segRows[segs[i].row].push(segs[i]);
  4902. }
  4903. return segRows;
  4904. }
  4905. });
  4906. // Computes whether two segments' columns collide. They are assumed to be in the same row.
  4907. function isDaySegCollision(seg, otherSegs) {
  4908. var i, otherSeg;
  4909. for (i = 0; i < otherSegs.length; i++) {
  4910. otherSeg = otherSegs[i];
  4911. if (
  4912. otherSeg.leftCol <= seg.rightCol &&
  4913. otherSeg.rightCol >= seg.leftCol
  4914. ) {
  4915. return true;
  4916. }
  4917. }
  4918. return false;
  4919. }
  4920. // A cmp function for determining the leftmost event
  4921. function compareDaySegCols(a, b) {
  4922. return a.leftCol - b.leftCol;
  4923. }
  4924. ;;
  4925. /* Methods relate to limiting the number events for a given day on a DayGrid
  4926. ----------------------------------------------------------------------------------------------------------------------*/
  4927. // NOTE: all the segs being passed around in here are foreground segs
  4928. DayGrid.mixin({
  4929. segPopover: null, // the Popover that holds events that can't fit in a cell. null when not visible
  4930. popoverSegs: null, // an array of segment objects that the segPopover holds. null when not visible
  4931. removeSegPopover: function() {
  4932. if (this.segPopover) {
  4933. this.segPopover.hide(); // in handler, will call segPopover's removeElement
  4934. }
  4935. },
  4936. // Limits the number of "levels" (vertically stacking layers of events) for each row of the grid.
  4937. // `levelLimit` can be false (don't limit), a number, or true (should be computed).
  4938. limitRows: function(levelLimit) {
  4939. var rowStructs = this.rowStructs || [];
  4940. var row; // row #
  4941. var rowLevelLimit;
  4942. for (row = 0; row < rowStructs.length; row++) {
  4943. this.unlimitRow(row);
  4944. if (!levelLimit) {
  4945. rowLevelLimit = false;
  4946. }
  4947. else if (typeof levelLimit === 'number') {
  4948. rowLevelLimit = levelLimit;
  4949. }
  4950. else {
  4951. rowLevelLimit = this.computeRowLevelLimit(row);
  4952. }
  4953. if (rowLevelLimit !== false) {
  4954. this.limitRow(row, rowLevelLimit);
  4955. }
  4956. }
  4957. },
  4958. // Computes the number of levels a row will accomodate without going outside its bounds.
  4959. // Assumes the row is "rigid" (maintains a constant height regardless of what is inside).
  4960. // `row` is the row number.
  4961. computeRowLevelLimit: function(row) {
  4962. var rowEl = this.rowEls.eq(row); // the containing "fake" row div
  4963. var rowHeight = rowEl.height(); // TODO: cache somehow?
  4964. var trEls = this.rowStructs[row].tbodyEl.children();
  4965. var i, trEl;
  4966. var trHeight;
  4967. function iterInnerHeights(i, childNode) {
  4968. trHeight = Math.max(trHeight, $(childNode).outerHeight());
  4969. }
  4970. // Reveal one level <tr> at a time and stop when we find one out of bounds
  4971. for (i = 0; i < trEls.length; i++) {
  4972. trEl = trEls.eq(i).removeClass('fc-limited'); // reset to original state (reveal)
  4973. // with rowspans>1 and IE8, trEl.outerHeight() would return the height of the largest cell,
  4974. // so instead, find the tallest inner content element.
  4975. trHeight = 0;
  4976. trEl.find('> td > :first-child').each(iterInnerHeights);
  4977. if (trEl.position().top + trHeight > rowHeight) {
  4978. return i;
  4979. }
  4980. }
  4981. return false; // should not limit at all
  4982. },
  4983. // Limits the given grid row to the maximum number of levels and injects "more" links if necessary.
  4984. // `row` is the row number.
  4985. // `levelLimit` is a number for the maximum (inclusive) number of levels allowed.
  4986. limitRow: function(row, levelLimit) {
  4987. var _this = this;
  4988. var rowStruct = this.rowStructs[row];
  4989. var moreNodes = []; // array of "more" <a> links and <td> DOM nodes
  4990. var col = 0; // col #, left-to-right (not chronologically)
  4991. var levelSegs; // array of segment objects in the last allowable level, ordered left-to-right
  4992. var cellMatrix; // a matrix (by level, then column) of all <td> jQuery elements in the row
  4993. var limitedNodes; // array of temporarily hidden level <tr> and segment <td> DOM nodes
  4994. var i, seg;
  4995. var segsBelow; // array of segment objects below `seg` in the current `col`
  4996. var totalSegsBelow; // total number of segments below `seg` in any of the columns `seg` occupies
  4997. var colSegsBelow; // array of segment arrays, below seg, one for each column (offset from segs's first column)
  4998. var td, rowspan;
  4999. var segMoreNodes; // array of "more" <td> cells that will stand-in for the current seg's cell
  5000. var j;
  5001. var moreTd, moreWrap, moreLink;
  5002. // Iterates through empty level cells and places "more" links inside if need be
  5003. function emptyCellsUntil(endCol) { // goes from current `col` to `endCol`
  5004. while (col < endCol) {
  5005. segsBelow = _this.getCellSegs(row, col, levelLimit);
  5006. if (segsBelow.length) {
  5007. td = cellMatrix[levelLimit - 1][col];
  5008. moreLink = _this.renderMoreLink(row, col, segsBelow);
  5009. moreWrap = $('<div/>').append(moreLink);
  5010. td.append(moreWrap);
  5011. moreNodes.push(moreWrap[0]);
  5012. }
  5013. col++;
  5014. }
  5015. }
  5016. if (levelLimit && levelLimit < rowStruct.segLevels.length) { // is it actually over the limit?
  5017. levelSegs = rowStruct.segLevels[levelLimit - 1];
  5018. cellMatrix = rowStruct.cellMatrix;
  5019. limitedNodes = rowStruct.tbodyEl.children().slice(levelLimit) // get level <tr> elements past the limit
  5020. .addClass('fc-limited').get(); // hide elements and get a simple DOM-nodes array
  5021. // iterate though segments in the last allowable level
  5022. for (i = 0; i < levelSegs.length; i++) {
  5023. seg = levelSegs[i];
  5024. emptyCellsUntil(seg.leftCol); // process empty cells before the segment
  5025. // determine *all* segments below `seg` that occupy the same columns
  5026. colSegsBelow = [];
  5027. totalSegsBelow = 0;
  5028. while (col <= seg.rightCol) {
  5029. segsBelow = this.getCellSegs(row, col, levelLimit);
  5030. colSegsBelow.push(segsBelow);
  5031. totalSegsBelow += segsBelow.length;
  5032. col++;
  5033. }
  5034. if (totalSegsBelow) { // do we need to replace this segment with one or many "more" links?
  5035. td = cellMatrix[levelLimit - 1][seg.leftCol]; // the segment's parent cell
  5036. rowspan = td.attr('rowspan') || 1;
  5037. segMoreNodes = [];
  5038. // make a replacement <td> for each column the segment occupies. will be one for each colspan
  5039. for (j = 0; j < colSegsBelow.length; j++) {
  5040. moreTd = $('<td class="fc-more-cell"/>').attr('rowspan', rowspan);
  5041. segsBelow = colSegsBelow[j];
  5042. moreLink = this.renderMoreLink(
  5043. row,
  5044. seg.leftCol + j,
  5045. [ seg ].concat(segsBelow) // count seg as hidden too
  5046. );
  5047. moreWrap = $('<div/>').append(moreLink);
  5048. moreTd.append(moreWrap);
  5049. segMoreNodes.push(moreTd[0]);
  5050. moreNodes.push(moreTd[0]);
  5051. }
  5052. td.addClass('fc-limited').after($(segMoreNodes)); // hide original <td> and inject replacements
  5053. limitedNodes.push(td[0]);
  5054. }
  5055. }
  5056. emptyCellsUntil(this.colCnt); // finish off the level
  5057. rowStruct.moreEls = $(moreNodes); // for easy undoing later
  5058. rowStruct.limitedEls = $(limitedNodes); // for easy undoing later
  5059. }
  5060. },
  5061. // Reveals all levels and removes all "more"-related elements for a grid's row.
  5062. // `row` is a row number.
  5063. unlimitRow: function(row) {
  5064. var rowStruct = this.rowStructs[row];
  5065. if (rowStruct.moreEls) {
  5066. rowStruct.moreEls.remove();
  5067. rowStruct.moreEls = null;
  5068. }
  5069. if (rowStruct.limitedEls) {
  5070. rowStruct.limitedEls.removeClass('fc-limited');
  5071. rowStruct.limitedEls = null;
  5072. }
  5073. },
  5074. // Renders an <a> element that represents hidden event element for a cell.
  5075. // Responsible for attaching click handler as well.
  5076. renderMoreLink: function(row, col, hiddenSegs) {
  5077. var _this = this;
  5078. var view = this.view;
  5079. return $('<a class="fc-more"/>')
  5080. .text(
  5081. this.getMoreLinkText(hiddenSegs.length)
  5082. )
  5083. .on('click', function(ev) {
  5084. var clickOption = view.opt('eventLimitClick');
  5085. var date = _this.getCellDate(row, col);
  5086. var moreEl = $(this);
  5087. var dayEl = _this.getCellEl(row, col);
  5088. var allSegs = _this.getCellSegs(row, col);
  5089. // rescope the segments to be within the cell's date
  5090. var reslicedAllSegs = _this.resliceDaySegs(allSegs, date);
  5091. var reslicedHiddenSegs = _this.resliceDaySegs(hiddenSegs, date);
  5092. if (typeof clickOption === 'function') {
  5093. // the returned value can be an atomic option
  5094. clickOption = view.trigger('eventLimitClick', null, {
  5095. date: date,
  5096. dayEl: dayEl,
  5097. moreEl: moreEl,
  5098. segs: reslicedAllSegs,
  5099. hiddenSegs: reslicedHiddenSegs
  5100. }, ev);
  5101. }
  5102. if (clickOption === 'popover') {
  5103. _this.showSegPopover(row, col, moreEl, reslicedAllSegs);
  5104. }
  5105. else if (typeof clickOption === 'string') { // a view name
  5106. view.calendar.zoomTo(date, clickOption);
  5107. }
  5108. });
  5109. },
  5110. // Reveals the popover that displays all events within a cell
  5111. showSegPopover: function(row, col, moreLink, segs) {
  5112. var _this = this;
  5113. var view = this.view;
  5114. var moreWrap = moreLink.parent(); // the <div> wrapper around the <a>
  5115. var topEl; // the element we want to match the top coordinate of
  5116. var options;
  5117. if (this.rowCnt == 1) {
  5118. topEl = view.el; // will cause the popover to cover any sort of header
  5119. }
  5120. else {
  5121. topEl = this.rowEls.eq(row); // will align with top of row
  5122. }
  5123. options = {
  5124. className: 'fc-more-popover',
  5125. content: this.renderSegPopoverContent(row, col, segs),
  5126. parentEl: this.view.el, // attach to root of view. guarantees outside of scrollbars.
  5127. top: topEl.offset().top,
  5128. autoHide: true, // when the user clicks elsewhere, hide the popover
  5129. viewportConstrain: view.opt('popoverViewportConstrain'),
  5130. hide: function() {
  5131. // kill everything when the popover is hidden
  5132. _this.segPopover.removeElement();
  5133. _this.segPopover = null;
  5134. _this.popoverSegs = null;
  5135. }
  5136. };
  5137. // Determine horizontal coordinate.
  5138. // We use the moreWrap instead of the <td> to avoid border confusion.
  5139. if (this.isRTL) {
  5140. options.right = moreWrap.offset().left + moreWrap.outerWidth() + 1; // +1 to be over cell border
  5141. }
  5142. else {
  5143. options.left = moreWrap.offset().left - 1; // -1 to be over cell border
  5144. }
  5145. this.segPopover = new Popover(options);
  5146. this.segPopover.show();
  5147. // the popover doesn't live within the grid's container element, and thus won't get the event
  5148. // delegated-handlers for free. attach event-related handlers to the popover.
  5149. this.bindSegHandlersToEl(this.segPopover.el);
  5150. },
  5151. // Builds the inner DOM contents of the segment popover
  5152. renderSegPopoverContent: function(row, col, segs) {
  5153. var view = this.view;
  5154. var isTheme = view.opt('theme');
  5155. var title = this.getCellDate(row, col).format(view.opt('dayPopoverFormat'));
  5156. var content = $(
  5157. '<div class="fc-header ' + view.widgetHeaderClass + '">' +
  5158. '<span class="fc-close ' +
  5159. (isTheme ? 'ui-icon ui-icon-closethick' : 'fc-icon fc-icon-x') +
  5160. '"></span>' +
  5161. '<span class="fc-title">' +
  5162. htmlEscape(title) +
  5163. '</span>' +
  5164. '<div class="fc-clear"/>' +
  5165. '</div>' +
  5166. '<div class="fc-body ' + view.widgetContentClass + '">' +
  5167. '<div class="fc-event-container"></div>' +
  5168. '</div>'
  5169. );
  5170. var segContainer = content.find('.fc-event-container');
  5171. var i;
  5172. // render each seg's `el` and only return the visible segs
  5173. segs = this.renderFgSegEls(segs, true); // disableResizing=true
  5174. this.popoverSegs = segs;
  5175. for (i = 0; i < segs.length; i++) {
  5176. // because segments in the popover are not part of a grid coordinate system, provide a hint to any
  5177. // grids that want to do drag-n-drop about which cell it came from
  5178. this.prepareHits();
  5179. segs[i].hit = this.getCellHit(row, col);
  5180. this.releaseHits();
  5181. segContainer.append(segs[i].el);
  5182. }
  5183. return content;
  5184. },
  5185. // Given the events within an array of segment objects, reslice them to be in a single day
  5186. resliceDaySegs: function(segs, dayDate) {
  5187. // build an array of the original events
  5188. var events = $.map(segs, function(seg) {
  5189. return seg.event;
  5190. });
  5191. var dayStart = dayDate.clone();
  5192. var dayEnd = dayStart.clone().add(1, 'days');
  5193. var dayRange = { start: dayStart, end: dayEnd };
  5194. // slice the events with a custom slicing function
  5195. segs = this.eventsToSegs(
  5196. events,
  5197. function(range) {
  5198. var seg = intersectRanges(range, dayRange); // undefind if no intersection
  5199. return seg ? [ seg ] : []; // must return an array of segments
  5200. }
  5201. );
  5202. // force an order because eventsToSegs doesn't guarantee one
  5203. this.sortEventSegs(segs);
  5204. return segs;
  5205. },
  5206. // Generates the text that should be inside a "more" link, given the number of events it represents
  5207. getMoreLinkText: function(num) {
  5208. var opt = this.view.opt('eventLimitText');
  5209. if (typeof opt === 'function') {
  5210. return opt(num);
  5211. }
  5212. else {
  5213. return '+' + num + ' ' + opt;
  5214. }
  5215. },
  5216. // Returns segments within a given cell.
  5217. // If `startLevel` is specified, returns only events including and below that level. Otherwise returns all segs.
  5218. getCellSegs: function(row, col, startLevel) {
  5219. var segMatrix = this.rowStructs[row].segMatrix;
  5220. var level = startLevel || 0;
  5221. var segs = [];
  5222. var seg;
  5223. while (level < segMatrix.length) {
  5224. seg = segMatrix[level][col];
  5225. if (seg) {
  5226. segs.push(seg);
  5227. }
  5228. level++;
  5229. }
  5230. return segs;
  5231. }
  5232. });
  5233. ;;
  5234. /* A component that renders one or more columns of vertical time slots
  5235. ----------------------------------------------------------------------------------------------------------------------*/
  5236. // We mixin DayTable, even though there is only a single row of days
  5237. var TimeGrid = FC.TimeGrid = Grid.extend(DayTableMixin, {
  5238. slotDuration: null, // duration of a "slot", a distinct time segment on given day, visualized by lines
  5239. snapDuration: null, // granularity of time for dragging and selecting
  5240. snapsPerSlot: null,
  5241. minTime: null, // Duration object that denotes the first visible time of any given day
  5242. maxTime: null, // Duration object that denotes the exclusive visible end time of any given day
  5243. labelFormat: null, // formatting string for times running along vertical axis
  5244. labelInterval: null, // duration of how often a label should be displayed for a slot
  5245. colEls: null, // cells elements in the day-row background
  5246. slatContainerEl: null, // div that wraps all the slat rows
  5247. slatEls: null, // elements running horizontally across all columns
  5248. nowIndicatorEls: null,
  5249. colCoordCache: null,
  5250. slatCoordCache: null,
  5251. constructor: function() {
  5252. Grid.apply(this, arguments); // call the super-constructor
  5253. this.processOptions();
  5254. },
  5255. // Renders the time grid into `this.el`, which should already be assigned.
  5256. // Relies on the view's colCnt. In the future, this component should probably be self-sufficient.
  5257. renderDates: function() {
  5258. this.el.html(this.renderHtml());
  5259. this.colEls = this.el.find('.fc-day');
  5260. this.slatContainerEl = this.el.find('.fc-slats');
  5261. this.slatEls = this.slatContainerEl.find('tr');
  5262. this.colCoordCache = new CoordCache({
  5263. els: this.colEls,
  5264. isHorizontal: true
  5265. });
  5266. this.slatCoordCache = new CoordCache({
  5267. els: this.slatEls,
  5268. isVertical: true
  5269. });
  5270. this.renderContentSkeleton();
  5271. },
  5272. // Renders the basic HTML skeleton for the grid
  5273. renderHtml: function() {
  5274. return '' +
  5275. '<div class="fc-bg">' +
  5276. '<table>' +
  5277. this.renderBgTrHtml(0) + // row=0
  5278. '</table>' +
  5279. '</div>' +
  5280. '<div class="fc-slats">' +
  5281. '<table>' +
  5282. this.renderSlatRowHtml() +
  5283. '</table>' +
  5284. '</div>';
  5285. },
  5286. // Generates the HTML for the horizontal "slats" that run width-wise. Has a time axis on a side. Depends on RTL.
  5287. renderSlatRowHtml: function() {
  5288. var view = this.view;
  5289. var isRTL = this.isRTL;
  5290. var html = '';
  5291. var slotTime = moment.duration(+this.minTime); // wish there was .clone() for durations
  5292. var slotDate; // will be on the view's first day, but we only care about its time
  5293. var isLabeled;
  5294. var axisHtml;
  5295. // Calculate the time for each slot
  5296. while (slotTime < this.maxTime) {
  5297. slotDate = this.start.clone().time(slotTime);
  5298. isLabeled = isInt(divideDurationByDuration(slotTime, this.labelInterval));
  5299. axisHtml =
  5300. '<td class="fc-axis fc-time ' + view.widgetContentClass + '" ' + view.axisStyleAttr() + '>' +
  5301. (isLabeled ?
  5302. '<span>' + // for matchCellWidths
  5303. htmlEscape(slotDate.format(this.labelFormat)) +
  5304. '</span>' :
  5305. ''
  5306. ) +
  5307. '</td>';
  5308. html +=
  5309. '<tr data-time="' + slotDate.format('HH:mm:ss') + '"' +
  5310. (isLabeled ? '' : ' class="fc-minor"') +
  5311. '>' +
  5312. (!isRTL ? axisHtml : '') +
  5313. '<td class="' + view.widgetContentClass + '"/>' +
  5314. (isRTL ? axisHtml : '') +
  5315. "</tr>";
  5316. slotTime.add(this.slotDuration);
  5317. }
  5318. return html;
  5319. },
  5320. /* Options
  5321. ------------------------------------------------------------------------------------------------------------------*/
  5322. // Parses various options into properties of this object
  5323. processOptions: function() {
  5324. var view = this.view;
  5325. var slotDuration = view.opt('slotDuration');
  5326. var snapDuration = view.opt('snapDuration');
  5327. var input;
  5328. slotDuration = moment.duration(slotDuration);
  5329. snapDuration = snapDuration ? moment.duration(snapDuration) : slotDuration;
  5330. this.slotDuration = slotDuration;
  5331. this.snapDuration = snapDuration;
  5332. this.snapsPerSlot = slotDuration / snapDuration; // TODO: ensure an integer multiple?
  5333. this.minResizeDuration = snapDuration; // hack
  5334. this.minTime = moment.duration(view.opt('minTime'));
  5335. this.maxTime = moment.duration(view.opt('maxTime'));
  5336. // might be an array value (for TimelineView).
  5337. // if so, getting the most granular entry (the last one probably).
  5338. input = view.opt('slotLabelFormat');
  5339. if ($.isArray(input)) {
  5340. input = input[input.length - 1];
  5341. }
  5342. this.labelFormat =
  5343. input ||
  5344. view.opt('axisFormat') || // deprecated
  5345. view.opt('smallTimeFormat'); // the computed default
  5346. input = view.opt('slotLabelInterval');
  5347. this.labelInterval = input ?
  5348. moment.duration(input) :
  5349. this.computeLabelInterval(slotDuration);
  5350. },
  5351. // Computes an automatic value for slotLabelInterval
  5352. computeLabelInterval: function(slotDuration) {
  5353. var i;
  5354. var labelInterval;
  5355. var slotsPerLabel;
  5356. // find the smallest stock label interval that results in more than one slots-per-label
  5357. for (i = AGENDA_STOCK_SUB_DURATIONS.length - 1; i >= 0; i--) {
  5358. labelInterval = moment.duration(AGENDA_STOCK_SUB_DURATIONS[i]);
  5359. slotsPerLabel = divideDurationByDuration(labelInterval, slotDuration);
  5360. if (isInt(slotsPerLabel) && slotsPerLabel > 1) {
  5361. return labelInterval;
  5362. }
  5363. }
  5364. return moment.duration(slotDuration); // fall back. clone
  5365. },
  5366. // Computes a default event time formatting string if `timeFormat` is not explicitly defined
  5367. computeEventTimeFormat: function() {
  5368. return this.view.opt('noMeridiemTimeFormat'); // like "6:30" (no AM/PM)
  5369. },
  5370. // Computes a default `displayEventEnd` value if one is not expliclty defined
  5371. computeDisplayEventEnd: function() {
  5372. return true;
  5373. },
  5374. /* Hit System
  5375. ------------------------------------------------------------------------------------------------------------------*/
  5376. prepareHits: function() {
  5377. this.colCoordCache.build();
  5378. this.slatCoordCache.build();
  5379. },
  5380. releaseHits: function() {
  5381. this.colCoordCache.clear();
  5382. // NOTE: don't clear slatCoordCache because we rely on it for computeTimeTop
  5383. },
  5384. queryHit: function(leftOffset, topOffset) {
  5385. var snapsPerSlot = this.snapsPerSlot;
  5386. var colCoordCache = this.colCoordCache;
  5387. var slatCoordCache = this.slatCoordCache;
  5388. if (colCoordCache.isLeftInBounds(leftOffset) && slatCoordCache.isTopInBounds(topOffset)) {
  5389. var colIndex = colCoordCache.getHorizontalIndex(leftOffset);
  5390. var slatIndex = slatCoordCache.getVerticalIndex(topOffset);
  5391. if (colIndex != null && slatIndex != null) {
  5392. var slatTop = slatCoordCache.getTopOffset(slatIndex);
  5393. var slatHeight = slatCoordCache.getHeight(slatIndex);
  5394. var partial = (topOffset - slatTop) / slatHeight; // floating point number between 0 and 1
  5395. var localSnapIndex = Math.floor(partial * snapsPerSlot); // the snap # relative to start of slat
  5396. var snapIndex = slatIndex * snapsPerSlot + localSnapIndex;
  5397. var snapTop = slatTop + (localSnapIndex / snapsPerSlot) * slatHeight;
  5398. var snapBottom = slatTop + ((localSnapIndex + 1) / snapsPerSlot) * slatHeight;
  5399. return {
  5400. col: colIndex,
  5401. snap: snapIndex,
  5402. component: this, // needed unfortunately :(
  5403. left: colCoordCache.getLeftOffset(colIndex),
  5404. right: colCoordCache.getRightOffset(colIndex),
  5405. top: snapTop,
  5406. bottom: snapBottom
  5407. };
  5408. }
  5409. }
  5410. },
  5411. getHitSpan: function(hit) {
  5412. var start = this.getCellDate(0, hit.col); // row=0
  5413. var time = this.computeSnapTime(hit.snap); // pass in the snap-index
  5414. var end;
  5415. start.time(time);
  5416. end = start.clone().add(this.snapDuration);
  5417. return { start: start, end: end };
  5418. },
  5419. getHitEl: function(hit) {
  5420. return this.colEls.eq(hit.col);
  5421. },
  5422. /* Dates
  5423. ------------------------------------------------------------------------------------------------------------------*/
  5424. rangeUpdated: function() {
  5425. this.updateDayTable();
  5426. },
  5427. // Given a row number of the grid, representing a "snap", returns a time (Duration) from its start-of-day
  5428. computeSnapTime: function(snapIndex) {
  5429. return moment.duration(this.minTime + this.snapDuration * snapIndex);
  5430. },
  5431. // Slices up the given span (unzoned start/end with other misc data) into an array of segments
  5432. spanToSegs: function(span) {
  5433. var segs = this.sliceRangeByTimes(span);
  5434. var i;
  5435. for (i = 0; i < segs.length; i++) {
  5436. if (this.isRTL) {
  5437. segs[i].col = this.daysPerRow - 1 - segs[i].dayIndex;
  5438. }
  5439. else {
  5440. segs[i].col = segs[i].dayIndex;
  5441. }
  5442. }
  5443. return segs;
  5444. },
  5445. sliceRangeByTimes: function(range) {
  5446. var segs = [];
  5447. var seg;
  5448. var dayIndex;
  5449. var dayDate;
  5450. var dayRange;
  5451. for (dayIndex = 0; dayIndex < this.daysPerRow; dayIndex++) {
  5452. dayDate = this.dayDates[dayIndex].clone(); // TODO: better API for this?
  5453. dayRange = {
  5454. start: dayDate.clone().time(this.minTime),
  5455. end: dayDate.clone().time(this.maxTime)
  5456. };
  5457. seg = intersectRanges(range, dayRange); // both will be ambig timezone
  5458. if (seg) {
  5459. seg.dayIndex = dayIndex;
  5460. segs.push(seg);
  5461. }
  5462. }
  5463. return segs;
  5464. },
  5465. /* Coordinates
  5466. ------------------------------------------------------------------------------------------------------------------*/
  5467. updateSize: function(isResize) { // NOT a standard Grid method
  5468. this.slatCoordCache.build();
  5469. if (isResize) {
  5470. this.updateSegVerticals(
  5471. [].concat(this.fgSegs || [], this.bgSegs || [], this.businessSegs || [])
  5472. );
  5473. }
  5474. },
  5475. getTotalSlatHeight: function() {
  5476. return this.slatContainerEl.outerHeight();
  5477. },
  5478. // Computes the top coordinate, relative to the bounds of the grid, of the given date.
  5479. // A `startOfDayDate` must be given for avoiding ambiguity over how to treat midnight.
  5480. computeDateTop: function(date, startOfDayDate) {
  5481. return this.computeTimeTop(
  5482. moment.duration(
  5483. date - startOfDayDate.clone().stripTime()
  5484. )
  5485. );
  5486. },
  5487. // Computes the top coordinate, relative to the bounds of the grid, of the given time (a Duration).
  5488. computeTimeTop: function(time) {
  5489. var len = this.slatEls.length;
  5490. var slatCoverage = (time - this.minTime) / this.slotDuration; // floating-point value of # of slots covered
  5491. var slatIndex;
  5492. var slatRemainder;
  5493. // compute a floating-point number for how many slats should be progressed through.
  5494. // from 0 to number of slats (inclusive)
  5495. // constrained because minTime/maxTime might be customized.
  5496. slatCoverage = Math.max(0, slatCoverage);
  5497. slatCoverage = Math.min(len, slatCoverage);
  5498. // an integer index of the furthest whole slat
  5499. // from 0 to number slats (*exclusive*, so len-1)
  5500. slatIndex = Math.floor(slatCoverage);
  5501. slatIndex = Math.min(slatIndex, len - 1);
  5502. // how much further through the slatIndex slat (from 0.0-1.0) must be covered in addition.
  5503. // could be 1.0 if slatCoverage is covering *all* the slots
  5504. slatRemainder = slatCoverage - slatIndex;
  5505. return this.slatCoordCache.getTopPosition(slatIndex) +
  5506. this.slatCoordCache.getHeight(slatIndex) * slatRemainder;
  5507. },
  5508. /* Event Drag Visualization
  5509. ------------------------------------------------------------------------------------------------------------------*/
  5510. // Renders a visual indication of an event being dragged over the specified date(s).
  5511. // A returned value of `true` signals that a mock "helper" event has been rendered.
  5512. renderDrag: function(eventLocation, seg) {
  5513. if (seg) { // if there is event information for this drag, render a helper event
  5514. // returns mock event elements
  5515. // signal that a helper has been rendered
  5516. return this.renderEventLocationHelper(eventLocation, seg);
  5517. }
  5518. else {
  5519. // otherwise, just render a highlight
  5520. this.renderHighlight(this.eventToSpan(eventLocation));
  5521. }
  5522. },
  5523. // Unrenders any visual indication of an event being dragged
  5524. unrenderDrag: function() {
  5525. this.unrenderHelper();
  5526. this.unrenderHighlight();
  5527. },
  5528. /* Event Resize Visualization
  5529. ------------------------------------------------------------------------------------------------------------------*/
  5530. // Renders a visual indication of an event being resized
  5531. renderEventResize: function(eventLocation, seg) {
  5532. return this.renderEventLocationHelper(eventLocation, seg); // returns mock event elements
  5533. },
  5534. // Unrenders any visual indication of an event being resized
  5535. unrenderEventResize: function() {
  5536. this.unrenderHelper();
  5537. },
  5538. /* Event Helper
  5539. ------------------------------------------------------------------------------------------------------------------*/
  5540. // Renders a mock "helper" event. `sourceSeg` is the original segment object and might be null (an external drag)
  5541. renderHelper: function(event, sourceSeg) {
  5542. return this.renderHelperSegs(this.eventToSegs(event), sourceSeg); // returns mock event elements
  5543. },
  5544. // Unrenders any mock helper event
  5545. unrenderHelper: function() {
  5546. this.unrenderHelperSegs();
  5547. },
  5548. /* Business Hours
  5549. ------------------------------------------------------------------------------------------------------------------*/
  5550. renderBusinessHours: function() {
  5551. this.renderBusinessSegs(
  5552. this.buildBusinessHourSegs()
  5553. );
  5554. },
  5555. unrenderBusinessHours: function() {
  5556. this.unrenderBusinessSegs();
  5557. },
  5558. /* Now Indicator
  5559. ------------------------------------------------------------------------------------------------------------------*/
  5560. getNowIndicatorUnit: function() {
  5561. return 'minute'; // will refresh on the minute
  5562. },
  5563. renderNowIndicator: function(date) {
  5564. // seg system might be overkill, but it handles scenario where line needs to be rendered
  5565. // more than once because of columns with the same date (resources columns for example)
  5566. var segs = this.spanToSegs({ start: date, end: date });
  5567. var top = this.computeDateTop(date, date);
  5568. var nodes = [];
  5569. var i;
  5570. // render lines within the columns
  5571. for (i = 0; i < segs.length; i++) {
  5572. nodes.push($('<div class="fc-now-indicator fc-now-indicator-line"></div>')
  5573. .css('top', top)
  5574. .appendTo(this.colContainerEls.eq(segs[i].col))[0]);
  5575. }
  5576. // render an arrow over the axis
  5577. if (segs.length > 0) { // is the current time in view?
  5578. nodes.push($('<div class="fc-now-indicator fc-now-indicator-arrow"></div>')
  5579. .css('top', top)
  5580. .appendTo(this.el.find('.fc-content-skeleton'))[0]);
  5581. }
  5582. this.nowIndicatorEls = $(nodes);
  5583. },
  5584. unrenderNowIndicator: function() {
  5585. if (this.nowIndicatorEls) {
  5586. this.nowIndicatorEls.remove();
  5587. this.nowIndicatorEls = null;
  5588. }
  5589. },
  5590. /* Selection
  5591. ------------------------------------------------------------------------------------------------------------------*/
  5592. // Renders a visual indication of a selection. Overrides the default, which was to simply render a highlight.
  5593. renderSelection: function(span) {
  5594. if (this.view.opt('selectHelper')) { // this setting signals that a mock helper event should be rendered
  5595. // normally acceps an eventLocation, span has a start/end, which is good enough
  5596. this.renderEventLocationHelper(span);
  5597. }
  5598. else {
  5599. this.renderHighlight(span);
  5600. }
  5601. },
  5602. // Unrenders any visual indication of a selection
  5603. unrenderSelection: function() {
  5604. this.unrenderHelper();
  5605. this.unrenderHighlight();
  5606. },
  5607. /* Highlight
  5608. ------------------------------------------------------------------------------------------------------------------*/
  5609. renderHighlight: function(span) {
  5610. this.renderHighlightSegs(this.spanToSegs(span));
  5611. },
  5612. unrenderHighlight: function() {
  5613. this.unrenderHighlightSegs();
  5614. }
  5615. });
  5616. ;;
  5617. /* Methods for rendering SEGMENTS, pieces of content that live on the view
  5618. ( this file is no longer just for events )
  5619. ----------------------------------------------------------------------------------------------------------------------*/
  5620. TimeGrid.mixin({
  5621. colContainerEls: null, // containers for each column
  5622. // inner-containers for each column where different types of segs live
  5623. fgContainerEls: null,
  5624. bgContainerEls: null,
  5625. helperContainerEls: null,
  5626. highlightContainerEls: null,
  5627. businessContainerEls: null,
  5628. // arrays of different types of displayed segments
  5629. fgSegs: null,
  5630. bgSegs: null,
  5631. helperSegs: null,
  5632. highlightSegs: null,
  5633. businessSegs: null,
  5634. // Renders the DOM that the view's content will live in
  5635. renderContentSkeleton: function() {
  5636. var cellHtml = '';
  5637. var i;
  5638. var skeletonEl;
  5639. for (i = 0; i < this.colCnt; i++) {
  5640. cellHtml +=
  5641. '<td>' +
  5642. '<div class="fc-content-col">' +
  5643. '<div class="fc-event-container fc-helper-container"></div>' +
  5644. '<div class="fc-event-container"></div>' +
  5645. '<div class="fc-highlight-container"></div>' +
  5646. '<div class="fc-bgevent-container"></div>' +
  5647. '<div class="fc-business-container"></div>' +
  5648. '</div>' +
  5649. '</td>';
  5650. }
  5651. skeletonEl = $(
  5652. '<div class="fc-content-skeleton">' +
  5653. '<table>' +
  5654. '<tr>' + cellHtml + '</tr>' +
  5655. '</table>' +
  5656. '</div>'
  5657. );
  5658. this.colContainerEls = skeletonEl.find('.fc-content-col');
  5659. this.helperContainerEls = skeletonEl.find('.fc-helper-container');
  5660. this.fgContainerEls = skeletonEl.find('.fc-event-container:not(.fc-helper-container)');
  5661. this.bgContainerEls = skeletonEl.find('.fc-bgevent-container');
  5662. this.highlightContainerEls = skeletonEl.find('.fc-highlight-container');
  5663. this.businessContainerEls = skeletonEl.find('.fc-business-container');
  5664. this.bookendCells(skeletonEl.find('tr')); // TODO: do this on string level
  5665. this.el.append(skeletonEl);
  5666. },
  5667. /* Foreground Events
  5668. ------------------------------------------------------------------------------------------------------------------*/
  5669. renderFgSegs: function(segs) {
  5670. segs = this.renderFgSegsIntoContainers(segs, this.fgContainerEls);
  5671. this.fgSegs = segs;
  5672. return segs; // needed for Grid::renderEvents
  5673. },
  5674. unrenderFgSegs: function() {
  5675. this.unrenderNamedSegs('fgSegs');
  5676. },
  5677. /* Foreground Helper Events
  5678. ------------------------------------------------------------------------------------------------------------------*/
  5679. renderHelperSegs: function(segs, sourceSeg) {
  5680. var helperEls = [];
  5681. var i, seg;
  5682. var sourceEl;
  5683. segs = this.renderFgSegsIntoContainers(segs, this.helperContainerEls);
  5684. // Try to make the segment that is in the same row as sourceSeg look the same
  5685. for (i = 0; i < segs.length; i++) {
  5686. seg = segs[i];
  5687. if (sourceSeg && sourceSeg.col === seg.col) {
  5688. sourceEl = sourceSeg.el;
  5689. seg.el.css({
  5690. left: sourceEl.css('left'),
  5691. right: sourceEl.css('right'),
  5692. 'margin-left': sourceEl.css('margin-left'),
  5693. 'margin-right': sourceEl.css('margin-right')
  5694. });
  5695. }
  5696. helperEls.push(seg.el[0]);
  5697. }
  5698. this.helperSegs = segs;
  5699. return $(helperEls); // must return rendered helpers
  5700. },
  5701. unrenderHelperSegs: function() {
  5702. this.unrenderNamedSegs('helperSegs');
  5703. },
  5704. /* Background Events
  5705. ------------------------------------------------------------------------------------------------------------------*/
  5706. renderBgSegs: function(segs) {
  5707. segs = this.renderFillSegEls('bgEvent', segs); // TODO: old fill system
  5708. this.updateSegVerticals(segs);
  5709. this.attachSegsByCol(this.groupSegsByCol(segs), this.bgContainerEls);
  5710. this.bgSegs = segs;
  5711. return segs; // needed for Grid::renderEvents
  5712. },
  5713. unrenderBgSegs: function() {
  5714. this.unrenderNamedSegs('bgSegs');
  5715. },
  5716. /* Highlight
  5717. ------------------------------------------------------------------------------------------------------------------*/
  5718. renderHighlightSegs: function(segs) {
  5719. segs = this.renderFillSegEls('highlight', segs); // TODO: old fill system
  5720. this.updateSegVerticals(segs);
  5721. this.attachSegsByCol(this.groupSegsByCol(segs), this.highlightContainerEls);
  5722. this.highlightSegs = segs;
  5723. },
  5724. unrenderHighlightSegs: function() {
  5725. this.unrenderNamedSegs('highlightSegs');
  5726. },
  5727. /* Business Hours
  5728. ------------------------------------------------------------------------------------------------------------------*/
  5729. renderBusinessSegs: function(segs) {
  5730. segs = this.renderFillSegEls('businessHours', segs); // TODO: old fill system
  5731. this.updateSegVerticals(segs);
  5732. this.attachSegsByCol(this.groupSegsByCol(segs), this.businessContainerEls);
  5733. this.businessSegs = segs;
  5734. },
  5735. unrenderBusinessSegs: function() {
  5736. this.unrenderNamedSegs('businessSegs');
  5737. },
  5738. /* Seg Rendering Utils
  5739. ------------------------------------------------------------------------------------------------------------------*/
  5740. // Given a flat array of segments, return an array of sub-arrays, grouped by each segment's col
  5741. groupSegsByCol: function(segs) {
  5742. var segsByCol = [];
  5743. var i;
  5744. for (i = 0; i < this.colCnt; i++) {
  5745. segsByCol.push([]);
  5746. }
  5747. for (i = 0; i < segs.length; i++) {
  5748. segsByCol[segs[i].col].push(segs[i]);
  5749. }
  5750. return segsByCol;
  5751. },
  5752. // Given segments grouped by column, insert the segments' elements into a parallel array of container
  5753. // elements, each living within a column.
  5754. attachSegsByCol: function(segsByCol, containerEls) {
  5755. var col;
  5756. var segs;
  5757. var i;
  5758. for (col = 0; col < this.colCnt; col++) { // iterate each column grouping
  5759. segs = segsByCol[col];
  5760. for (i = 0; i < segs.length; i++) {
  5761. containerEls.eq(col).append(segs[i].el);
  5762. }
  5763. }
  5764. },
  5765. // Given the name of a property of `this` object, assumed to be an array of segments,
  5766. // loops through each segment and removes from DOM. Will null-out the property afterwards.
  5767. unrenderNamedSegs: function(propName) {
  5768. var segs = this[propName];
  5769. var i;
  5770. if (segs) {
  5771. for (i = 0; i < segs.length; i++) {
  5772. segs[i].el.remove();
  5773. }
  5774. this[propName] = null;
  5775. }
  5776. },
  5777. /* Foreground Event Rendering Utils
  5778. ------------------------------------------------------------------------------------------------------------------*/
  5779. // Given an array of foreground segments, render a DOM element for each, computes position,
  5780. // and attaches to the column inner-container elements.
  5781. renderFgSegsIntoContainers: function(segs, containerEls) {
  5782. var segsByCol;
  5783. var col;
  5784. segs = this.renderFgSegEls(segs); // will call fgSegHtml
  5785. segsByCol = this.groupSegsByCol(segs);
  5786. for (col = 0; col < this.colCnt; col++) {
  5787. this.updateFgSegCoords(segsByCol[col]);
  5788. }
  5789. this.attachSegsByCol(segsByCol, containerEls);
  5790. return segs;
  5791. },
  5792. // Renders the HTML for a single event segment's default rendering
  5793. fgSegHtml: function(seg, disableResizing) {
  5794. var view = this.view;
  5795. var event = seg.event;
  5796. var isDraggable = view.isEventDraggable(event);
  5797. var isResizableFromStart = !disableResizing && seg.isStart && view.isEventResizableFromStart(event);
  5798. var isResizableFromEnd = !disableResizing && seg.isEnd && view.isEventResizableFromEnd(event);
  5799. var classes = this.getSegClasses(seg, isDraggable, isResizableFromStart || isResizableFromEnd);
  5800. var skinCss = cssToStr(this.getSegSkinCss(seg));
  5801. var timeText;
  5802. var fullTimeText; // more verbose time text. for the print stylesheet
  5803. var startTimeText; // just the start time text
  5804. classes.unshift('fc-time-grid-event', 'fc-v-event');
  5805. if (view.isMultiDayEvent(event)) { // if the event appears to span more than one day...
  5806. // Don't display time text on segments that run entirely through a day.
  5807. // That would appear as midnight-midnight and would look dumb.
  5808. // Otherwise, display the time text for the *segment's* times (like 6pm-midnight or midnight-10am)
  5809. if (seg.isStart || seg.isEnd) {
  5810. timeText = this.getEventTimeText(seg);
  5811. fullTimeText = this.getEventTimeText(seg, 'LT');
  5812. startTimeText = this.getEventTimeText(seg, null, false); // displayEnd=false
  5813. }
  5814. } else {
  5815. // Display the normal time text for the *event's* times
  5816. timeText = this.getEventTimeText(event);
  5817. fullTimeText = this.getEventTimeText(event, 'LT');
  5818. startTimeText = this.getEventTimeText(event, null, false); // displayEnd=false
  5819. }
  5820. return '<a class="' + classes.join(' ') + '"' +
  5821. (event.url ?
  5822. ' href="' + htmlEscape(event.url) + '"' :
  5823. ''
  5824. ) +
  5825. (skinCss ?
  5826. ' style="' + skinCss + '"' :
  5827. ''
  5828. ) +
  5829. '>' +
  5830. '<div class="fc-content">' +
  5831. (timeText ?
  5832. '<div class="fc-time"' +
  5833. ' data-start="' + htmlEscape(startTimeText) + '"' +
  5834. ' data-full="' + htmlEscape(fullTimeText) + '"' +
  5835. '>' +
  5836. '<span>' + htmlEscape(timeText) + '</span>' +
  5837. '</div>' :
  5838. ''
  5839. ) +
  5840. (event.title ?
  5841. '<div class="fc-title">' +
  5842. htmlEscape(event.title) +
  5843. '</div>' :
  5844. ''
  5845. ) +
  5846. '</div>' +
  5847. '<div class="fc-bg"/>' +
  5848. /* TODO: write CSS for this
  5849. (isResizableFromStart ?
  5850. '<div class="fc-resizer fc-start-resizer" />' :
  5851. ''
  5852. ) +
  5853. */
  5854. (isResizableFromEnd ?
  5855. '<div class="fc-resizer fc-end-resizer" />' :
  5856. ''
  5857. ) +
  5858. '</a>';
  5859. },
  5860. /* Seg Position Utils
  5861. ------------------------------------------------------------------------------------------------------------------*/
  5862. // Refreshes the CSS top/bottom coordinates for each segment element.
  5863. // Works when called after initial render, after a window resize/zoom for example.
  5864. updateSegVerticals: function(segs) {
  5865. this.computeSegVerticals(segs);
  5866. this.assignSegVerticals(segs);
  5867. },
  5868. // For each segment in an array, computes and assigns its top and bottom properties
  5869. computeSegVerticals: function(segs) {
  5870. var i, seg;
  5871. for (i = 0; i < segs.length; i++) {
  5872. seg = segs[i];
  5873. seg.top = this.computeDateTop(seg.start, seg.start);
  5874. seg.bottom = this.computeDateTop(seg.end, seg.start);
  5875. }
  5876. },
  5877. // Given segments that already have their top/bottom properties computed, applies those values to
  5878. // the segments' elements.
  5879. assignSegVerticals: function(segs) {
  5880. var i, seg;
  5881. for (i = 0; i < segs.length; i++) {
  5882. seg = segs[i];
  5883. seg.el.css(this.generateSegVerticalCss(seg));
  5884. }
  5885. },
  5886. // Generates an object with CSS properties for the top/bottom coordinates of a segment element
  5887. generateSegVerticalCss: function(seg) {
  5888. return {
  5889. top: seg.top,
  5890. bottom: -seg.bottom // flipped because needs to be space beyond bottom edge of event container
  5891. };
  5892. },
  5893. /* Foreground Event Positioning Utils
  5894. ------------------------------------------------------------------------------------------------------------------*/
  5895. // Given segments that are assumed to all live in the *same column*,
  5896. // compute their verical/horizontal coordinates and assign to their elements.
  5897. updateFgSegCoords: function(segs) {
  5898. this.computeSegVerticals(segs); // horizontals relies on this
  5899. this.computeFgSegHorizontals(segs); // compute horizontal coordinates, z-index's, and reorder the array
  5900. this.assignSegVerticals(segs);
  5901. this.assignFgSegHorizontals(segs);
  5902. },
  5903. // Given an array of segments that are all in the same column, sets the backwardCoord and forwardCoord on each.
  5904. // NOTE: Also reorders the given array by date!
  5905. computeFgSegHorizontals: function(segs) {
  5906. var levels;
  5907. var level0;
  5908. var i;
  5909. this.sortEventSegs(segs); // order by certain criteria
  5910. levels = buildSlotSegLevels(segs);
  5911. computeForwardSlotSegs(levels);
  5912. if ((level0 = levels[0])) {
  5913. for (i = 0; i < level0.length; i++) {
  5914. computeSlotSegPressures(level0[i]);
  5915. }
  5916. for (i = 0; i < level0.length; i++) {
  5917. this.computeFgSegForwardBack(level0[i], 0, 0);
  5918. }
  5919. }
  5920. },
  5921. // Calculate seg.forwardCoord and seg.backwardCoord for the segment, where both values range
  5922. // from 0 to 1. If the calendar is left-to-right, the seg.backwardCoord maps to "left" and
  5923. // seg.forwardCoord maps to "right" (via percentage). Vice-versa if the calendar is right-to-left.
  5924. //
  5925. // The segment might be part of a "series", which means consecutive segments with the same pressure
  5926. // who's width is unknown until an edge has been hit. `seriesBackwardPressure` is the number of
  5927. // segments behind this one in the current series, and `seriesBackwardCoord` is the starting
  5928. // coordinate of the first segment in the series.
  5929. computeFgSegForwardBack: function(seg, seriesBackwardPressure, seriesBackwardCoord) {
  5930. var forwardSegs = seg.forwardSegs;
  5931. var i;
  5932. if (seg.forwardCoord === undefined) { // not already computed
  5933. if (!forwardSegs.length) {
  5934. // if there are no forward segments, this segment should butt up against the edge
  5935. seg.forwardCoord = 1;
  5936. }
  5937. else {
  5938. // sort highest pressure first
  5939. this.sortForwardSegs(forwardSegs);
  5940. // this segment's forwardCoord will be calculated from the backwardCoord of the
  5941. // highest-pressure forward segment.
  5942. this.computeFgSegForwardBack(forwardSegs[0], seriesBackwardPressure + 1, seriesBackwardCoord);
  5943. seg.forwardCoord = forwardSegs[0].backwardCoord;
  5944. }
  5945. // calculate the backwardCoord from the forwardCoord. consider the series
  5946. seg.backwardCoord = seg.forwardCoord -
  5947. (seg.forwardCoord - seriesBackwardCoord) / // available width for series
  5948. (seriesBackwardPressure + 1); // # of segments in the series
  5949. // use this segment's coordinates to computed the coordinates of the less-pressurized
  5950. // forward segments
  5951. for (i=0; i<forwardSegs.length; i++) {
  5952. this.computeFgSegForwardBack(forwardSegs[i], 0, seg.forwardCoord);
  5953. }
  5954. }
  5955. },
  5956. sortForwardSegs: function(forwardSegs) {
  5957. forwardSegs.sort(proxy(this, 'compareForwardSegs'));
  5958. },
  5959. // A cmp function for determining which forward segment to rely on more when computing coordinates.
  5960. compareForwardSegs: function(seg1, seg2) {
  5961. // put higher-pressure first
  5962. return seg2.forwardPressure - seg1.forwardPressure ||
  5963. // put segments that are closer to initial edge first (and favor ones with no coords yet)
  5964. (seg1.backwardCoord || 0) - (seg2.backwardCoord || 0) ||
  5965. // do normal sorting...
  5966. this.compareEventSegs(seg1, seg2);
  5967. },
  5968. // Given foreground event segments that have already had their position coordinates computed,
  5969. // assigns position-related CSS values to their elements.
  5970. assignFgSegHorizontals: function(segs) {
  5971. var i, seg;
  5972. for (i = 0; i < segs.length; i++) {
  5973. seg = segs[i];
  5974. seg.el.css(this.generateFgSegHorizontalCss(seg));
  5975. // if the height is short, add a className for alternate styling
  5976. if (seg.bottom - seg.top < 30) {
  5977. seg.el.addClass('fc-short');
  5978. }
  5979. }
  5980. },
  5981. // Generates an object with CSS properties/values that should be applied to an event segment element.
  5982. // Contains important positioning-related properties that should be applied to any event element, customized or not.
  5983. generateFgSegHorizontalCss: function(seg) {
  5984. var shouldOverlap = this.view.opt('slotEventOverlap');
  5985. var backwardCoord = seg.backwardCoord; // the left side if LTR. the right side if RTL. floating-point
  5986. var forwardCoord = seg.forwardCoord; // the right side if LTR. the left side if RTL. floating-point
  5987. var props = this.generateSegVerticalCss(seg); // get top/bottom first
  5988. var left; // amount of space from left edge, a fraction of the total width
  5989. var right; // amount of space from right edge, a fraction of the total width
  5990. if (shouldOverlap) {
  5991. // double the width, but don't go beyond the maximum forward coordinate (1.0)
  5992. forwardCoord = Math.min(1, backwardCoord + (forwardCoord - backwardCoord) * 2);
  5993. }
  5994. if (this.isRTL) {
  5995. left = 1 - forwardCoord;
  5996. right = backwardCoord;
  5997. }
  5998. else {
  5999. left = backwardCoord;
  6000. right = 1 - forwardCoord;
  6001. }
  6002. props.zIndex = seg.level + 1; // convert from 0-base to 1-based
  6003. props.left = left * 100 + '%';
  6004. props.right = right * 100 + '%';
  6005. if (shouldOverlap && seg.forwardPressure) {
  6006. // add padding to the edge so that forward stacked events don't cover the resizer's icon
  6007. props[this.isRTL ? 'marginLeft' : 'marginRight'] = 10 * 2; // 10 is a guesstimate of the icon's width
  6008. }
  6009. return props;
  6010. }
  6011. });
  6012. // Builds an array of segments "levels". The first level will be the leftmost tier of segments if the calendar is
  6013. // left-to-right, or the rightmost if the calendar is right-to-left. Assumes the segments are already ordered by date.
  6014. function buildSlotSegLevels(segs) {
  6015. var levels = [];
  6016. var i, seg;
  6017. var j;
  6018. for (i=0; i<segs.length; i++) {
  6019. seg = segs[i];
  6020. // go through all the levels and stop on the first level where there are no collisions
  6021. for (j=0; j<levels.length; j++) {
  6022. if (!computeSlotSegCollisions(seg, levels[j]).length) {
  6023. break;
  6024. }
  6025. }
  6026. seg.level = j;
  6027. (levels[j] || (levels[j] = [])).push(seg);
  6028. }
  6029. return levels;
  6030. }
  6031. // For every segment, figure out the other segments that are in subsequent
  6032. // levels that also occupy the same vertical space. Accumulate in seg.forwardSegs
  6033. function computeForwardSlotSegs(levels) {
  6034. var i, level;
  6035. var j, seg;
  6036. var k;
  6037. for (i=0; i<levels.length; i++) {
  6038. level = levels[i];
  6039. for (j=0; j<level.length; j++) {
  6040. seg = level[j];
  6041. seg.forwardSegs = [];
  6042. for (k=i+1; k<levels.length; k++) {
  6043. computeSlotSegCollisions(seg, levels[k], seg.forwardSegs);
  6044. }
  6045. }
  6046. }
  6047. }
  6048. // Figure out which path forward (via seg.forwardSegs) results in the longest path until
  6049. // the furthest edge is reached. The number of segments in this path will be seg.forwardPressure
  6050. function computeSlotSegPressures(seg) {
  6051. var forwardSegs = seg.forwardSegs;
  6052. var forwardPressure = 0;
  6053. var i, forwardSeg;
  6054. if (seg.forwardPressure === undefined) { // not already computed
  6055. for (i=0; i<forwardSegs.length; i++) {
  6056. forwardSeg = forwardSegs[i];
  6057. // figure out the child's maximum forward path
  6058. computeSlotSegPressures(forwardSeg);
  6059. // either use the existing maximum, or use the child's forward pressure
  6060. // plus one (for the forwardSeg itself)
  6061. forwardPressure = Math.max(
  6062. forwardPressure,
  6063. 1 + forwardSeg.forwardPressure
  6064. );
  6065. }
  6066. seg.forwardPressure = forwardPressure;
  6067. }
  6068. }
  6069. // Find all the segments in `otherSegs` that vertically collide with `seg`.
  6070. // Append into an optionally-supplied `results` array and return.
  6071. function computeSlotSegCollisions(seg, otherSegs, results) {
  6072. results = results || [];
  6073. for (var i=0; i<otherSegs.length; i++) {
  6074. if (isSlotSegCollision(seg, otherSegs[i])) {
  6075. results.push(otherSegs[i]);
  6076. }
  6077. }
  6078. return results;
  6079. }
  6080. // Do these segments occupy the same vertical space?
  6081. function isSlotSegCollision(seg1, seg2) {
  6082. return seg1.bottom > seg2.top && seg1.top < seg2.bottom;
  6083. }
  6084. ;;
  6085. /* An abstract class from which other views inherit from
  6086. ----------------------------------------------------------------------------------------------------------------------*/
  6087. var View = FC.View = Class.extend(EmitterMixin, ListenerMixin, {
  6088. type: null, // subclass' view name (string)
  6089. name: null, // deprecated. use `type` instead
  6090. title: null, // the text that will be displayed in the header's title
  6091. calendar: null, // owner Calendar object
  6092. options: null, // hash containing all options. already merged with view-specific-options
  6093. el: null, // the view's containing element. set by Calendar
  6094. displaying: null, // a promise representing the state of rendering. null if no render requested
  6095. isSkeletonRendered: false,
  6096. isEventsRendered: false,
  6097. // range the view is actually displaying (moments)
  6098. start: null,
  6099. end: null, // exclusive
  6100. // range the view is formally responsible for (moments)
  6101. // may be different from start/end. for example, a month view might have 1st-31st, excluding padded dates
  6102. intervalStart: null,
  6103. intervalEnd: null, // exclusive
  6104. intervalDuration: null,
  6105. intervalUnit: null, // name of largest unit being displayed, like "month" or "week"
  6106. isRTL: false,
  6107. isSelected: false, // boolean whether a range of time is user-selected or not
  6108. selectedEvent: null,
  6109. eventOrderSpecs: null, // criteria for ordering events when they have same date/time
  6110. // classNames styled by jqui themes
  6111. widgetHeaderClass: null,
  6112. widgetContentClass: null,
  6113. highlightStateClass: null,
  6114. // for date utils, computed from options
  6115. nextDayThreshold: null,
  6116. isHiddenDayHash: null,
  6117. // now indicator
  6118. isNowIndicatorRendered: null,
  6119. initialNowDate: null, // result first getNow call
  6120. initialNowQueriedMs: null, // ms time the getNow was called
  6121. nowIndicatorTimeoutID: null, // for refresh timing of now indicator
  6122. nowIndicatorIntervalID: null, // "
  6123. constructor: function(calendar, type, options, intervalDuration) {
  6124. this.calendar = calendar;
  6125. this.type = this.name = type; // .name is deprecated
  6126. this.options = options;
  6127. this.intervalDuration = intervalDuration || moment.duration(1, 'day');
  6128. this.nextDayThreshold = moment.duration(this.opt('nextDayThreshold'));
  6129. this.initThemingProps();
  6130. this.initHiddenDays();
  6131. this.isRTL = this.opt('isRTL');
  6132. this.eventOrderSpecs = parseFieldSpecs(this.opt('eventOrder'));
  6133. this.initialize();
  6134. },
  6135. // A good place for subclasses to initialize member variables
  6136. initialize: function() {
  6137. // subclasses can implement
  6138. },
  6139. // Retrieves an option with the given name
  6140. opt: function(name) {
  6141. return this.options[name];
  6142. },
  6143. // Triggers handlers that are view-related. Modifies args before passing to calendar.
  6144. trigger: function(name, thisObj) { // arguments beyond thisObj are passed along
  6145. var calendar = this.calendar;
  6146. return calendar.trigger.apply(
  6147. calendar,
  6148. [name, thisObj || this].concat(
  6149. Array.prototype.slice.call(arguments, 2), // arguments beyond thisObj
  6150. [ this ] // always make the last argument a reference to the view. TODO: deprecate
  6151. )
  6152. );
  6153. },
  6154. /* Dates
  6155. ------------------------------------------------------------------------------------------------------------------*/
  6156. // Updates all internal dates to center around the given current unzoned date.
  6157. setDate: function(date) {
  6158. this.setRange(this.computeRange(date));
  6159. },
  6160. // Updates all internal dates for displaying the given unzoned range.
  6161. setRange: function(range) {
  6162. $.extend(this, range); // assigns every property to this object's member variables
  6163. this.updateTitle();
  6164. },
  6165. // Given a single current unzoned date, produce information about what range to display.
  6166. // Subclasses can override. Must return all properties.
  6167. computeRange: function(date) {
  6168. var intervalUnit = computeIntervalUnit(this.intervalDuration);
  6169. var intervalStart = date.clone().startOf(intervalUnit);
  6170. var intervalEnd = intervalStart.clone().add(this.intervalDuration);
  6171. var start, end;
  6172. // normalize the range's time-ambiguity
  6173. if (/year|month|week|day/.test(intervalUnit)) { // whole-days?
  6174. intervalStart.stripTime();
  6175. intervalEnd.stripTime();
  6176. }
  6177. else { // needs to have a time?
  6178. if (!intervalStart.hasTime()) {
  6179. intervalStart = this.calendar.time(0); // give 00:00 time
  6180. }
  6181. if (!intervalEnd.hasTime()) {
  6182. intervalEnd = this.calendar.time(0); // give 00:00 time
  6183. }
  6184. }
  6185. start = intervalStart.clone();
  6186. start = this.skipHiddenDays(start);
  6187. end = intervalEnd.clone();
  6188. end = this.skipHiddenDays(end, -1, true); // exclusively move backwards
  6189. return {
  6190. intervalUnit: intervalUnit,
  6191. intervalStart: intervalStart,
  6192. intervalEnd: intervalEnd,
  6193. start: start,
  6194. end: end
  6195. };
  6196. },
  6197. // Computes the new date when the user hits the prev button, given the current date
  6198. computePrevDate: function(date) {
  6199. return this.massageCurrentDate(
  6200. date.clone().startOf(this.intervalUnit).subtract(this.intervalDuration), -1
  6201. );
  6202. },
  6203. // Computes the new date when the user hits the next button, given the current date
  6204. computeNextDate: function(date) {
  6205. return this.massageCurrentDate(
  6206. date.clone().startOf(this.intervalUnit).add(this.intervalDuration)
  6207. );
  6208. },
  6209. // Given an arbitrarily calculated current date of the calendar, returns a date that is ensured to be completely
  6210. // visible. `direction` is optional and indicates which direction the current date was being
  6211. // incremented or decremented (1 or -1).
  6212. massageCurrentDate: function(date, direction) {
  6213. if (this.intervalDuration.as('days') <= 1) { // if the view displays a single day or smaller
  6214. if (this.isHiddenDay(date)) {
  6215. date = this.skipHiddenDays(date, direction);
  6216. date.startOf('day');
  6217. }
  6218. }
  6219. return date;
  6220. },
  6221. /* Title and Date Formatting
  6222. ------------------------------------------------------------------------------------------------------------------*/
  6223. // Sets the view's title property to the most updated computed value
  6224. updateTitle: function() {
  6225. this.title = this.computeTitle();
  6226. },
  6227. // Computes what the title at the top of the calendar should be for this view
  6228. computeTitle: function() {
  6229. return this.formatRange(
  6230. {
  6231. // in case intervalStart/End has a time, make sure timezone is correct
  6232. start: this.calendar.applyTimezone(this.intervalStart),
  6233. end: this.calendar.applyTimezone(this.intervalEnd)
  6234. },
  6235. this.opt('titleFormat') || this.computeTitleFormat(),
  6236. this.opt('titleRangeSeparator')
  6237. );
  6238. },
  6239. // Generates the format string that should be used to generate the title for the current date range.
  6240. // Attempts to compute the most appropriate format if not explicitly specified with `titleFormat`.
  6241. computeTitleFormat: function() {
  6242. if (this.intervalUnit == 'year') {
  6243. return 'YYYY';
  6244. }
  6245. else if (this.intervalUnit == 'month') {
  6246. return this.opt('monthYearFormat'); // like "September 2014"
  6247. }
  6248. else if (this.intervalDuration.as('days') > 1) {
  6249. return 'll'; // multi-day range. shorter, like "Sep 9 - 10 2014"
  6250. }
  6251. else {
  6252. return 'LL'; // one day. longer, like "September 9 2014"
  6253. }
  6254. },
  6255. // Utility for formatting a range. Accepts a range object, formatting string, and optional separator.
  6256. // Displays all-day ranges naturally, with an inclusive end. Takes the current isRTL into account.
  6257. // The timezones of the dates within `range` will be respected.
  6258. formatRange: function(range, formatStr, separator) {
  6259. var end = range.end;
  6260. if (!end.hasTime()) { // all-day?
  6261. end = end.clone().subtract(1); // convert to inclusive. last ms of previous day
  6262. }
  6263. return formatRange(range.start, end, formatStr, separator, this.opt('isRTL'));
  6264. },
  6265. /* Rendering
  6266. ------------------------------------------------------------------------------------------------------------------*/
  6267. // Sets the container element that the view should render inside of.
  6268. // Does other DOM-related initializations.
  6269. setElement: function(el) {
  6270. this.el = el;
  6271. this.bindGlobalHandlers();
  6272. },
  6273. // Removes the view's container element from the DOM, clearing any content beforehand.
  6274. // Undoes any other DOM-related attachments.
  6275. removeElement: function() {
  6276. this.clear(); // clears all content
  6277. // clean up the skeleton
  6278. if (this.isSkeletonRendered) {
  6279. this.unrenderSkeleton();
  6280. this.isSkeletonRendered = false;
  6281. }
  6282. this.unbindGlobalHandlers();
  6283. this.el.remove();
  6284. // NOTE: don't null-out this.el in case the View was destroyed within an API callback.
  6285. // We don't null-out the View's other jQuery element references upon destroy,
  6286. // so we shouldn't kill this.el either.
  6287. },
  6288. // Does everything necessary to display the view centered around the given unzoned date.
  6289. // Does every type of rendering EXCEPT rendering events.
  6290. // Is asychronous and returns a promise.
  6291. display: function(date, explicitScrollState) {
  6292. var _this = this;
  6293. var prevScrollState = null;
  6294. if (explicitScrollState != null && this.displaying) { // don't need prevScrollState if explicitScrollState
  6295. prevScrollState = this.queryScroll();
  6296. }
  6297. this.calendar.freezeContentHeight();
  6298. return syncThen(this.clear(), function() { // clear the content first
  6299. return (
  6300. _this.displaying =
  6301. syncThen(_this.displayView(date), function() { // displayView might return a promise
  6302. // caller of display() wants a specific scroll state?
  6303. if (explicitScrollState != null) {
  6304. // we make an assumption that this is NOT the initial render,
  6305. // and thus don't need forceScroll (is inconveniently asynchronous)
  6306. _this.setScroll(explicitScrollState);
  6307. }
  6308. else {
  6309. _this.forceScroll(_this.computeInitialScroll(prevScrollState));
  6310. }
  6311. _this.calendar.unfreezeContentHeight();
  6312. _this.triggerRender();
  6313. })
  6314. );
  6315. });
  6316. },
  6317. // Does everything necessary to clear the content of the view.
  6318. // Clears dates and events. Does not clear the skeleton.
  6319. // Is asychronous and returns a promise.
  6320. clear: function() {
  6321. var _this = this;
  6322. var displaying = this.displaying;
  6323. if (displaying) { // previously displayed, or in the process of being displayed?
  6324. return syncThen(displaying, function() { // wait for the display to finish
  6325. _this.displaying = null;
  6326. _this.clearEvents();
  6327. return _this.clearView(); // might return a promise. chain it
  6328. });
  6329. }
  6330. else {
  6331. return $.when(); // an immediately-resolved promise
  6332. }
  6333. },
  6334. // Displays the view's non-event content, such as date-related content or anything required by events.
  6335. // Renders the view's non-content skeleton if necessary.
  6336. // Can be asynchronous and return a promise.
  6337. displayView: function(date) {
  6338. if (!this.isSkeletonRendered) {
  6339. this.renderSkeleton();
  6340. this.isSkeletonRendered = true;
  6341. }
  6342. if (date) {
  6343. this.setDate(date);
  6344. }
  6345. if (this.render) {
  6346. this.render(); // TODO: deprecate
  6347. }
  6348. this.renderDates();
  6349. this.updateSize();
  6350. this.renderBusinessHours(); // might need coordinates, so should go after updateSize()
  6351. this.startNowIndicator();
  6352. },
  6353. // Unrenders the view content that was rendered in displayView.
  6354. // Can be asynchronous and return a promise.
  6355. clearView: function() {
  6356. this.unselect();
  6357. this.stopNowIndicator();
  6358. this.triggerUnrender();
  6359. this.unrenderBusinessHours();
  6360. this.unrenderDates();
  6361. if (this.destroy) {
  6362. this.destroy(); // TODO: deprecate
  6363. }
  6364. },
  6365. // Renders the basic structure of the view before any content is rendered
  6366. renderSkeleton: function() {
  6367. // subclasses should implement
  6368. },
  6369. // Unrenders the basic structure of the view
  6370. unrenderSkeleton: function() {
  6371. // subclasses should implement
  6372. },
  6373. // Renders the view's date-related content.
  6374. // Assumes setRange has already been called and the skeleton has already been rendered.
  6375. renderDates: function() {
  6376. // subclasses should implement
  6377. },
  6378. // Unrenders the view's date-related content
  6379. unrenderDates: function() {
  6380. // subclasses should override
  6381. },
  6382. // Signals that the view's content has been rendered
  6383. triggerRender: function() {
  6384. this.trigger('viewRender', this, this, this.el);
  6385. },
  6386. // Signals that the view's content is about to be unrendered
  6387. triggerUnrender: function() {
  6388. this.trigger('viewDestroy', this, this, this.el);
  6389. },
  6390. // Binds DOM handlers to elements that reside outside the view container, such as the document
  6391. bindGlobalHandlers: function() {
  6392. this.listenTo($(document), 'mousedown', this.handleDocumentMousedown);
  6393. this.listenTo($(document), 'touchstart', this.processUnselect);
  6394. },
  6395. // Unbinds DOM handlers from elements that reside outside the view container
  6396. unbindGlobalHandlers: function() {
  6397. this.stopListeningTo($(document));
  6398. },
  6399. // Initializes internal variables related to theming
  6400. initThemingProps: function() {
  6401. var tm = this.opt('theme') ? 'ui' : 'fc';
  6402. this.widgetHeaderClass = tm + '-widget-header';
  6403. this.widgetContentClass = tm + '-widget-content';
  6404. this.highlightStateClass = tm + '-state-highlight';
  6405. },
  6406. /* Business Hours
  6407. ------------------------------------------------------------------------------------------------------------------*/
  6408. // Renders business-hours onto the view. Assumes updateSize has already been called.
  6409. renderBusinessHours: function() {
  6410. // subclasses should implement
  6411. },
  6412. // Unrenders previously-rendered business-hours
  6413. unrenderBusinessHours: function() {
  6414. // subclasses should implement
  6415. },
  6416. /* Now Indicator
  6417. ------------------------------------------------------------------------------------------------------------------*/
  6418. // Immediately render the current time indicator and begins re-rendering it at an interval,
  6419. // which is defined by this.getNowIndicatorUnit().
  6420. // TODO: somehow do this for the current whole day's background too
  6421. startNowIndicator: function() {
  6422. var _this = this;
  6423. var unit;
  6424. var update;
  6425. var delay; // ms wait value
  6426. if (this.opt('nowIndicator')) {
  6427. unit = this.getNowIndicatorUnit();
  6428. if (unit) {
  6429. update = proxy(this, 'updateNowIndicator'); // bind to `this`
  6430. this.initialNowDate = this.calendar.getNow();
  6431. this.initialNowQueriedMs = +new Date();
  6432. this.renderNowIndicator(this.initialNowDate);
  6433. this.isNowIndicatorRendered = true;
  6434. // wait until the beginning of the next interval
  6435. delay = this.initialNowDate.clone().startOf(unit).add(1, unit) - this.initialNowDate;
  6436. this.nowIndicatorTimeoutID = setTimeout(function() {
  6437. _this.nowIndicatorTimeoutID = null;
  6438. update();
  6439. delay = +moment.duration(1, unit);
  6440. delay = Math.max(100, delay); // prevent too frequent
  6441. _this.nowIndicatorIntervalID = setInterval(update, delay); // update every interval
  6442. }, delay);
  6443. }
  6444. }
  6445. },
  6446. // rerenders the now indicator, computing the new current time from the amount of time that has passed
  6447. // since the initial getNow call.
  6448. updateNowIndicator: function() {
  6449. if (this.isNowIndicatorRendered) {
  6450. this.unrenderNowIndicator();
  6451. this.renderNowIndicator(
  6452. this.initialNowDate.clone().add(new Date() - this.initialNowQueriedMs) // add ms
  6453. );
  6454. }
  6455. },
  6456. // Immediately unrenders the view's current time indicator and stops any re-rendering timers.
  6457. // Won't cause side effects if indicator isn't rendered.
  6458. stopNowIndicator: function() {
  6459. if (this.isNowIndicatorRendered) {
  6460. if (this.nowIndicatorTimeoutID) {
  6461. clearTimeout(this.nowIndicatorTimeoutID);
  6462. this.nowIndicatorTimeoutID = null;
  6463. }
  6464. if (this.nowIndicatorIntervalID) {
  6465. clearTimeout(this.nowIndicatorIntervalID);
  6466. this.nowIndicatorIntervalID = null;
  6467. }
  6468. this.unrenderNowIndicator();
  6469. this.isNowIndicatorRendered = false;
  6470. }
  6471. },
  6472. // Returns a string unit, like 'second' or 'minute' that defined how often the current time indicator
  6473. // should be refreshed. If something falsy is returned, no time indicator is rendered at all.
  6474. getNowIndicatorUnit: function() {
  6475. // subclasses should implement
  6476. },
  6477. // Renders a current time indicator at the given datetime
  6478. renderNowIndicator: function(date) {
  6479. // subclasses should implement
  6480. },
  6481. // Undoes the rendering actions from renderNowIndicator
  6482. unrenderNowIndicator: function() {
  6483. // subclasses should implement
  6484. },
  6485. /* Dimensions
  6486. ------------------------------------------------------------------------------------------------------------------*/
  6487. // Refreshes anything dependant upon sizing of the container element of the grid
  6488. updateSize: function(isResize) {
  6489. var scrollState;
  6490. if (isResize) {
  6491. scrollState = this.queryScroll();
  6492. }
  6493. this.updateHeight(isResize);
  6494. this.updateWidth(isResize);
  6495. this.updateNowIndicator();
  6496. if (isResize) {
  6497. this.setScroll(scrollState);
  6498. }
  6499. },
  6500. // Refreshes the horizontal dimensions of the calendar
  6501. updateWidth: function(isResize) {
  6502. // subclasses should implement
  6503. },
  6504. // Refreshes the vertical dimensions of the calendar
  6505. updateHeight: function(isResize) {
  6506. var calendar = this.calendar; // we poll the calendar for height information
  6507. this.setHeight(
  6508. calendar.getSuggestedViewHeight(),
  6509. calendar.isHeightAuto()
  6510. );
  6511. },
  6512. // Updates the vertical dimensions of the calendar to the specified height.
  6513. // if `isAuto` is set to true, height becomes merely a suggestion and the view should use its "natural" height.
  6514. setHeight: function(height, isAuto) {
  6515. // subclasses should implement
  6516. },
  6517. /* Scroller
  6518. ------------------------------------------------------------------------------------------------------------------*/
  6519. // Computes the initial pre-configured scroll state prior to allowing the user to change it.
  6520. // Given the scroll state from the previous rendering. If first time rendering, given null.
  6521. computeInitialScroll: function(previousScrollState) {
  6522. return 0;
  6523. },
  6524. // Retrieves the view's current natural scroll state. Can return an arbitrary format.
  6525. queryScroll: function() {
  6526. // subclasses must implement
  6527. },
  6528. // Sets the view's scroll state. Will accept the same format computeInitialScroll and queryScroll produce.
  6529. setScroll: function(scrollState) {
  6530. // subclasses must implement
  6531. },
  6532. // Sets the scroll state, making sure to overcome any predefined scroll value the browser has in mind
  6533. forceScroll: function(scrollState) {
  6534. var _this = this;
  6535. this.setScroll(scrollState);
  6536. setTimeout(function() {
  6537. _this.setScroll(scrollState);
  6538. }, 0);
  6539. },
  6540. /* Event Elements / Segments
  6541. ------------------------------------------------------------------------------------------------------------------*/
  6542. // Does everything necessary to display the given events onto the current view
  6543. displayEvents: function(events) {
  6544. var scrollState = this.queryScroll();
  6545. this.clearEvents();
  6546. this.renderEvents(events);
  6547. this.isEventsRendered = true;
  6548. this.setScroll(scrollState);
  6549. this.triggerEventRender();
  6550. },
  6551. // Does everything necessary to clear the view's currently-rendered events
  6552. clearEvents: function() {
  6553. var scrollState;
  6554. if (this.isEventsRendered) {
  6555. // TODO: optimize: if we know this is part of a displayEvents call, don't queryScroll/setScroll
  6556. scrollState = this.queryScroll();
  6557. this.triggerEventUnrender();
  6558. if (this.destroyEvents) {
  6559. this.destroyEvents(); // TODO: deprecate
  6560. }
  6561. this.unrenderEvents();
  6562. this.setScroll(scrollState);
  6563. this.isEventsRendered = false;
  6564. }
  6565. },
  6566. // Renders the events onto the view.
  6567. renderEvents: function(events) {
  6568. // subclasses should implement
  6569. },
  6570. // Removes event elements from the view.
  6571. unrenderEvents: function() {
  6572. // subclasses should implement
  6573. },
  6574. // Signals that all events have been rendered
  6575. triggerEventRender: function() {
  6576. this.renderedEventSegEach(function(seg) {
  6577. this.trigger('eventAfterRender', seg.event, seg.event, seg.el);
  6578. });
  6579. this.trigger('eventAfterAllRender');
  6580. },
  6581. // Signals that all event elements are about to be removed
  6582. triggerEventUnrender: function() {
  6583. this.renderedEventSegEach(function(seg) {
  6584. this.trigger('eventDestroy', seg.event, seg.event, seg.el);
  6585. });
  6586. },
  6587. // Given an event and the default element used for rendering, returns the element that should actually be used.
  6588. // Basically runs events and elements through the eventRender hook.
  6589. resolveEventEl: function(event, el) {
  6590. var custom = this.trigger('eventRender', event, event, el);
  6591. if (custom === false) { // means don't render at all
  6592. el = null;
  6593. }
  6594. else if (custom && custom !== true) {
  6595. el = $(custom);
  6596. }
  6597. return el;
  6598. },
  6599. // Hides all rendered event segments linked to the given event
  6600. showEvent: function(event) {
  6601. this.renderedEventSegEach(function(seg) {
  6602. seg.el.css('visibility', '');
  6603. }, event);
  6604. },
  6605. // Shows all rendered event segments linked to the given event
  6606. hideEvent: function(event) {
  6607. this.renderedEventSegEach(function(seg) {
  6608. seg.el.css('visibility', 'hidden');
  6609. }, event);
  6610. },
  6611. // Iterates through event segments that have been rendered (have an el). Goes through all by default.
  6612. // If the optional `event` argument is specified, only iterates through segments linked to that event.
  6613. // The `this` value of the callback function will be the view.
  6614. renderedEventSegEach: function(func, event) {
  6615. var segs = this.getEventSegs();
  6616. var i;
  6617. for (i = 0; i < segs.length; i++) {
  6618. if (!event || segs[i].event._id === event._id) {
  6619. if (segs[i].el) {
  6620. func.call(this, segs[i]);
  6621. }
  6622. }
  6623. }
  6624. },
  6625. // Retrieves all the rendered segment objects for the view
  6626. getEventSegs: function() {
  6627. // subclasses must implement
  6628. return [];
  6629. },
  6630. /* Event Drag-n-Drop
  6631. ------------------------------------------------------------------------------------------------------------------*/
  6632. // Computes if the given event is allowed to be dragged by the user
  6633. isEventDraggable: function(event) {
  6634. var source = event.source || {};
  6635. return firstDefined(
  6636. event.startEditable,
  6637. source.startEditable,
  6638. this.opt('eventStartEditable'),
  6639. event.editable,
  6640. source.editable,
  6641. this.opt('editable')
  6642. );
  6643. },
  6644. // Must be called when an event in the view is dropped onto new location.
  6645. // `dropLocation` is an object that contains the new zoned start/end/allDay values for the event.
  6646. reportEventDrop: function(event, dropLocation, largeUnit, el, ev) {
  6647. var calendar = this.calendar;
  6648. var mutateResult = calendar.mutateEvent(event, dropLocation, largeUnit);
  6649. var undoFunc = function() {
  6650. mutateResult.undo();
  6651. calendar.reportEventChange();
  6652. };
  6653. this.triggerEventDrop(event, mutateResult.dateDelta, undoFunc, el, ev);
  6654. calendar.reportEventChange(); // will rerender events
  6655. },
  6656. // Triggers event-drop handlers that have subscribed via the API
  6657. triggerEventDrop: function(event, dateDelta, undoFunc, el, ev) {
  6658. this.trigger('eventDrop', el[0], event, dateDelta, undoFunc, ev, {}); // {} = jqui dummy
  6659. },
  6660. /* External Element Drag-n-Drop
  6661. ------------------------------------------------------------------------------------------------------------------*/
  6662. // Must be called when an external element, via jQuery UI, has been dropped onto the calendar.
  6663. // `meta` is the parsed data that has been embedded into the dragging event.
  6664. // `dropLocation` is an object that contains the new zoned start/end/allDay values for the event.
  6665. reportExternalDrop: function(meta, dropLocation, el, ev, ui) {
  6666. var eventProps = meta.eventProps;
  6667. var eventInput;
  6668. var event;
  6669. // Try to build an event object and render it. TODO: decouple the two
  6670. if (eventProps) {
  6671. eventInput = $.extend({}, eventProps, dropLocation);
  6672. event = this.calendar.renderEvent(eventInput, meta.stick)[0]; // renderEvent returns an array
  6673. }
  6674. this.triggerExternalDrop(event, dropLocation, el, ev, ui);
  6675. },
  6676. // Triggers external-drop handlers that have subscribed via the API
  6677. triggerExternalDrop: function(event, dropLocation, el, ev, ui) {
  6678. // trigger 'drop' regardless of whether element represents an event
  6679. this.trigger('drop', el[0], dropLocation.start, ev, ui);
  6680. if (event) {
  6681. this.trigger('eventReceive', null, event); // signal an external event landed
  6682. }
  6683. },
  6684. /* Drag-n-Drop Rendering (for both events and external elements)
  6685. ------------------------------------------------------------------------------------------------------------------*/
  6686. // Renders a visual indication of a event or external-element drag over the given drop zone.
  6687. // If an external-element, seg will be `null`.
  6688. // Must return elements used for any mock events.
  6689. renderDrag: function(dropLocation, seg) {
  6690. // subclasses must implement
  6691. },
  6692. // Unrenders a visual indication of an event or external-element being dragged.
  6693. unrenderDrag: function() {
  6694. // subclasses must implement
  6695. },
  6696. /* Event Resizing
  6697. ------------------------------------------------------------------------------------------------------------------*/
  6698. // Computes if the given event is allowed to be resized from its starting edge
  6699. isEventResizableFromStart: function(event) {
  6700. return this.opt('eventResizableFromStart') && this.isEventResizable(event);
  6701. },
  6702. // Computes if the given event is allowed to be resized from its ending edge
  6703. isEventResizableFromEnd: function(event) {
  6704. return this.isEventResizable(event);
  6705. },
  6706. // Computes if the given event is allowed to be resized by the user at all
  6707. isEventResizable: function(event) {
  6708. var source = event.source || {};
  6709. return firstDefined(
  6710. event.durationEditable,
  6711. source.durationEditable,
  6712. this.opt('eventDurationEditable'),
  6713. event.editable,
  6714. source.editable,
  6715. this.opt('editable')
  6716. );
  6717. },
  6718. // Must be called when an event in the view has been resized to a new length
  6719. reportEventResize: function(event, resizeLocation, largeUnit, el, ev) {
  6720. var calendar = this.calendar;
  6721. var mutateResult = calendar.mutateEvent(event, resizeLocation, largeUnit);
  6722. var undoFunc = function() {
  6723. mutateResult.undo();
  6724. calendar.reportEventChange();
  6725. };
  6726. this.triggerEventResize(event, mutateResult.durationDelta, undoFunc, el, ev);
  6727. calendar.reportEventChange(); // will rerender events
  6728. },
  6729. // Triggers event-resize handlers that have subscribed via the API
  6730. triggerEventResize: function(event, durationDelta, undoFunc, el, ev) {
  6731. this.trigger('eventResize', el[0], event, durationDelta, undoFunc, ev, {}); // {} = jqui dummy
  6732. },
  6733. /* Selection (time range)
  6734. ------------------------------------------------------------------------------------------------------------------*/
  6735. // Selects a date span on the view. `start` and `end` are both Moments.
  6736. // `ev` is the native mouse event that begin the interaction.
  6737. select: function(span, ev) {
  6738. this.unselect(ev);
  6739. this.renderSelection(span);
  6740. this.reportSelection(span, ev);
  6741. },
  6742. // Renders a visual indication of the selection
  6743. renderSelection: function(span) {
  6744. // subclasses should implement
  6745. },
  6746. // Called when a new selection is made. Updates internal state and triggers handlers.
  6747. reportSelection: function(span, ev) {
  6748. this.isSelected = true;
  6749. this.triggerSelect(span, ev);
  6750. },
  6751. // Triggers handlers to 'select'
  6752. triggerSelect: function(span, ev) {
  6753. this.trigger(
  6754. 'select',
  6755. null,
  6756. this.calendar.applyTimezone(span.start), // convert to calendar's tz for external API
  6757. this.calendar.applyTimezone(span.end), // "
  6758. ev
  6759. );
  6760. },
  6761. // Undoes a selection. updates in the internal state and triggers handlers.
  6762. // `ev` is the native mouse event that began the interaction.
  6763. unselect: function(ev) {
  6764. if (this.isSelected) {
  6765. this.isSelected = false;
  6766. if (this.destroySelection) {
  6767. this.destroySelection(); // TODO: deprecate
  6768. }
  6769. this.unrenderSelection();
  6770. this.trigger('unselect', null, ev);
  6771. }
  6772. },
  6773. // Unrenders a visual indication of selection
  6774. unrenderSelection: function() {
  6775. // subclasses should implement
  6776. },
  6777. /* Event Selection
  6778. ------------------------------------------------------------------------------------------------------------------*/
  6779. selectEvent: function(event) {
  6780. if (!this.selectedEvent || this.selectedEvent !== event) {
  6781. this.unselectEvent();
  6782. this.renderedEventSegEach(function(seg) {
  6783. seg.el.addClass('fc-selected');
  6784. }, event);
  6785. this.selectedEvent = event;
  6786. }
  6787. },
  6788. unselectEvent: function() {
  6789. if (this.selectedEvent) {
  6790. this.renderedEventSegEach(function(seg) {
  6791. seg.el.removeClass('fc-selected');
  6792. }, this.selectedEvent);
  6793. this.selectedEvent = null;
  6794. }
  6795. },
  6796. isEventSelected: function(event) {
  6797. // event references might change on refetchEvents(), while selectedEvent doesn't,
  6798. // so compare IDs
  6799. return this.selectedEvent && this.selectedEvent._id === event._id;
  6800. },
  6801. /* Mouse / Touch Unselecting (time range & event unselection)
  6802. ------------------------------------------------------------------------------------------------------------------*/
  6803. // TODO: move consistently to down/start or up/end?
  6804. // TODO: don't kill previous selection if touch scrolling
  6805. handleDocumentMousedown: function(ev) {
  6806. if (isPrimaryMouseButton(ev)) {
  6807. this.processUnselect(ev);
  6808. }
  6809. },
  6810. processUnselect: function(ev) {
  6811. this.processRangeUnselect(ev);
  6812. this.processEventUnselect(ev);
  6813. },
  6814. processRangeUnselect: function(ev) {
  6815. var ignore;
  6816. // is there a time-range selection?
  6817. if (this.isSelected && this.opt('unselectAuto')) {
  6818. // only unselect if the clicked element is not identical to or inside of an 'unselectCancel' element
  6819. ignore = this.opt('unselectCancel');
  6820. if (!ignore || !$(ev.target).closest(ignore).length) {
  6821. this.unselect(ev);
  6822. }
  6823. }
  6824. },
  6825. processEventUnselect: function(ev) {
  6826. if (this.selectedEvent) {
  6827. if (!$(ev.target).closest('.fc-selected').length) {
  6828. this.unselectEvent();
  6829. }
  6830. }
  6831. },
  6832. /* Day Click
  6833. ------------------------------------------------------------------------------------------------------------------*/
  6834. // Triggers handlers to 'dayClick'
  6835. // Span has start/end of the clicked area. Only the start is useful.
  6836. triggerDayClick: function(span, dayEl, ev) {
  6837. this.trigger(
  6838. 'dayClick',
  6839. dayEl,
  6840. this.calendar.applyTimezone(span.start), // convert to calendar's timezone for external API
  6841. ev
  6842. );
  6843. },
  6844. /* Date Utils
  6845. ------------------------------------------------------------------------------------------------------------------*/
  6846. // Initializes internal variables related to calculating hidden days-of-week
  6847. initHiddenDays: function() {
  6848. var hiddenDays = this.opt('hiddenDays') || []; // array of day-of-week indices that are hidden
  6849. var isHiddenDayHash = []; // is the day-of-week hidden? (hash with day-of-week-index -> bool)
  6850. var dayCnt = 0;
  6851. var i;
  6852. if (this.opt('weekends') === false) {
  6853. hiddenDays.push(0, 6); // 0=sunday, 6=saturday
  6854. }
  6855. for (i = 0; i < 7; i++) {
  6856. if (
  6857. !(isHiddenDayHash[i] = $.inArray(i, hiddenDays) !== -1)
  6858. ) {
  6859. dayCnt++;
  6860. }
  6861. }
  6862. if (!dayCnt) {
  6863. throw 'invalid hiddenDays'; // all days were hidden? bad.
  6864. }
  6865. this.isHiddenDayHash = isHiddenDayHash;
  6866. },
  6867. // Is the current day hidden?
  6868. // `day` is a day-of-week index (0-6), or a Moment
  6869. isHiddenDay: function(day) {
  6870. if (moment.isMoment(day)) {
  6871. day = day.day();
  6872. }
  6873. return this.isHiddenDayHash[day];
  6874. },
  6875. // Incrementing the current day until it is no longer a hidden day, returning a copy.
  6876. // If the initial value of `date` is not a hidden day, don't do anything.
  6877. // Pass `isExclusive` as `true` if you are dealing with an end date.
  6878. // `inc` defaults to `1` (increment one day forward each time)
  6879. skipHiddenDays: function(date, inc, isExclusive) {
  6880. var out = date.clone();
  6881. inc = inc || 1;
  6882. while (
  6883. this.isHiddenDayHash[(out.day() + (isExclusive ? inc : 0) + 7) % 7]
  6884. ) {
  6885. out.add(inc, 'days');
  6886. }
  6887. return out;
  6888. },
  6889. // Returns the date range of the full days the given range visually appears to occupy.
  6890. // Returns a new range object.
  6891. computeDayRange: function(range) {
  6892. var startDay = range.start.clone().stripTime(); // the beginning of the day the range starts
  6893. var end = range.end;
  6894. var endDay = null;
  6895. var endTimeMS;
  6896. if (end) {
  6897. endDay = end.clone().stripTime(); // the beginning of the day the range exclusively ends
  6898. endTimeMS = +end.time(); // # of milliseconds into `endDay`
  6899. // If the end time is actually inclusively part of the next day and is equal to or
  6900. // beyond the next day threshold, adjust the end to be the exclusive end of `endDay`.
  6901. // Otherwise, leaving it as inclusive will cause it to exclude `endDay`.
  6902. if (endTimeMS && endTimeMS >= this.nextDayThreshold) {
  6903. endDay.add(1, 'days');
  6904. }
  6905. }
  6906. // If no end was specified, or if it is within `startDay` but not past nextDayThreshold,
  6907. // assign the default duration of one day.
  6908. if (!end || endDay <= startDay) {
  6909. endDay = startDay.clone().add(1, 'days');
  6910. }
  6911. return { start: startDay, end: endDay };
  6912. },
  6913. // Does the given event visually appear to occupy more than one day?
  6914. isMultiDayEvent: function(event) {
  6915. var range = this.computeDayRange(event); // event is range-ish
  6916. return range.end.diff(range.start, 'days') > 1;
  6917. }
  6918. });
  6919. ;;
  6920. /*
  6921. Embodies a div that has potential scrollbars
  6922. */
  6923. var Scroller = FC.Scroller = Class.extend({
  6924. el: null, // the guaranteed outer element
  6925. scrollEl: null, // the element with the scrollbars
  6926. overflowX: null,
  6927. overflowY: null,
  6928. constructor: function(options) {
  6929. options = options || {};
  6930. this.overflowX = options.overflowX || options.overflow || 'auto';
  6931. this.overflowY = options.overflowY || options.overflow || 'auto';
  6932. },
  6933. render: function() {
  6934. this.el = this.renderEl();
  6935. this.applyOverflow();
  6936. },
  6937. renderEl: function() {
  6938. return (this.scrollEl = $('<div class="fc-scroller"></div>'));
  6939. },
  6940. // sets to natural height, unlocks overflow
  6941. clear: function() {
  6942. this.setHeight('auto');
  6943. this.applyOverflow();
  6944. },
  6945. destroy: function() {
  6946. this.el.remove();
  6947. },
  6948. // Overflow
  6949. // -----------------------------------------------------------------------------------------------------------------
  6950. applyOverflow: function() {
  6951. this.scrollEl.css({
  6952. 'overflow-x': this.overflowX,
  6953. 'overflow-y': this.overflowY
  6954. });
  6955. },
  6956. // Causes any 'auto' overflow values to resolves to 'scroll' or 'hidden'.
  6957. // Useful for preserving scrollbar widths regardless of future resizes.
  6958. // Can pass in scrollbarWidths for optimization.
  6959. lockOverflow: function(scrollbarWidths) {
  6960. var overflowX = this.overflowX;
  6961. var overflowY = this.overflowY;
  6962. scrollbarWidths = scrollbarWidths || this.getScrollbarWidths();
  6963. if (overflowX === 'auto') {
  6964. overflowX = (
  6965. scrollbarWidths.top || scrollbarWidths.bottom || // horizontal scrollbars?
  6966. // OR scrolling pane with massless scrollbars?
  6967. this.scrollEl[0].scrollWidth - 1 > this.scrollEl[0].clientWidth
  6968. // subtract 1 because of IE off-by-one issue
  6969. ) ? 'scroll' : 'hidden';
  6970. }
  6971. if (overflowY === 'auto') {
  6972. overflowY = (
  6973. scrollbarWidths.left || scrollbarWidths.right || // vertical scrollbars?
  6974. // OR scrolling pane with massless scrollbars?
  6975. this.scrollEl[0].scrollHeight - 1 > this.scrollEl[0].clientHeight
  6976. // subtract 1 because of IE off-by-one issue
  6977. ) ? 'scroll' : 'hidden';
  6978. }
  6979. this.scrollEl.css({ 'overflow-x': overflowX, 'overflow-y': overflowY });
  6980. },
  6981. // Getters / Setters
  6982. // -----------------------------------------------------------------------------------------------------------------
  6983. setHeight: function(height) {
  6984. this.scrollEl.height(height);
  6985. },
  6986. getScrollTop: function() {
  6987. return this.scrollEl.scrollTop();
  6988. },
  6989. setScrollTop: function(top) {
  6990. this.scrollEl.scrollTop(top);
  6991. },
  6992. getClientWidth: function() {
  6993. return this.scrollEl[0].clientWidth;
  6994. },
  6995. getClientHeight: function() {
  6996. return this.scrollEl[0].clientHeight;
  6997. },
  6998. getScrollbarWidths: function() {
  6999. return getScrollbarWidths(this.scrollEl);
  7000. }
  7001. });
  7002. ;;
  7003. var Calendar = FC.Calendar = Class.extend({
  7004. dirDefaults: null, // option defaults related to LTR or RTL
  7005. langDefaults: null, // option defaults related to current locale
  7006. overrides: null, // option overrides given to the fullCalendar constructor
  7007. dynamicOverrides: null, // options set with dynamic setter method. higher precedence than view overrides.
  7008. options: null, // all defaults combined with overrides
  7009. viewSpecCache: null, // cache of view definitions
  7010. view: null, // current View object
  7011. header: null,
  7012. loadingLevel: 0, // number of simultaneous loading tasks
  7013. // a lot of this class' OOP logic is scoped within this constructor function,
  7014. // but in the future, write individual methods on the prototype.
  7015. constructor: Calendar_constructor,
  7016. // Subclasses can override this for initialization logic after the constructor has been called
  7017. initialize: function() {
  7018. },
  7019. // Computes the flattened options hash for the calendar and assigns to `this.options`.
  7020. // Assumes this.overrides and this.dynamicOverrides have already been initialized.
  7021. populateOptionsHash: function() {
  7022. var lang, langDefaults;
  7023. var isRTL, dirDefaults;
  7024. lang = firstDefined( // explicit lang option given?
  7025. this.dynamicOverrides.lang,
  7026. this.overrides.lang
  7027. );
  7028. langDefaults = langOptionHash[lang];
  7029. if (!langDefaults) { // explicit lang option not given or invalid?
  7030. lang = Calendar.defaults.lang;
  7031. langDefaults = langOptionHash[lang] || {};
  7032. }
  7033. isRTL = firstDefined( // based on options computed so far, is direction RTL?
  7034. this.dynamicOverrides.isRTL,
  7035. this.overrides.isRTL,
  7036. langDefaults.isRTL,
  7037. Calendar.defaults.isRTL
  7038. );
  7039. dirDefaults = isRTL ? Calendar.rtlDefaults : {};
  7040. this.dirDefaults = dirDefaults;
  7041. this.langDefaults = langDefaults;
  7042. this.options = mergeOptions([ // merge defaults and overrides. lowest to highest precedence
  7043. Calendar.defaults, // global defaults
  7044. dirDefaults,
  7045. langDefaults,
  7046. this.overrides,
  7047. this.dynamicOverrides
  7048. ]);
  7049. populateInstanceComputableOptions(this.options); // fill in gaps with computed options
  7050. },
  7051. // Gets information about how to create a view. Will use a cache.
  7052. getViewSpec: function(viewType) {
  7053. var cache = this.viewSpecCache;
  7054. return cache[viewType] || (cache[viewType] = this.buildViewSpec(viewType));
  7055. },
  7056. // Given a duration singular unit, like "week" or "day", finds a matching view spec.
  7057. // Preference is given to views that have corresponding buttons.
  7058. getUnitViewSpec: function(unit) {
  7059. var viewTypes;
  7060. var i;
  7061. var spec;
  7062. if ($.inArray(unit, intervalUnits) != -1) {
  7063. // put views that have buttons first. there will be duplicates, but oh well
  7064. viewTypes = this.header.getViewsWithButtons();
  7065. $.each(FC.views, function(viewType) { // all views
  7066. viewTypes.push(viewType);
  7067. });
  7068. for (i = 0; i < viewTypes.length; i++) {
  7069. spec = this.getViewSpec(viewTypes[i]);
  7070. if (spec) {
  7071. if (spec.singleUnit == unit) {
  7072. return spec;
  7073. }
  7074. }
  7075. }
  7076. }
  7077. },
  7078. // Builds an object with information on how to create a given view
  7079. buildViewSpec: function(requestedViewType) {
  7080. var viewOverrides = this.overrides.views || {};
  7081. var specChain = []; // for the view. lowest to highest priority
  7082. var defaultsChain = []; // for the view. lowest to highest priority
  7083. var overridesChain = []; // for the view. lowest to highest priority
  7084. var viewType = requestedViewType;
  7085. var spec; // for the view
  7086. var overrides; // for the view
  7087. var duration;
  7088. var unit;
  7089. // iterate from the specific view definition to a more general one until we hit an actual View class
  7090. while (viewType) {
  7091. spec = fcViews[viewType];
  7092. overrides = viewOverrides[viewType];
  7093. viewType = null; // clear. might repopulate for another iteration
  7094. if (typeof spec === 'function') { // TODO: deprecate
  7095. spec = { 'class': spec };
  7096. }
  7097. if (spec) {
  7098. specChain.unshift(spec);
  7099. defaultsChain.unshift(spec.defaults || {});
  7100. duration = duration || spec.duration;
  7101. viewType = viewType || spec.type;
  7102. }
  7103. if (overrides) {
  7104. overridesChain.unshift(overrides); // view-specific option hashes have options at zero-level
  7105. duration = duration || overrides.duration;
  7106. viewType = viewType || overrides.type;
  7107. }
  7108. }
  7109. spec = mergeProps(specChain);
  7110. spec.type = requestedViewType;
  7111. if (!spec['class']) {
  7112. return false;
  7113. }
  7114. if (duration) {
  7115. duration = moment.duration(duration);
  7116. if (duration.valueOf()) { // valid?
  7117. spec.duration = duration;
  7118. unit = computeIntervalUnit(duration);
  7119. // view is a single-unit duration, like "week" or "day"
  7120. // incorporate options for this. lowest priority
  7121. if (duration.as(unit) === 1) {
  7122. spec.singleUnit = unit;
  7123. overridesChain.unshift(viewOverrides[unit] || {});
  7124. }
  7125. }
  7126. }
  7127. spec.defaults = mergeOptions(defaultsChain);
  7128. spec.overrides = mergeOptions(overridesChain);
  7129. this.buildViewSpecOptions(spec);
  7130. this.buildViewSpecButtonText(spec, requestedViewType);
  7131. return spec;
  7132. },
  7133. // Builds and assigns a view spec's options object from its already-assigned defaults and overrides
  7134. buildViewSpecOptions: function(spec) {
  7135. spec.options = mergeOptions([ // lowest to highest priority
  7136. Calendar.defaults, // global defaults
  7137. spec.defaults, // view's defaults (from ViewSubclass.defaults)
  7138. this.dirDefaults,
  7139. this.langDefaults, // locale and dir take precedence over view's defaults!
  7140. this.overrides, // calendar's overrides (options given to constructor)
  7141. spec.overrides, // view's overrides (view-specific options)
  7142. this.dynamicOverrides // dynamically set via setter. highest precedence
  7143. ]);
  7144. populateInstanceComputableOptions(spec.options);
  7145. },
  7146. // Computes and assigns a view spec's buttonText-related options
  7147. buildViewSpecButtonText: function(spec, requestedViewType) {
  7148. // given an options object with a possible `buttonText` hash, lookup the buttonText for the
  7149. // requested view, falling back to a generic unit entry like "week" or "day"
  7150. function queryButtonText(options) {
  7151. var buttonText = options.buttonText || {};
  7152. return buttonText[requestedViewType] ||
  7153. (spec.singleUnit ? buttonText[spec.singleUnit] : null);
  7154. }
  7155. // highest to lowest priority
  7156. spec.buttonTextOverride =
  7157. queryButtonText(this.dynamicOverrides) ||
  7158. queryButtonText(this.overrides) || // constructor-specified buttonText lookup hash takes precedence
  7159. spec.overrides.buttonText; // `buttonText` for view-specific options is a string
  7160. // highest to lowest priority. mirrors buildViewSpecOptions
  7161. spec.buttonTextDefault =
  7162. queryButtonText(this.langDefaults) ||
  7163. queryButtonText(this.dirDefaults) ||
  7164. spec.defaults.buttonText || // a single string. from ViewSubclass.defaults
  7165. queryButtonText(Calendar.defaults) ||
  7166. (spec.duration ? this.humanizeDuration(spec.duration) : null) || // like "3 days"
  7167. requestedViewType; // fall back to given view name
  7168. },
  7169. // Given a view name for a custom view or a standard view, creates a ready-to-go View object
  7170. instantiateView: function(viewType) {
  7171. var spec = this.getViewSpec(viewType);
  7172. return new spec['class'](this, viewType, spec.options, spec.duration);
  7173. },
  7174. // Returns a boolean about whether the view is okay to instantiate at some point
  7175. isValidViewType: function(viewType) {
  7176. return Boolean(this.getViewSpec(viewType));
  7177. },
  7178. // Should be called when any type of async data fetching begins
  7179. pushLoading: function() {
  7180. if (!(this.loadingLevel++)) {
  7181. this.trigger('loading', null, true, this.view);
  7182. }
  7183. },
  7184. // Should be called when any type of async data fetching completes
  7185. popLoading: function() {
  7186. if (!(--this.loadingLevel)) {
  7187. this.trigger('loading', null, false, this.view);
  7188. }
  7189. },
  7190. // Given arguments to the select method in the API, returns a span (unzoned start/end and other info)
  7191. buildSelectSpan: function(zonedStartInput, zonedEndInput) {
  7192. var start = this.moment(zonedStartInput).stripZone();
  7193. var end;
  7194. if (zonedEndInput) {
  7195. end = this.moment(zonedEndInput).stripZone();
  7196. }
  7197. else if (start.hasTime()) {
  7198. end = start.clone().add(this.defaultTimedEventDuration);
  7199. }
  7200. else {
  7201. end = start.clone().add(this.defaultAllDayEventDuration);
  7202. }
  7203. return { start: start, end: end };
  7204. }
  7205. });
  7206. Calendar.mixin(EmitterMixin);
  7207. function Calendar_constructor(element, overrides) {
  7208. var t = this;
  7209. // Exports
  7210. // -----------------------------------------------------------------------------------
  7211. t.render = render;
  7212. t.destroy = destroy;
  7213. t.refetchEvents = refetchEvents;
  7214. t.refetchEventSources = refetchEventSources;
  7215. t.reportEvents = reportEvents;
  7216. t.reportEventChange = reportEventChange;
  7217. t.rerenderEvents = renderEvents; // `renderEvents` serves as a rerender. an API method
  7218. t.changeView = renderView; // `renderView` will switch to another view
  7219. t.select = select;
  7220. t.unselect = unselect;
  7221. t.prev = prev;
  7222. t.next = next;
  7223. t.prevYear = prevYear;
  7224. t.nextYear = nextYear;
  7225. t.today = today;
  7226. t.gotoDate = gotoDate;
  7227. t.incrementDate = incrementDate;
  7228. t.zoomTo = zoomTo;
  7229. t.getDate = getDate;
  7230. t.getCalendar = getCalendar;
  7231. t.getView = getView;
  7232. t.option = option; // getter/setter method
  7233. t.trigger = trigger;
  7234. // Options
  7235. // -----------------------------------------------------------------------------------
  7236. t.dynamicOverrides = {};
  7237. t.viewSpecCache = {};
  7238. t.optionHandlers = {}; // for Calendar.options.js
  7239. // convert legacy options into non-legacy ones.
  7240. // in the future, when this is removed, don't use `overrides` reference. make a copy.
  7241. t.overrides = massageOverrides(overrides || {});
  7242. t.populateOptionsHash(); // sets this.options
  7243. // Language-data Internals
  7244. // -----------------------------------------------------------------------------------
  7245. // Apply overrides to the current language's data
  7246. var localeData;
  7247. // Called immediately, and when any of the options change.
  7248. // Happens before any internal objects rebuild or rerender, because this is very core.
  7249. t.bindOptions([
  7250. 'lang', 'monthNames', 'monthNamesShort', 'dayNames', 'dayNamesShort', 'firstDay', 'weekNumberCalculation'
  7251. ], function(lang, monthNames, monthNamesShort, dayNames, dayNamesShort, firstDay, weekNumberCalculation) {
  7252. localeData = createObject( // make a cheap copy
  7253. getMomentLocaleData(lang) // will fall back to en
  7254. );
  7255. if (monthNames) {
  7256. localeData._months = monthNames;
  7257. }
  7258. if (monthNamesShort) {
  7259. localeData._monthsShort = monthNamesShort;
  7260. }
  7261. if (dayNames) {
  7262. localeData._weekdays = dayNames;
  7263. }
  7264. if (dayNamesShort) {
  7265. localeData._weekdaysShort = dayNamesShort;
  7266. }
  7267. if (firstDay != null) {
  7268. var _week = createObject(localeData._week); // _week: { dow: # }
  7269. _week.dow = firstDay;
  7270. localeData._week = _week;
  7271. }
  7272. if (weekNumberCalculation === 'iso') {
  7273. weekNumberCalculation = 'ISO'; // normalize
  7274. }
  7275. if ( // whitelist certain kinds of input
  7276. weekNumberCalculation === 'ISO' ||
  7277. weekNumberCalculation === 'local' ||
  7278. typeof weekNumberCalculation === 'function'
  7279. ) {
  7280. localeData._fullCalendar_weekCalc = weekNumberCalculation; // moment-ext will know what to do with it
  7281. }
  7282. // If the internal current date object already exists, move to new locale.
  7283. // We do NOT need to do this technique for event dates, because this happens when converting to "segments".
  7284. if (date) {
  7285. localizeMoment(date); // sets to localeData
  7286. }
  7287. });
  7288. // Calendar-specific Date Utilities
  7289. // -----------------------------------------------------------------------------------
  7290. t.defaultAllDayEventDuration = moment.duration(t.options.defaultAllDayEventDuration);
  7291. t.defaultTimedEventDuration = moment.duration(t.options.defaultTimedEventDuration);
  7292. // Builds a moment using the settings of the current calendar: timezone and language.
  7293. // Accepts anything the vanilla moment() constructor accepts.
  7294. t.moment = function() {
  7295. var mom;
  7296. if (t.options.timezone === 'local') {
  7297. mom = FC.moment.apply(null, arguments);
  7298. // Force the moment to be local, because FC.moment doesn't guarantee it.
  7299. if (mom.hasTime()) { // don't give ambiguously-timed moments a local zone
  7300. mom.local();
  7301. }
  7302. }
  7303. else if (t.options.timezone === 'UTC') {
  7304. mom = FC.moment.utc.apply(null, arguments); // process as UTC
  7305. }
  7306. else {
  7307. mom = FC.moment.parseZone.apply(null, arguments); // let the input decide the zone
  7308. }
  7309. localizeMoment(mom);
  7310. return mom;
  7311. };
  7312. // Updates the given moment's locale settings to the current calendar locale settings.
  7313. function localizeMoment(mom) {
  7314. if ('_locale' in mom) { // moment 2.8 and above
  7315. mom._locale = localeData;
  7316. }
  7317. else { // pre-moment-2.8
  7318. mom._lang = localeData;
  7319. }
  7320. }
  7321. // Returns a boolean about whether or not the calendar knows how to calculate
  7322. // the timezone offset of arbitrary dates in the current timezone.
  7323. t.getIsAmbigTimezone = function() {
  7324. return t.options.timezone !== 'local' && t.options.timezone !== 'UTC';
  7325. };
  7326. // Returns a copy of the given date in the current timezone. Has no effect on dates without times.
  7327. t.applyTimezone = function(date) {
  7328. if (!date.hasTime()) {
  7329. return date.clone();
  7330. }
  7331. var zonedDate = t.moment(date.toArray());
  7332. var timeAdjust = date.time() - zonedDate.time();
  7333. var adjustedZonedDate;
  7334. // Safari sometimes has problems with this coersion when near DST. Adjust if necessary. (bug #2396)
  7335. if (timeAdjust) { // is the time result different than expected?
  7336. adjustedZonedDate = zonedDate.clone().add(timeAdjust); // add milliseconds
  7337. if (date.time() - adjustedZonedDate.time() === 0) { // does it match perfectly now?
  7338. zonedDate = adjustedZonedDate;
  7339. }
  7340. }
  7341. return zonedDate;
  7342. };
  7343. // Returns a moment for the current date, as defined by the client's computer or from the `now` option.
  7344. // Will return an moment with an ambiguous timezone.
  7345. t.getNow = function() {
  7346. var now = t.options.now;
  7347. if (typeof now === 'function') {
  7348. now = now();
  7349. }
  7350. return t.moment(now).stripZone();
  7351. };
  7352. // Get an event's normalized end date. If not present, calculate it from the defaults.
  7353. t.getEventEnd = function(event) {
  7354. if (event.end) {
  7355. return event.end.clone();
  7356. }
  7357. else {
  7358. return t.getDefaultEventEnd(event.allDay, event.start);
  7359. }
  7360. };
  7361. // Given an event's allDay status and start date, return what its fallback end date should be.
  7362. // TODO: rename to computeDefaultEventEnd
  7363. t.getDefaultEventEnd = function(allDay, zonedStart) {
  7364. var end = zonedStart.clone();
  7365. if (allDay) {
  7366. end.stripTime().add(t.defaultAllDayEventDuration);
  7367. }
  7368. else {
  7369. end.add(t.defaultTimedEventDuration);
  7370. }
  7371. if (t.getIsAmbigTimezone()) {
  7372. end.stripZone(); // we don't know what the tzo should be
  7373. }
  7374. return end;
  7375. };
  7376. // Produces a human-readable string for the given duration.
  7377. // Side-effect: changes the locale of the given duration.
  7378. t.humanizeDuration = function(duration) {
  7379. return (duration.locale || duration.lang).call(duration, t.options.lang) // works moment-pre-2.8
  7380. .humanize();
  7381. };
  7382. // Imports
  7383. // -----------------------------------------------------------------------------------
  7384. EventManager.call(t);
  7385. var isFetchNeeded = t.isFetchNeeded;
  7386. var fetchEvents = t.fetchEvents;
  7387. var fetchEventSources = t.fetchEventSources;
  7388. // Locals
  7389. // -----------------------------------------------------------------------------------
  7390. var _element = element[0];
  7391. var header;
  7392. var content;
  7393. var tm; // for making theme classes
  7394. var currentView; // NOTE: keep this in sync with this.view
  7395. var viewsByType = {}; // holds all instantiated view instances, current or not
  7396. var suggestedViewHeight;
  7397. var windowResizeProxy; // wraps the windowResize function
  7398. var ignoreWindowResize = 0;
  7399. var events = [];
  7400. var date; // unzoned
  7401. // Main Rendering
  7402. // -----------------------------------------------------------------------------------
  7403. // compute the initial ambig-timezone date
  7404. if (t.options.defaultDate != null) {
  7405. date = t.moment(t.options.defaultDate).stripZone();
  7406. }
  7407. else {
  7408. date = t.getNow(); // getNow already returns unzoned
  7409. }
  7410. function render() {
  7411. if (!content) {
  7412. initialRender();
  7413. }
  7414. else if (elementVisible()) {
  7415. // mainly for the public API
  7416. calcSize();
  7417. renderView();
  7418. }
  7419. }
  7420. function initialRender() {
  7421. element.addClass('fc');
  7422. // called immediately, and upon option change
  7423. t.bindOption('theme', function(theme) {
  7424. tm = theme ? 'ui' : 'fc'; // affects a larger scope
  7425. element.toggleClass('ui-widget', theme);
  7426. element.toggleClass('fc-unthemed', !theme);
  7427. });
  7428. // called immediately, and upon option change.
  7429. // HACK: lang often affects isRTL, so we explicitly listen to that too.
  7430. t.bindOptions([ 'isRTL', 'lang' ], function(isRTL) {
  7431. element.toggleClass('fc-ltr', !isRTL);
  7432. element.toggleClass('fc-rtl', isRTL);
  7433. });
  7434. content = $("<div class='fc-view-container'/>").prependTo(element);
  7435. header = t.header = new Header(t);
  7436. renderHeader();
  7437. renderView(t.options.defaultView);
  7438. if (t.options.handleWindowResize) {
  7439. windowResizeProxy = debounce(windowResize, t.options.windowResizeDelay); // prevents rapid calls
  7440. $(window).resize(windowResizeProxy);
  7441. }
  7442. }
  7443. // can be called repeatedly and Header will rerender
  7444. function renderHeader() {
  7445. header.render();
  7446. if (header.el) {
  7447. element.prepend(header.el);
  7448. }
  7449. }
  7450. function destroy() {
  7451. if (currentView) {
  7452. currentView.removeElement();
  7453. // NOTE: don't null-out currentView/t.view in case API methods are called after destroy.
  7454. // It is still the "current" view, just not rendered.
  7455. }
  7456. header.removeElement();
  7457. content.remove();
  7458. element.removeClass('fc fc-ltr fc-rtl fc-unthemed ui-widget');
  7459. if (windowResizeProxy) {
  7460. $(window).unbind('resize', windowResizeProxy);
  7461. }
  7462. }
  7463. function elementVisible() {
  7464. return element.is(':visible');
  7465. }
  7466. // View Rendering
  7467. // -----------------------------------------------------------------------------------
  7468. // Renders a view because of a date change, view-type change, or for the first time.
  7469. // If not given a viewType, keep the current view but render different dates.
  7470. // Accepts an optional scroll state to restore to.
  7471. function renderView(viewType, explicitScrollState) {
  7472. ignoreWindowResize++;
  7473. // if viewType is changing, remove the old view's rendering
  7474. if (currentView && viewType && currentView.type !== viewType) {
  7475. freezeContentHeight(); // prevent a scroll jump when view element is removed
  7476. clearView();
  7477. }
  7478. // if viewType changed, or the view was never created, create a fresh view
  7479. if (!currentView && viewType) {
  7480. currentView = t.view =
  7481. viewsByType[viewType] ||
  7482. (viewsByType[viewType] = t.instantiateView(viewType));
  7483. currentView.setElement(
  7484. $("<div class='fc-view fc-" + viewType + "-view' />").appendTo(content)
  7485. );
  7486. header.activateButton(viewType);
  7487. }
  7488. if (currentView) {
  7489. // in case the view should render a period of time that is completely hidden
  7490. date = currentView.massageCurrentDate(date);
  7491. // render or rerender the view
  7492. if (
  7493. !currentView.displaying ||
  7494. !date.isWithin(currentView.intervalStart, currentView.intervalEnd) // implicit date window change
  7495. ) {
  7496. if (elementVisible()) {
  7497. currentView.display(date, explicitScrollState); // will call freezeContentHeight
  7498. unfreezeContentHeight(); // immediately unfreeze regardless of whether display is async
  7499. // need to do this after View::render, so dates are calculated
  7500. updateHeaderTitle();
  7501. updateTodayButton();
  7502. getAndRenderEvents();
  7503. }
  7504. }
  7505. }
  7506. unfreezeContentHeight(); // undo any lone freezeContentHeight calls
  7507. ignoreWindowResize--;
  7508. }
  7509. // Unrenders the current view and reflects this change in the Header.
  7510. // Unregsiters the `currentView`, but does not remove from viewByType hash.
  7511. function clearView() {
  7512. header.deactivateButton(currentView.type);
  7513. currentView.removeElement();
  7514. currentView = t.view = null;
  7515. }
  7516. // Destroys the view, including the view object. Then, re-instantiates it and renders it.
  7517. // Maintains the same scroll state.
  7518. // TODO: maintain any other user-manipulated state.
  7519. function reinitView() {
  7520. ignoreWindowResize++;
  7521. freezeContentHeight();
  7522. var viewType = currentView.type;
  7523. var scrollState = currentView.queryScroll();
  7524. clearView();
  7525. renderView(viewType, scrollState);
  7526. unfreezeContentHeight();
  7527. ignoreWindowResize--;
  7528. }
  7529. // Resizing
  7530. // -----------------------------------------------------------------------------------
  7531. t.getSuggestedViewHeight = function() {
  7532. if (suggestedViewHeight === undefined) {
  7533. calcSize();
  7534. }
  7535. return suggestedViewHeight;
  7536. };
  7537. t.isHeightAuto = function() {
  7538. return t.options.contentHeight === 'auto' || t.options.height === 'auto';
  7539. };
  7540. function updateSize(shouldRecalc) {
  7541. if (elementVisible()) {
  7542. if (shouldRecalc) {
  7543. _calcSize();
  7544. }
  7545. ignoreWindowResize++;
  7546. currentView.updateSize(true); // isResize=true. will poll getSuggestedViewHeight() and isHeightAuto()
  7547. ignoreWindowResize--;
  7548. return true; // signal success
  7549. }
  7550. }
  7551. function calcSize() {
  7552. if (elementVisible()) {
  7553. _calcSize();
  7554. }
  7555. }
  7556. function _calcSize() { // assumes elementVisible
  7557. var contentHeightInput = t.options.contentHeight;
  7558. var heightInput = t.options.height;
  7559. if (typeof contentHeightInput === 'number') { // exists and not 'auto'
  7560. suggestedViewHeight = contentHeightInput;
  7561. }
  7562. else if (typeof contentHeightInput === 'function') { // exists and is a function
  7563. suggestedViewHeight = contentHeightInput();
  7564. }
  7565. else if (typeof heightInput === 'number') { // exists and not 'auto'
  7566. suggestedViewHeight = heightInput - queryHeaderHeight();
  7567. }
  7568. else if (typeof heightInput === 'function') { // exists and is a function
  7569. suggestedViewHeight = heightInput() - queryHeaderHeight();
  7570. }
  7571. else if (heightInput === 'parent') { // set to height of parent element
  7572. suggestedViewHeight = element.parent().height() - queryHeaderHeight();
  7573. }
  7574. else {
  7575. suggestedViewHeight = Math.round(content.width() / Math.max(t.options.aspectRatio, .5));
  7576. }
  7577. }
  7578. function queryHeaderHeight() {
  7579. return header.el ? header.el.outerHeight(true) : 0; // includes margin
  7580. }
  7581. function windowResize(ev) {
  7582. if (
  7583. !ignoreWindowResize &&
  7584. ev.target === window && // so we don't process jqui "resize" events that have bubbled up
  7585. currentView.start // view has already been rendered
  7586. ) {
  7587. if (updateSize(true)) {
  7588. currentView.trigger('windowResize', _element);
  7589. }
  7590. }
  7591. }
  7592. /* Event Fetching/Rendering
  7593. -----------------------------------------------------------------------------*/
  7594. // TODO: going forward, most of this stuff should be directly handled by the view
  7595. function refetchEvents() { // can be called as an API method
  7596. fetchAndRenderEvents();
  7597. }
  7598. // TODO: move this into EventManager?
  7599. function refetchEventSources(matchInputs) {
  7600. fetchEventSources(t.getEventSourcesByMatchArray(matchInputs));
  7601. }
  7602. function renderEvents() { // destroys old events if previously rendered
  7603. if (elementVisible()) {
  7604. freezeContentHeight();
  7605. currentView.displayEvents(events);
  7606. unfreezeContentHeight();
  7607. }
  7608. }
  7609. function getAndRenderEvents() {
  7610. if (!t.options.lazyFetching || isFetchNeeded(currentView.start, currentView.end)) {
  7611. fetchAndRenderEvents();
  7612. }
  7613. else {
  7614. renderEvents();
  7615. }
  7616. }
  7617. function fetchAndRenderEvents() {
  7618. fetchEvents(currentView.start, currentView.end);
  7619. // ... will call reportEvents
  7620. // ... which will call renderEvents
  7621. }
  7622. // called when event data arrives
  7623. function reportEvents(_events) {
  7624. events = _events;
  7625. renderEvents();
  7626. }
  7627. // called when a single event's data has been changed
  7628. function reportEventChange() {
  7629. renderEvents();
  7630. }
  7631. /* Header Updating
  7632. -----------------------------------------------------------------------------*/
  7633. function updateHeaderTitle() {
  7634. header.updateTitle(currentView.title);
  7635. }
  7636. function updateTodayButton() {
  7637. var now = t.getNow();
  7638. if (now.isWithin(currentView.intervalStart, currentView.intervalEnd)) {
  7639. header.disableButton('today');
  7640. }
  7641. else {
  7642. header.enableButton('today');
  7643. }
  7644. }
  7645. /* Selection
  7646. -----------------------------------------------------------------------------*/
  7647. // this public method receives start/end dates in any format, with any timezone
  7648. function select(zonedStartInput, zonedEndInput) {
  7649. currentView.select(
  7650. t.buildSelectSpan.apply(t, arguments)
  7651. );
  7652. }
  7653. function unselect() { // safe to be called before renderView
  7654. if (currentView) {
  7655. currentView.unselect();
  7656. }
  7657. }
  7658. /* Date
  7659. -----------------------------------------------------------------------------*/
  7660. function prev() {
  7661. date = currentView.computePrevDate(date);
  7662. renderView();
  7663. }
  7664. function next() {
  7665. date = currentView.computeNextDate(date);
  7666. renderView();
  7667. }
  7668. function prevYear() {
  7669. date.add(-1, 'years');
  7670. renderView();
  7671. }
  7672. function nextYear() {
  7673. date.add(1, 'years');
  7674. renderView();
  7675. }
  7676. function today() {
  7677. date = t.getNow();
  7678. renderView();
  7679. }
  7680. function gotoDate(zonedDateInput) {
  7681. date = t.moment(zonedDateInput).stripZone();
  7682. renderView();
  7683. }
  7684. function incrementDate(delta) {
  7685. date.add(moment.duration(delta));
  7686. renderView();
  7687. }
  7688. // Forces navigation to a view for the given date.
  7689. // `viewType` can be a specific view name or a generic one like "week" or "day".
  7690. function zoomTo(newDate, viewType) {
  7691. var spec;
  7692. viewType = viewType || 'day'; // day is default zoom
  7693. spec = t.getViewSpec(viewType) || t.getUnitViewSpec(viewType);
  7694. date = newDate.clone();
  7695. renderView(spec ? spec.type : null);
  7696. }
  7697. // for external API
  7698. function getDate() {
  7699. return t.applyTimezone(date); // infuse the calendar's timezone
  7700. }
  7701. /* Height "Freezing"
  7702. -----------------------------------------------------------------------------*/
  7703. // TODO: move this into the view
  7704. t.freezeContentHeight = freezeContentHeight;
  7705. t.unfreezeContentHeight = unfreezeContentHeight;
  7706. function freezeContentHeight() {
  7707. content.css({
  7708. width: '100%',
  7709. height: content.height(),
  7710. overflow: 'hidden'
  7711. });
  7712. }
  7713. function unfreezeContentHeight() {
  7714. content.css({
  7715. width: '',
  7716. height: '',
  7717. overflow: ''
  7718. });
  7719. }
  7720. /* Misc
  7721. -----------------------------------------------------------------------------*/
  7722. function getCalendar() {
  7723. return t;
  7724. }
  7725. function getView() {
  7726. return currentView;
  7727. }
  7728. function option(name, value) {
  7729. var newOptionHash;
  7730. if (typeof name === 'string') {
  7731. if (value === undefined) { // getter
  7732. return t.options[name];
  7733. }
  7734. else { // setter for individual option
  7735. newOptionHash = {};
  7736. newOptionHash[name] = value;
  7737. setOptions(newOptionHash);
  7738. }
  7739. }
  7740. else if (typeof name === 'object') { // compound setter with object input
  7741. setOptions(name);
  7742. }
  7743. }
  7744. function setOptions(newOptionHash) {
  7745. var optionCnt = 0;
  7746. var optionName;
  7747. for (optionName in newOptionHash) {
  7748. t.dynamicOverrides[optionName] = newOptionHash[optionName];
  7749. }
  7750. t.viewSpecCache = {}; // the dynamic override invalidates the options in this cache, so just clear it
  7751. t.populateOptionsHash(); // this.options needs to be recomputed after the dynamic override
  7752. // trigger handlers after this.options has been updated
  7753. for (optionName in newOptionHash) {
  7754. t.triggerOptionHandlers(optionName); // recall bindOption/bindOptions
  7755. optionCnt++;
  7756. }
  7757. // special-case handling of single option change.
  7758. // if only one option change, `optionName` will be its name.
  7759. if (optionCnt === 1) {
  7760. if (optionName === 'height' || optionName === 'contentHeight' || optionName === 'aspectRatio') {
  7761. updateSize(true); // true = allow recalculation of height
  7762. return;
  7763. }
  7764. else if (optionName === 'defaultDate') {
  7765. return; // can't change date this way. use gotoDate instead
  7766. }
  7767. else if (optionName === 'businessHours') {
  7768. if (currentView) {
  7769. currentView.unrenderBusinessHours();
  7770. currentView.renderBusinessHours();
  7771. }
  7772. return;
  7773. }
  7774. else if (optionName === 'timezone') {
  7775. t.rezoneArrayEventSources();
  7776. refetchEvents();
  7777. return;
  7778. }
  7779. }
  7780. // catch-all. rerender the header and rebuild/rerender the current view
  7781. renderHeader();
  7782. viewsByType = {}; // even non-current views will be affected by this option change. do before rerender
  7783. reinitView();
  7784. }
  7785. function trigger(name, thisObj) { // overrides the Emitter's trigger method :(
  7786. var args = Array.prototype.slice.call(arguments, 2);
  7787. thisObj = thisObj || _element;
  7788. this.triggerWith(name, thisObj, args); // Emitter's method
  7789. if (t.options[name]) {
  7790. return t.options[name].apply(thisObj, args);
  7791. }
  7792. }
  7793. t.initialize();
  7794. }
  7795. ;;
  7796. /*
  7797. Options binding/triggering system.
  7798. */
  7799. Calendar.mixin({
  7800. // A map of option names to arrays of handler objects. Initialized to {} in Calendar.
  7801. // Format for a handler object:
  7802. // {
  7803. // func // callback function to be called upon change
  7804. // names // option names whose values should be given to func
  7805. // }
  7806. optionHandlers: null,
  7807. // Calls handlerFunc immediately, and when the given option has changed.
  7808. // handlerFunc will be given the option value.
  7809. bindOption: function(optionName, handlerFunc) {
  7810. this.bindOptions([ optionName ], handlerFunc);
  7811. },
  7812. // Calls handlerFunc immediately, and when any of the given options change.
  7813. // handlerFunc will be given each option value as ordered function arguments.
  7814. bindOptions: function(optionNames, handlerFunc) {
  7815. var handlerObj = { func: handlerFunc, names: optionNames };
  7816. var i;
  7817. for (i = 0; i < optionNames.length; i++) {
  7818. this.registerOptionHandlerObj(optionNames[i], handlerObj);
  7819. }
  7820. this.triggerOptionHandlerObj(handlerObj);
  7821. },
  7822. // Puts the given handler object into the internal hash
  7823. registerOptionHandlerObj: function(optionName, handlerObj) {
  7824. (this.optionHandlers[optionName] || (this.optionHandlers[optionName] = []))
  7825. .push(handlerObj);
  7826. },
  7827. // Reports that the given option has changed, and calls all appropriate handlers.
  7828. triggerOptionHandlers: function(optionName) {
  7829. var handlerObjs = this.optionHandlers[optionName] || [];
  7830. var i;
  7831. for (i = 0; i < handlerObjs.length; i++) {
  7832. this.triggerOptionHandlerObj(handlerObjs[i]);
  7833. }
  7834. },
  7835. // Calls the callback for a specific handler object, passing in the appropriate arguments.
  7836. triggerOptionHandlerObj: function(handlerObj) {
  7837. var optionNames = handlerObj.names;
  7838. var optionValues = [];
  7839. var i;
  7840. for (i = 0; i < optionNames.length; i++) {
  7841. optionValues.push(this.options[optionNames[i]]);
  7842. }
  7843. handlerObj.func.apply(this, optionValues); // maintain the Calendar's `this` context
  7844. }
  7845. });
  7846. ;;
  7847. Calendar.defaults = {
  7848. titleRangeSeparator: ' \u2013 ', // en dash
  7849. monthYearFormat: 'MMMM YYYY', // required for en. other languages rely on datepicker computable option
  7850. defaultTimedEventDuration: '02:00:00',
  7851. defaultAllDayEventDuration: { days: 1 },
  7852. forceEventDuration: false,
  7853. nextDayThreshold: '09:00:00', // 9am
  7854. // display
  7855. defaultView: 'month',
  7856. aspectRatio: 1.35,
  7857. header: {
  7858. left: 'title',
  7859. center: '',
  7860. right: 'today prev,next'
  7861. },
  7862. weekends: true,
  7863. weekNumbers: false,
  7864. weekNumberTitle: 'W',
  7865. weekNumberCalculation: 'local',
  7866. //editable: false,
  7867. //nowIndicator: false,
  7868. scrollTime: '06:00:00',
  7869. // event ajax
  7870. lazyFetching: true,
  7871. startParam: 'start',
  7872. endParam: 'end',
  7873. timezoneParam: 'timezone',
  7874. timezone: false,
  7875. //allDayDefault: undefined,
  7876. // locale
  7877. isRTL: false,
  7878. buttonText: {
  7879. prev: "prev",
  7880. next: "next",
  7881. prevYear: "prev year",
  7882. nextYear: "next year",
  7883. year: 'year', // TODO: locale files need to specify this
  7884. today: 'today',
  7885. month: 'month',
  7886. week: 'week',
  7887. day: 'day'
  7888. },
  7889. buttonIcons: {
  7890. prev: 'left-single-arrow',
  7891. next: 'right-single-arrow',
  7892. prevYear: 'left-double-arrow',
  7893. nextYear: 'right-double-arrow'
  7894. },
  7895. // jquery-ui theming
  7896. theme: false,
  7897. themeButtonIcons: {
  7898. prev: 'circle-triangle-w',
  7899. next: 'circle-triangle-e',
  7900. prevYear: 'seek-prev',
  7901. nextYear: 'seek-next'
  7902. },
  7903. //eventResizableFromStart: false,
  7904. dragOpacity: .75,
  7905. dragRevertDuration: 500,
  7906. dragScroll: true,
  7907. //selectable: false,
  7908. unselectAuto: true,
  7909. dropAccept: '*',
  7910. eventOrder: 'title',
  7911. eventLimit: false,
  7912. eventLimitText: 'more',
  7913. eventLimitClick: 'popover',
  7914. dayPopoverFormat: 'LL',
  7915. handleWindowResize: true,
  7916. windowResizeDelay: 100, // milliseconds before an updateSize happens
  7917. longPressDelay: 1000
  7918. };
  7919. Calendar.englishDefaults = { // used by lang.js
  7920. dayPopoverFormat: 'dddd, MMMM D'
  7921. };
  7922. Calendar.rtlDefaults = { // right-to-left defaults
  7923. header: { // TODO: smarter solution (first/center/last ?)
  7924. left: 'next,prev today',
  7925. center: '',
  7926. right: 'title'
  7927. },
  7928. buttonIcons: {
  7929. prev: 'right-single-arrow',
  7930. next: 'left-single-arrow',
  7931. prevYear: 'right-double-arrow',
  7932. nextYear: 'left-double-arrow'
  7933. },
  7934. themeButtonIcons: {
  7935. prev: 'circle-triangle-e',
  7936. next: 'circle-triangle-w',
  7937. nextYear: 'seek-prev',
  7938. prevYear: 'seek-next'
  7939. }
  7940. };
  7941. ;;
  7942. var langOptionHash = FC.langs = {}; // initialize and expose
  7943. // TODO: document the structure and ordering of a FullCalendar lang file
  7944. // TODO: rename everything "lang" to "locale", like what the moment project did
  7945. // Initialize jQuery UI datepicker translations while using some of the translations
  7946. // Will set this as the default language for datepicker.
  7947. FC.datepickerLang = function(langCode, dpLangCode, dpOptions) {
  7948. // get the FullCalendar internal option hash for this language. create if necessary
  7949. var fcOptions = langOptionHash[langCode] || (langOptionHash[langCode] = {});
  7950. // transfer some simple options from datepicker to fc
  7951. fcOptions.isRTL = dpOptions.isRTL;
  7952. fcOptions.weekNumberTitle = dpOptions.weekHeader;
  7953. // compute some more complex options from datepicker
  7954. $.each(dpComputableOptions, function(name, func) {
  7955. fcOptions[name] = func(dpOptions);
  7956. });
  7957. // is jQuery UI Datepicker is on the page?
  7958. if ($.datepicker) {
  7959. // Register the language data.
  7960. // FullCalendar and MomentJS use language codes like "pt-br" but Datepicker
  7961. // does it like "pt-BR" or if it doesn't have the language, maybe just "pt".
  7962. // Make an alias so the language can be referenced either way.
  7963. $.datepicker.regional[dpLangCode] =
  7964. $.datepicker.regional[langCode] = // alias
  7965. dpOptions;
  7966. // Alias 'en' to the default language data. Do this every time.
  7967. $.datepicker.regional.en = $.datepicker.regional[''];
  7968. // Set as Datepicker's global defaults.
  7969. $.datepicker.setDefaults(dpOptions);
  7970. }
  7971. };
  7972. // Sets FullCalendar-specific translations. Will set the language as the global default.
  7973. FC.lang = function(langCode, newFcOptions) {
  7974. var fcOptions;
  7975. var momOptions;
  7976. // get the FullCalendar internal option hash for this language. create if necessary
  7977. fcOptions = langOptionHash[langCode] || (langOptionHash[langCode] = {});
  7978. // provided new options for this language? merge them in
  7979. if (newFcOptions) {
  7980. fcOptions = langOptionHash[langCode] = mergeOptions([ fcOptions, newFcOptions ]);
  7981. }
  7982. // compute language options that weren't defined.
  7983. // always do this. newFcOptions can be undefined when initializing from i18n file,
  7984. // so no way to tell if this is an initialization or a default-setting.
  7985. momOptions = getMomentLocaleData(langCode); // will fall back to en
  7986. $.each(momComputableOptions, function(name, func) {
  7987. if (fcOptions[name] == null) {
  7988. fcOptions[name] = func(momOptions, fcOptions);
  7989. }
  7990. });
  7991. // set it as the default language for FullCalendar
  7992. Calendar.defaults.lang = langCode;
  7993. };
  7994. // NOTE: can't guarantee any of these computations will run because not every language has datepicker
  7995. // configs, so make sure there are English fallbacks for these in the defaults file.
  7996. var dpComputableOptions = {
  7997. buttonText: function(dpOptions) {
  7998. return {
  7999. // the translations sometimes wrongly contain HTML entities
  8000. prev: stripHtmlEntities(dpOptions.prevText),
  8001. next: stripHtmlEntities(dpOptions.nextText),
  8002. today: stripHtmlEntities(dpOptions.currentText)
  8003. };
  8004. },
  8005. // Produces format strings like "MMMM YYYY" -> "September 2014"
  8006. monthYearFormat: function(dpOptions) {
  8007. return dpOptions.showMonthAfterYear ?
  8008. 'YYYY[' + dpOptions.yearSuffix + '] MMMM' :
  8009. 'MMMM YYYY[' + dpOptions.yearSuffix + ']';
  8010. }
  8011. };
  8012. var momComputableOptions = {
  8013. // Produces format strings like "ddd M/D" -> "Fri 9/15"
  8014. dayOfMonthFormat: function(momOptions, fcOptions) {
  8015. var format = momOptions.longDateFormat('l'); // for the format like "M/D/YYYY"
  8016. // strip the year off the edge, as well as other misc non-whitespace chars
  8017. format = format.replace(/^Y+[^\w\s]*|[^\w\s]*Y+$/g, '');
  8018. if (fcOptions.isRTL) {
  8019. format += ' ddd'; // for RTL, add day-of-week to end
  8020. }
  8021. else {
  8022. format = 'ddd ' + format; // for LTR, add day-of-week to beginning
  8023. }
  8024. return format;
  8025. },
  8026. // Produces format strings like "h:mma" -> "6:00pm"
  8027. mediumTimeFormat: function(momOptions) { // can't be called `timeFormat` because collides with option
  8028. return momOptions.longDateFormat('LT')
  8029. .replace(/\s*a$/i, 'a'); // convert AM/PM/am/pm to lowercase. remove any spaces beforehand
  8030. },
  8031. // Produces format strings like "h(:mm)a" -> "6pm" / "6:30pm"
  8032. smallTimeFormat: function(momOptions) {
  8033. return momOptions.longDateFormat('LT')
  8034. .replace(':mm', '(:mm)')
  8035. .replace(/(\Wmm)$/, '($1)') // like above, but for foreign langs
  8036. .replace(/\s*a$/i, 'a'); // convert AM/PM/am/pm to lowercase. remove any spaces beforehand
  8037. },
  8038. // Produces format strings like "h(:mm)t" -> "6p" / "6:30p"
  8039. extraSmallTimeFormat: function(momOptions) {
  8040. return momOptions.longDateFormat('LT')
  8041. .replace(':mm', '(:mm)')
  8042. .replace(/(\Wmm)$/, '($1)') // like above, but for foreign langs
  8043. .replace(/\s*a$/i, 't'); // convert to AM/PM/am/pm to lowercase one-letter. remove any spaces beforehand
  8044. },
  8045. // Produces format strings like "ha" / "H" -> "6pm" / "18"
  8046. hourFormat: function(momOptions) {
  8047. return momOptions.longDateFormat('LT')
  8048. .replace(':mm', '')
  8049. .replace(/(\Wmm)$/, '') // like above, but for foreign langs
  8050. .replace(/\s*a$/i, 'a'); // convert AM/PM/am/pm to lowercase. remove any spaces beforehand
  8051. },
  8052. // Produces format strings like "h:mm" -> "6:30" (with no AM/PM)
  8053. noMeridiemTimeFormat: function(momOptions) {
  8054. return momOptions.longDateFormat('LT')
  8055. .replace(/\s*a$/i, ''); // remove trailing AM/PM
  8056. }
  8057. };
  8058. // options that should be computed off live calendar options (considers override options)
  8059. // TODO: best place for this? related to lang?
  8060. // TODO: flipping text based on isRTL is a bad idea because the CSS `direction` might want to handle it
  8061. var instanceComputableOptions = {
  8062. // Produces format strings for results like "Mo 16"
  8063. smallDayDateFormat: function(options) {
  8064. return options.isRTL ?
  8065. 'D dd' :
  8066. 'dd D';
  8067. },
  8068. // Produces format strings for results like "Wk 5"
  8069. weekFormat: function(options) {
  8070. return options.isRTL ?
  8071. 'w[ ' + options.weekNumberTitle + ']' :
  8072. '[' + options.weekNumberTitle + ' ]w';
  8073. },
  8074. // Produces format strings for results like "Wk5"
  8075. smallWeekFormat: function(options) {
  8076. return options.isRTL ?
  8077. 'w[' + options.weekNumberTitle + ']' :
  8078. '[' + options.weekNumberTitle + ']w';
  8079. }
  8080. };
  8081. function populateInstanceComputableOptions(options) {
  8082. $.each(instanceComputableOptions, function(name, func) {
  8083. if (options[name] == null) {
  8084. options[name] = func(options);
  8085. }
  8086. });
  8087. }
  8088. // Returns moment's internal locale data. If doesn't exist, returns English.
  8089. // Works with moment-pre-2.8
  8090. function getMomentLocaleData(langCode) {
  8091. var func = moment.localeData || moment.langData;
  8092. return func.call(moment, langCode) ||
  8093. func.call(moment, 'en'); // the newer localData could return null, so fall back to en
  8094. }
  8095. // Initialize English by forcing computation of moment-derived options.
  8096. // Also, sets it as the default.
  8097. FC.lang('en', Calendar.englishDefaults);
  8098. ;;
  8099. /* Top toolbar area with buttons and title
  8100. ----------------------------------------------------------------------------------------------------------------------*/
  8101. // TODO: rename all header-related things to "toolbar"
  8102. function Header(calendar) {
  8103. var t = this;
  8104. // exports
  8105. t.render = render;
  8106. t.removeElement = removeElement;
  8107. t.updateTitle = updateTitle;
  8108. t.activateButton = activateButton;
  8109. t.deactivateButton = deactivateButton;
  8110. t.disableButton = disableButton;
  8111. t.enableButton = enableButton;
  8112. t.getViewsWithButtons = getViewsWithButtons;
  8113. t.el = null; // mirrors local `el`
  8114. // locals
  8115. var el;
  8116. var viewsWithButtons = [];
  8117. var tm;
  8118. // can be called repeatedly and will rerender
  8119. function render() {
  8120. var options = calendar.options;
  8121. var sections = options.header;
  8122. tm = options.theme ? 'ui' : 'fc';
  8123. if (sections) {
  8124. if (!el) {
  8125. el = this.el = $("<div class='fc-toolbar'/>");
  8126. }
  8127. else {
  8128. el.empty();
  8129. }
  8130. el.append(renderSection('left'))
  8131. .append(renderSection('right'))
  8132. .append(renderSection('center'))
  8133. .append('<div class="fc-clear"/>');
  8134. }
  8135. else {
  8136. removeElement();
  8137. }
  8138. }
  8139. function removeElement() {
  8140. if (el) {
  8141. el.remove();
  8142. el = t.el = null;
  8143. }
  8144. }
  8145. function renderSection(position) {
  8146. var sectionEl = $('<div class="fc-' + position + '"/>');
  8147. var options = calendar.options;
  8148. var buttonStr = options.header[position];
  8149. if (buttonStr) {
  8150. $.each(buttonStr.split(' '), function(i) {
  8151. var groupChildren = $();
  8152. var isOnlyButtons = true;
  8153. var groupEl;
  8154. $.each(this.split(','), function(j, buttonName) {
  8155. var customButtonProps;
  8156. var viewSpec;
  8157. var buttonClick;
  8158. var overrideText; // text explicitly set by calendar's constructor options. overcomes icons
  8159. var defaultText;
  8160. var themeIcon;
  8161. var normalIcon;
  8162. var innerHtml;
  8163. var classes;
  8164. var button; // the element
  8165. if (buttonName == 'title') {
  8166. groupChildren = groupChildren.add($('<h2>&nbsp;</h2>')); // we always want it to take up height
  8167. isOnlyButtons = false;
  8168. }
  8169. else {
  8170. if ((customButtonProps = (options.customButtons || {})[buttonName])) {
  8171. buttonClick = function(ev) {
  8172. if (customButtonProps.click) {
  8173. customButtonProps.click.call(button[0], ev);
  8174. }
  8175. };
  8176. overrideText = ''; // icons will override text
  8177. defaultText = customButtonProps.text;
  8178. }
  8179. else if ((viewSpec = calendar.getViewSpec(buttonName))) {
  8180. buttonClick = function() {
  8181. calendar.changeView(buttonName);
  8182. };
  8183. viewsWithButtons.push(buttonName);
  8184. overrideText = viewSpec.buttonTextOverride;
  8185. defaultText = viewSpec.buttonTextDefault;
  8186. }
  8187. else if (calendar[buttonName]) { // a calendar method
  8188. buttonClick = function() {
  8189. calendar[buttonName]();
  8190. };
  8191. overrideText = (calendar.overrides.buttonText || {})[buttonName];
  8192. defaultText = options.buttonText[buttonName]; // everything else is considered default
  8193. }
  8194. if (buttonClick) {
  8195. themeIcon =
  8196. customButtonProps ?
  8197. customButtonProps.themeIcon :
  8198. options.themeButtonIcons[buttonName];
  8199. normalIcon =
  8200. customButtonProps ?
  8201. customButtonProps.icon :
  8202. options.buttonIcons[buttonName];
  8203. if (overrideText) {
  8204. innerHtml = htmlEscape(overrideText);
  8205. }
  8206. else if (themeIcon && options.theme) {
  8207. innerHtml = "<span class='ui-icon ui-icon-" + themeIcon + "'></span>";
  8208. }
  8209. else if (normalIcon && !options.theme) {
  8210. innerHtml = "<span class='" + normalIcon + "'></span>";
  8211. }
  8212. else {
  8213. innerHtml = htmlEscape(defaultText);
  8214. }
  8215. classes = [
  8216. 'fc-' + buttonName + '-button',
  8217. tm + '-button',
  8218. tm + '-state-default'
  8219. ];
  8220. button = $( // type="button" so that it doesn't submit a form
  8221. '<button type="button" class="' + classes.join(' ') + '">' +
  8222. innerHtml +
  8223. '</button>'
  8224. )
  8225. .click(function(ev) {
  8226. // don't process clicks for disabled buttons
  8227. if (!button.hasClass(tm + '-state-disabled')) {
  8228. buttonClick(ev);
  8229. // after the click action, if the button becomes the "active" tab, or disabled,
  8230. // it should never have a hover class, so remove it now.
  8231. if (
  8232. button.hasClass(tm + '-state-active') ||
  8233. button.hasClass(tm + '-state-disabled')
  8234. ) {
  8235. button.removeClass(tm + '-state-hover');
  8236. }
  8237. }
  8238. })
  8239. .mousedown(function() {
  8240. // the *down* effect (mouse pressed in).
  8241. // only on buttons that are not the "active" tab, or disabled
  8242. button
  8243. .not('.' + tm + '-state-active')
  8244. .not('.' + tm + '-state-disabled')
  8245. .addClass(tm + '-state-down');
  8246. })
  8247. .mouseup(function() {
  8248. // undo the *down* effect
  8249. button.removeClass(tm + '-state-down');
  8250. })
  8251. .hover(
  8252. function() {
  8253. // the *hover* effect.
  8254. // only on buttons that are not the "active" tab, or disabled
  8255. button
  8256. .not('.' + tm + '-state-active')
  8257. .not('.' + tm + '-state-disabled')
  8258. .addClass(tm + '-state-hover');
  8259. },
  8260. function() {
  8261. // undo the *hover* effect
  8262. button
  8263. .removeClass(tm + '-state-hover')
  8264. .removeClass(tm + '-state-down'); // if mouseleave happens before mouseup
  8265. }
  8266. );
  8267. groupChildren = groupChildren.add(button);
  8268. }
  8269. }
  8270. });
  8271. if (isOnlyButtons) {
  8272. groupChildren
  8273. .first().addClass(tm + '-corner-left').end()
  8274. .last().addClass(tm + '-corner-right').end();
  8275. }
  8276. if (groupChildren.length > 1) {
  8277. groupEl = $('<div/>');
  8278. if (isOnlyButtons) {
  8279. groupEl.addClass('fc-button-group');
  8280. }
  8281. groupEl.append(groupChildren);
  8282. sectionEl.append(groupEl);
  8283. }
  8284. else {
  8285. sectionEl.append(groupChildren); // 1 or 0 children
  8286. }
  8287. });
  8288. }
  8289. return sectionEl;
  8290. }
  8291. function updateTitle(text) {
  8292. if (el) {
  8293. el.find('h2').text(text);
  8294. }
  8295. }
  8296. function activateButton(buttonName) {
  8297. if (el) {
  8298. el.find('.fc-' + buttonName + '-button')
  8299. .addClass(tm + '-state-active');
  8300. }
  8301. }
  8302. function deactivateButton(buttonName) {
  8303. if (el) {
  8304. el.find('.fc-' + buttonName + '-button')
  8305. .removeClass(tm + '-state-active');
  8306. }
  8307. }
  8308. function disableButton(buttonName) {
  8309. if (el) {
  8310. el.find('.fc-' + buttonName + '-button')
  8311. .prop('disabled', true)
  8312. .addClass(tm + '-state-disabled');
  8313. }
  8314. }
  8315. function enableButton(buttonName) {
  8316. if (el) {
  8317. el.find('.fc-' + buttonName + '-button')
  8318. .prop('disabled', false)
  8319. .removeClass(tm + '-state-disabled');
  8320. }
  8321. }
  8322. function getViewsWithButtons() {
  8323. return viewsWithButtons;
  8324. }
  8325. }
  8326. ;;
  8327. FC.sourceNormalizers = [];
  8328. FC.sourceFetchers = [];
  8329. var ajaxDefaults = {
  8330. dataType: 'json',
  8331. cache: false
  8332. };
  8333. var eventGUID = 1;
  8334. function EventManager() { // assumed to be a calendar
  8335. var t = this;
  8336. // exports
  8337. t.isFetchNeeded = isFetchNeeded;
  8338. t.fetchEvents = fetchEvents;
  8339. t.fetchEventSources = fetchEventSources;
  8340. t.getEventSources = getEventSources;
  8341. t.getEventSourceById = getEventSourceById;
  8342. t.getEventSourcesByMatchArray = getEventSourcesByMatchArray;
  8343. t.getEventSourcesByMatch = getEventSourcesByMatch;
  8344. t.addEventSource = addEventSource;
  8345. t.removeEventSource = removeEventSource;
  8346. t.removeEventSources = removeEventSources;
  8347. t.updateEvent = updateEvent;
  8348. t.renderEvent = renderEvent;
  8349. t.removeEvents = removeEvents;
  8350. t.clientEvents = clientEvents;
  8351. t.mutateEvent = mutateEvent;
  8352. t.normalizeEventDates = normalizeEventDates;
  8353. t.normalizeEventTimes = normalizeEventTimes;
  8354. // imports
  8355. var reportEvents = t.reportEvents;
  8356. // locals
  8357. var stickySource = { events: [] };
  8358. var sources = [ stickySource ];
  8359. var rangeStart, rangeEnd;
  8360. var pendingSourceCnt = 0; // outstanding fetch requests, max one per source
  8361. var cache = []; // holds events that have already been expanded
  8362. $.each(
  8363. (t.options.events ? [ t.options.events ] : []).concat(t.options.eventSources || []),
  8364. function(i, sourceInput) {
  8365. var source = buildEventSource(sourceInput);
  8366. if (source) {
  8367. sources.push(source);
  8368. }
  8369. }
  8370. );
  8371. /* Fetching
  8372. -----------------------------------------------------------------------------*/
  8373. // start and end are assumed to be unzoned
  8374. function isFetchNeeded(start, end) {
  8375. return !rangeStart || // nothing has been fetched yet?
  8376. start < rangeStart || end > rangeEnd; // is part of the new range outside of the old range?
  8377. }
  8378. function fetchEvents(start, end) {
  8379. rangeStart = start;
  8380. rangeEnd = end;
  8381. fetchEventSources(sources, 'reset');
  8382. }
  8383. // expects an array of event source objects (the originals, not copies)
  8384. // `specialFetchType` is an optimization parameter that affects purging of the event cache.
  8385. function fetchEventSources(specificSources, specialFetchType) {
  8386. var i, source;
  8387. if (specialFetchType === 'reset') {
  8388. cache = [];
  8389. }
  8390. else if (specialFetchType !== 'add') {
  8391. cache = excludeEventsBySources(cache, specificSources);
  8392. }
  8393. for (i = 0; i < specificSources.length; i++) {
  8394. source = specificSources[i];
  8395. // already-pending sources have already been accounted for in pendingSourceCnt
  8396. if (source._status !== 'pending') {
  8397. pendingSourceCnt++;
  8398. }
  8399. source._fetchId = (source._fetchId || 0) + 1;
  8400. source._status = 'pending';
  8401. }
  8402. for (i = 0; i < specificSources.length; i++) {
  8403. source = specificSources[i];
  8404. tryFetchEventSource(source, source._fetchId);
  8405. }
  8406. }
  8407. // fetches an event source and processes its result ONLY if it is still the current fetch.
  8408. // caller is responsible for incrementing pendingSourceCnt first.
  8409. function tryFetchEventSource(source, fetchId) {
  8410. _fetchEventSource(source, function(eventInputs) {
  8411. var isArraySource = $.isArray(source.events);
  8412. var i, eventInput;
  8413. var abstractEvent;
  8414. if (
  8415. // is this the source's most recent fetch?
  8416. // if not, rely on an upcoming fetch of this source to decrement pendingSourceCnt
  8417. fetchId === source._fetchId &&
  8418. // event source no longer valid?
  8419. source._status !== 'rejected'
  8420. ) {
  8421. source._status = 'resolved';
  8422. if (eventInputs) {
  8423. for (i = 0; i < eventInputs.length; i++) {
  8424. eventInput = eventInputs[i];
  8425. if (isArraySource) { // array sources have already been convert to Event Objects
  8426. abstractEvent = eventInput;
  8427. }
  8428. else {
  8429. abstractEvent = buildEventFromInput(eventInput, source);
  8430. }
  8431. if (abstractEvent) { // not false (an invalid event)
  8432. cache.push.apply(
  8433. cache,
  8434. expandEvent(abstractEvent) // add individual expanded events to the cache
  8435. );
  8436. }
  8437. }
  8438. }
  8439. decrementPendingSourceCnt();
  8440. }
  8441. });
  8442. }
  8443. function rejectEventSource(source) {
  8444. var wasPending = source._status === 'pending';
  8445. source._status = 'rejected';
  8446. if (wasPending) {
  8447. decrementPendingSourceCnt();
  8448. }
  8449. }
  8450. function decrementPendingSourceCnt() {
  8451. pendingSourceCnt--;
  8452. if (!pendingSourceCnt) {
  8453. reportEvents(cache);
  8454. }
  8455. }
  8456. function _fetchEventSource(source, callback) {
  8457. var i;
  8458. var fetchers = FC.sourceFetchers;
  8459. var res;
  8460. for (i=0; i<fetchers.length; i++) {
  8461. res = fetchers[i].call(
  8462. t, // this, the Calendar object
  8463. source,
  8464. rangeStart.clone(),
  8465. rangeEnd.clone(),
  8466. t.options.timezone,
  8467. callback
  8468. );
  8469. if (res === true) {
  8470. // the fetcher is in charge. made its own async request
  8471. return;
  8472. }
  8473. else if (typeof res == 'object') {
  8474. // the fetcher returned a new source. process it
  8475. _fetchEventSource(res, callback);
  8476. return;
  8477. }
  8478. }
  8479. var events = source.events;
  8480. if (events) {
  8481. if ($.isFunction(events)) {
  8482. t.pushLoading();
  8483. events.call(
  8484. t, // this, the Calendar object
  8485. rangeStart.clone(),
  8486. rangeEnd.clone(),
  8487. t.options.timezone,
  8488. function(events) {
  8489. callback(events);
  8490. t.popLoading();
  8491. }
  8492. );
  8493. }
  8494. else if ($.isArray(events)) {
  8495. callback(events);
  8496. }
  8497. else {
  8498. callback();
  8499. }
  8500. }else{
  8501. var url = source.url;
  8502. if (url) {
  8503. var success = source.success;
  8504. var error = source.error;
  8505. var complete = source.complete;
  8506. // retrieve any outbound GET/POST $.ajax data from the options
  8507. var customData;
  8508. if ($.isFunction(source.data)) {
  8509. // supplied as a function that returns a key/value object
  8510. customData = source.data();
  8511. }
  8512. else {
  8513. // supplied as a straight key/value object
  8514. customData = source.data;
  8515. }
  8516. // use a copy of the custom data so we can modify the parameters
  8517. // and not affect the passed-in object.
  8518. var data = $.extend({}, customData || {});
  8519. var startParam = firstDefined(source.startParam, t.options.startParam);
  8520. var endParam = firstDefined(source.endParam, t.options.endParam);
  8521. var timezoneParam = firstDefined(source.timezoneParam, t.options.timezoneParam);
  8522. if (startParam) {
  8523. data[startParam] = rangeStart.format();
  8524. }
  8525. if (endParam) {
  8526. data[endParam] = rangeEnd.format();
  8527. }
  8528. if (t.options.timezone && t.options.timezone != 'local') {
  8529. data[timezoneParam] = t.options.timezone;
  8530. }
  8531. t.pushLoading();
  8532. $.ajax($.extend({}, ajaxDefaults, source, {
  8533. data: data,
  8534. success: function(events) {
  8535. events = events || [];
  8536. var res = applyAll(success, this, arguments);
  8537. if ($.isArray(res)) {
  8538. events = res;
  8539. }
  8540. callback(events);
  8541. },
  8542. error: function() {
  8543. applyAll(error, this, arguments);
  8544. callback();
  8545. },
  8546. complete: function() {
  8547. applyAll(complete, this, arguments);
  8548. t.popLoading();
  8549. }
  8550. }));
  8551. }else{
  8552. callback();
  8553. }
  8554. }
  8555. }
  8556. /* Sources
  8557. -----------------------------------------------------------------------------*/
  8558. function addEventSource(sourceInput) {
  8559. var source = buildEventSource(sourceInput);
  8560. if (source) {
  8561. sources.push(source);
  8562. fetchEventSources([ source ], 'add'); // will eventually call reportEvents
  8563. }
  8564. }
  8565. function buildEventSource(sourceInput) { // will return undefined if invalid source
  8566. var normalizers = FC.sourceNormalizers;
  8567. var source;
  8568. var i;
  8569. if ($.isFunction(sourceInput) || $.isArray(sourceInput)) {
  8570. source = { events: sourceInput };
  8571. }
  8572. else if (typeof sourceInput === 'string') {
  8573. source = { url: sourceInput };
  8574. }
  8575. else if (typeof sourceInput === 'object') {
  8576. source = $.extend({}, sourceInput); // shallow copy
  8577. }
  8578. if (source) {
  8579. // TODO: repeat code, same code for event classNames
  8580. if (source.className) {
  8581. if (typeof source.className === 'string') {
  8582. source.className = source.className.split(/\s+/);
  8583. }
  8584. // otherwise, assumed to be an array
  8585. }
  8586. else {
  8587. source.className = [];
  8588. }
  8589. // for array sources, we convert to standard Event Objects up front
  8590. if ($.isArray(source.events)) {
  8591. source.origArray = source.events; // for removeEventSource
  8592. source.events = $.map(source.events, function(eventInput) {
  8593. return buildEventFromInput(eventInput, source);
  8594. });
  8595. }
  8596. for (i=0; i<normalizers.length; i++) {
  8597. normalizers[i].call(t, source);
  8598. }
  8599. return source;
  8600. }
  8601. }
  8602. function removeEventSource(matchInput) {
  8603. removeSpecificEventSources(
  8604. getEventSourcesByMatch(matchInput)
  8605. );
  8606. }
  8607. // if called with no arguments, removes all.
  8608. function removeEventSources(matchInputs) {
  8609. if (matchInputs == null) {
  8610. removeSpecificEventSources(sources, true); // isAll=true
  8611. }
  8612. else {
  8613. removeSpecificEventSources(
  8614. getEventSourcesByMatchArray(matchInputs)
  8615. );
  8616. }
  8617. }
  8618. function removeSpecificEventSources(targetSources, isAll) {
  8619. var i;
  8620. // cancel pending requests
  8621. for (i = 0; i < targetSources.length; i++) {
  8622. rejectEventSource(targetSources[i]);
  8623. }
  8624. if (isAll) { // an optimization
  8625. sources = [];
  8626. cache = [];
  8627. }
  8628. else {
  8629. // remove from persisted source list
  8630. sources = $.grep(sources, function(source) {
  8631. for (i = 0; i < targetSources.length; i++) {
  8632. if (source === targetSources[i]) {
  8633. return false; // exclude
  8634. }
  8635. }
  8636. return true; // include
  8637. });
  8638. cache = excludeEventsBySources(cache, targetSources);
  8639. }
  8640. reportEvents(cache);
  8641. }
  8642. function getEventSources() {
  8643. return sources.slice(1); // returns a shallow copy of sources with stickySource removed
  8644. }
  8645. function getEventSourceById(id) {
  8646. return $.grep(sources, function(source) {
  8647. return source.id && source.id === id;
  8648. })[0];
  8649. }
  8650. // like getEventSourcesByMatch, but accepts multple match criteria (like multiple IDs)
  8651. function getEventSourcesByMatchArray(matchInputs) {
  8652. // coerce into an array
  8653. if (!matchInputs) {
  8654. matchInputs = [];
  8655. }
  8656. else if (!$.isArray(matchInputs)) {
  8657. matchInputs = [ matchInputs ];
  8658. }
  8659. var matchingSources = [];
  8660. var i;
  8661. // resolve raw inputs to real event source objects
  8662. for (i = 0; i < matchInputs.length; i++) {
  8663. matchingSources.push.apply( // append
  8664. matchingSources,
  8665. getEventSourcesByMatch(matchInputs[i])
  8666. );
  8667. }
  8668. return matchingSources;
  8669. }
  8670. // matchInput can either by a real event source object, an ID, or the function/URL for the source.
  8671. // returns an array of matching source objects.
  8672. function getEventSourcesByMatch(matchInput) {
  8673. var i, source;
  8674. // given an proper event source object
  8675. for (i = 0; i < sources.length; i++) {
  8676. source = sources[i];
  8677. if (source === matchInput) {
  8678. return [ source ];
  8679. }
  8680. }
  8681. // an ID match
  8682. source = getEventSourceById(matchInput);
  8683. if (source) {
  8684. return [ source ];
  8685. }
  8686. return $.grep(sources, function(source) {
  8687. return isSourcesEquivalent(matchInput, source);
  8688. });
  8689. }
  8690. function isSourcesEquivalent(source1, source2) {
  8691. return source1 && source2 && getSourcePrimitive(source1) == getSourcePrimitive(source2);
  8692. }
  8693. function getSourcePrimitive(source) {
  8694. return (
  8695. (typeof source === 'object') ? // a normalized event source?
  8696. (source.origArray || source.googleCalendarId || source.url || source.events) : // get the primitive
  8697. null
  8698. ) ||
  8699. source; // the given argument *is* the primitive
  8700. }
  8701. // util
  8702. // returns a filtered array without events that are part of any of the given sources
  8703. function excludeEventsBySources(specificEvents, specificSources) {
  8704. return $.grep(specificEvents, function(event) {
  8705. for (var i = 0; i < specificSources.length; i++) {
  8706. if (event.source === specificSources[i]) {
  8707. return false; // exclude
  8708. }
  8709. }
  8710. return true; // keep
  8711. });
  8712. }
  8713. /* Manipulation
  8714. -----------------------------------------------------------------------------*/
  8715. // Only ever called from the externally-facing API
  8716. function updateEvent(event) {
  8717. // massage start/end values, even if date string values
  8718. event.start = t.moment(event.start);
  8719. if (event.end) {
  8720. event.end = t.moment(event.end);
  8721. }
  8722. else {
  8723. event.end = null;
  8724. }
  8725. mutateEvent(event, getMiscEventProps(event)); // will handle start/end/allDay normalization
  8726. reportEvents(cache); // reports event modifications (so we can redraw)
  8727. }
  8728. // Returns a hash of misc event properties that should be copied over to related events.
  8729. function getMiscEventProps(event) {
  8730. var props = {};
  8731. $.each(event, function(name, val) {
  8732. if (isMiscEventPropName(name)) {
  8733. if (val !== undefined && isAtomic(val)) { // a defined non-object
  8734. props[name] = val;
  8735. }
  8736. }
  8737. });
  8738. return props;
  8739. }
  8740. // non-date-related, non-id-related, non-secret
  8741. function isMiscEventPropName(name) {
  8742. return !/^_|^(id|allDay|start|end)$/.test(name);
  8743. }
  8744. // returns the expanded events that were created
  8745. function renderEvent(eventInput, stick) {
  8746. var abstractEvent = buildEventFromInput(eventInput);
  8747. var events;
  8748. var i, event;
  8749. if (abstractEvent) { // not false (a valid input)
  8750. events = expandEvent(abstractEvent);
  8751. for (i = 0; i < events.length; i++) {
  8752. event = events[i];
  8753. if (!event.source) {
  8754. if (stick) {
  8755. stickySource.events.push(event);
  8756. event.source = stickySource;
  8757. }
  8758. cache.push(event);
  8759. }
  8760. }
  8761. reportEvents(cache);
  8762. return events;
  8763. }
  8764. return [];
  8765. }
  8766. function removeEvents(filter) {
  8767. var eventID;
  8768. var i;
  8769. if (filter == null) { // null or undefined. remove all events
  8770. filter = function() { return true; }; // will always match
  8771. }
  8772. else if (!$.isFunction(filter)) { // an event ID
  8773. eventID = filter + '';
  8774. filter = function(event) {
  8775. return event._id == eventID;
  8776. };
  8777. }
  8778. // Purge event(s) from our local cache
  8779. cache = $.grep(cache, filter, true); // inverse=true
  8780. // Remove events from array sources.
  8781. // This works because they have been converted to official Event Objects up front.
  8782. // (and as a result, event._id has been calculated).
  8783. for (i=0; i<sources.length; i++) {
  8784. if ($.isArray(sources[i].events)) {
  8785. sources[i].events = $.grep(sources[i].events, filter, true);
  8786. }
  8787. }
  8788. reportEvents(cache);
  8789. }
  8790. function clientEvents(filter) {
  8791. if ($.isFunction(filter)) {
  8792. return $.grep(cache, filter);
  8793. }
  8794. else if (filter != null) { // not null, not undefined. an event ID
  8795. filter += '';
  8796. return $.grep(cache, function(e) {
  8797. return e._id == filter;
  8798. });
  8799. }
  8800. return cache; // else, return all
  8801. }
  8802. // Makes sure all array event sources have their internal event objects
  8803. // converted over to the Calendar's current timezone.
  8804. t.rezoneArrayEventSources = function() {
  8805. var i;
  8806. var events;
  8807. var j;
  8808. for (i = 0; i < sources.length; i++) {
  8809. events = sources[i].events;
  8810. if ($.isArray(events)) {
  8811. for (j = 0; j < events.length; j++) {
  8812. rezoneEventDates(events[j]);
  8813. }
  8814. }
  8815. }
  8816. };
  8817. function rezoneEventDates(event) {
  8818. event.start = t.moment(event.start);
  8819. if (event.end) {
  8820. event.end = t.moment(event.end);
  8821. }
  8822. backupEventDates(event);
  8823. }
  8824. /* Event Normalization
  8825. -----------------------------------------------------------------------------*/
  8826. // Given a raw object with key/value properties, returns an "abstract" Event object.
  8827. // An "abstract" event is an event that, if recurring, will not have been expanded yet.
  8828. // Will return `false` when input is invalid.
  8829. // `source` is optional
  8830. function buildEventFromInput(input, source) {
  8831. var out = {};
  8832. var start, end;
  8833. var allDay;
  8834. if (t.options.eventDataTransform) {
  8835. input = t.options.eventDataTransform(input);
  8836. }
  8837. if (source && source.eventDataTransform) {
  8838. input = source.eventDataTransform(input);
  8839. }
  8840. // Copy all properties over to the resulting object.
  8841. // The special-case properties will be copied over afterwards.
  8842. $.extend(out, input);
  8843. if (source) {
  8844. out.source = source;
  8845. }
  8846. out._id = input._id || (input.id === undefined ? '_fc' + eventGUID++ : input.id + '');
  8847. if (input.className) {
  8848. if (typeof input.className == 'string') {
  8849. out.className = input.className.split(/\s+/);
  8850. }
  8851. else { // assumed to be an array
  8852. out.className = input.className;
  8853. }
  8854. }
  8855. else {
  8856. out.className = [];
  8857. }
  8858. start = input.start || input.date; // "date" is an alias for "start"
  8859. end = input.end;
  8860. // parse as a time (Duration) if applicable
  8861. if (isTimeString(start)) {
  8862. start = moment.duration(start);
  8863. }
  8864. if (isTimeString(end)) {
  8865. end = moment.duration(end);
  8866. }
  8867. if (input.dow || moment.isDuration(start) || moment.isDuration(end)) {
  8868. // the event is "abstract" (recurring) so don't calculate exact start/end dates just yet
  8869. out.start = start ? moment.duration(start) : null; // will be a Duration or null
  8870. out.end = end ? moment.duration(end) : null; // will be a Duration or null
  8871. out._recurring = true; // our internal marker
  8872. }
  8873. else {
  8874. if (start) {
  8875. start = t.moment(start);
  8876. if (!start.isValid()) {
  8877. return false;
  8878. }
  8879. }
  8880. if (end) {
  8881. end = t.moment(end);
  8882. if (!end.isValid()) {
  8883. end = null; // let defaults take over
  8884. }
  8885. }
  8886. allDay = input.allDay;
  8887. if (allDay === undefined) { // still undefined? fallback to default
  8888. allDay = firstDefined(
  8889. source ? source.allDayDefault : undefined,
  8890. t.options.allDayDefault
  8891. );
  8892. // still undefined? normalizeEventDates will calculate it
  8893. }
  8894. assignDatesToEvent(start, end, allDay, out);
  8895. }
  8896. t.normalizeEvent(out); // hook for external use. a prototype method
  8897. return out;
  8898. }
  8899. t.buildEventFromInput = buildEventFromInput;
  8900. // Normalizes and assigns the given dates to the given partially-formed event object.
  8901. // NOTE: mutates the given start/end moments. does not make a copy.
  8902. function assignDatesToEvent(start, end, allDay, event) {
  8903. event.start = start;
  8904. event.end = end;
  8905. event.allDay = allDay;
  8906. normalizeEventDates(event);
  8907. backupEventDates(event);
  8908. }
  8909. // Ensures proper values for allDay/start/end. Accepts an Event object, or a plain object with event-ish properties.
  8910. // NOTE: Will modify the given object.
  8911. function normalizeEventDates(eventProps) {
  8912. normalizeEventTimes(eventProps);
  8913. if (eventProps.end && !eventProps.end.isAfter(eventProps.start)) {
  8914. eventProps.end = null;
  8915. }
  8916. if (!eventProps.end) {
  8917. if (t.options.forceEventDuration) {
  8918. eventProps.end = t.getDefaultEventEnd(eventProps.allDay, eventProps.start);
  8919. }
  8920. else {
  8921. eventProps.end = null;
  8922. }
  8923. }
  8924. }
  8925. // Ensures the allDay property exists and the timeliness of the start/end dates are consistent
  8926. function normalizeEventTimes(eventProps) {
  8927. if (eventProps.allDay == null) {
  8928. eventProps.allDay = !(eventProps.start.hasTime() || (eventProps.end && eventProps.end.hasTime()));
  8929. }
  8930. if (eventProps.allDay) {
  8931. eventProps.start.stripTime();
  8932. if (eventProps.end) {
  8933. // TODO: consider nextDayThreshold here? If so, will require a lot of testing and adjustment
  8934. eventProps.end.stripTime();
  8935. }
  8936. }
  8937. else {
  8938. if (!eventProps.start.hasTime()) {
  8939. eventProps.start = t.applyTimezone(eventProps.start.time(0)); // will assign a 00:00 time
  8940. }
  8941. if (eventProps.end && !eventProps.end.hasTime()) {
  8942. eventProps.end = t.applyTimezone(eventProps.end.time(0)); // will assign a 00:00 time
  8943. }
  8944. }
  8945. }
  8946. // If the given event is a recurring event, break it down into an array of individual instances.
  8947. // If not a recurring event, return an array with the single original event.
  8948. // If given a falsy input (probably because of a failed buildEventFromInput call), returns an empty array.
  8949. // HACK: can override the recurring window by providing custom rangeStart/rangeEnd (for businessHours).
  8950. function expandEvent(abstractEvent, _rangeStart, _rangeEnd) {
  8951. var events = [];
  8952. var dowHash;
  8953. var dow;
  8954. var i;
  8955. var date;
  8956. var startTime, endTime;
  8957. var start, end;
  8958. var event;
  8959. _rangeStart = _rangeStart || rangeStart;
  8960. _rangeEnd = _rangeEnd || rangeEnd;
  8961. if (abstractEvent) {
  8962. if (abstractEvent._recurring) {
  8963. // make a boolean hash as to whether the event occurs on each day-of-week
  8964. if ((dow = abstractEvent.dow)) {
  8965. dowHash = {};
  8966. for (i = 0; i < dow.length; i++) {
  8967. dowHash[dow[i]] = true;
  8968. }
  8969. }
  8970. // iterate through every day in the current range
  8971. date = _rangeStart.clone().stripTime(); // holds the date of the current day
  8972. while (date.isBefore(_rangeEnd)) {
  8973. if (!dowHash || dowHash[date.day()]) { // if everyday, or this particular day-of-week
  8974. startTime = abstractEvent.start; // the stored start and end properties are times (Durations)
  8975. endTime = abstractEvent.end; // "
  8976. start = date.clone();
  8977. end = null;
  8978. if (startTime) {
  8979. start = start.time(startTime);
  8980. }
  8981. if (endTime) {
  8982. end = date.clone().time(endTime);
  8983. }
  8984. event = $.extend({}, abstractEvent); // make a copy of the original
  8985. assignDatesToEvent(
  8986. start, end,
  8987. !startTime && !endTime, // allDay?
  8988. event
  8989. );
  8990. events.push(event);
  8991. }
  8992. date.add(1, 'days');
  8993. }
  8994. }
  8995. else {
  8996. events.push(abstractEvent); // return the original event. will be a one-item array
  8997. }
  8998. }
  8999. return events;
  9000. }
  9001. t.expandEvent = expandEvent;
  9002. /* Event Modification Math
  9003. -----------------------------------------------------------------------------------------*/
  9004. // Modifies an event and all related events by applying the given properties.
  9005. // Special date-diffing logic is used for manipulation of dates.
  9006. // If `props` does not contain start/end dates, the updated values are assumed to be the event's current start/end.
  9007. // All date comparisons are done against the event's pristine _start and _end dates.
  9008. // Returns an object with delta information and a function to undo all operations.
  9009. // For making computations in a granularity greater than day/time, specify largeUnit.
  9010. // NOTE: The given `newProps` might be mutated for normalization purposes.
  9011. function mutateEvent(event, newProps, largeUnit) {
  9012. var miscProps = {};
  9013. var oldProps;
  9014. var clearEnd;
  9015. var startDelta;
  9016. var endDelta;
  9017. var durationDelta;
  9018. var undoFunc;
  9019. // diffs the dates in the appropriate way, returning a duration
  9020. function diffDates(date1, date0) { // date1 - date0
  9021. if (largeUnit) {
  9022. return diffByUnit(date1, date0, largeUnit);
  9023. }
  9024. else if (newProps.allDay) {
  9025. return diffDay(date1, date0);
  9026. }
  9027. else {
  9028. return diffDayTime(date1, date0);
  9029. }
  9030. }
  9031. newProps = newProps || {};
  9032. // normalize new date-related properties
  9033. if (!newProps.start) {
  9034. newProps.start = event.start.clone();
  9035. }
  9036. if (newProps.end === undefined) {
  9037. newProps.end = event.end ? event.end.clone() : null;
  9038. }
  9039. if (newProps.allDay == null) { // is null or undefined?
  9040. newProps.allDay = event.allDay;
  9041. }
  9042. normalizeEventDates(newProps);
  9043. // create normalized versions of the original props to compare against
  9044. // need a real end value, for diffing
  9045. oldProps = {
  9046. start: event._start.clone(),
  9047. end: event._end ? event._end.clone() : t.getDefaultEventEnd(event._allDay, event._start),
  9048. allDay: newProps.allDay // normalize the dates in the same regard as the new properties
  9049. };
  9050. normalizeEventDates(oldProps);
  9051. // need to clear the end date if explicitly changed to null
  9052. clearEnd = event._end !== null && newProps.end === null;
  9053. // compute the delta for moving the start date
  9054. startDelta = diffDates(newProps.start, oldProps.start);
  9055. // compute the delta for moving the end date
  9056. if (newProps.end) {
  9057. endDelta = diffDates(newProps.end, oldProps.end);
  9058. durationDelta = endDelta.subtract(startDelta);
  9059. }
  9060. else {
  9061. durationDelta = null;
  9062. }
  9063. // gather all non-date-related properties
  9064. $.each(newProps, function(name, val) {
  9065. if (isMiscEventPropName(name)) {
  9066. if (val !== undefined) {
  9067. miscProps[name] = val;
  9068. }
  9069. }
  9070. });
  9071. // apply the operations to the event and all related events
  9072. undoFunc = mutateEvents(
  9073. clientEvents(event._id), // get events with this ID
  9074. clearEnd,
  9075. newProps.allDay,
  9076. startDelta,
  9077. durationDelta,
  9078. miscProps
  9079. );
  9080. return {
  9081. dateDelta: startDelta,
  9082. durationDelta: durationDelta,
  9083. undo: undoFunc
  9084. };
  9085. }
  9086. // Modifies an array of events in the following ways (operations are in order):
  9087. // - clear the event's `end`
  9088. // - convert the event to allDay
  9089. // - add `dateDelta` to the start and end
  9090. // - add `durationDelta` to the event's duration
  9091. // - assign `miscProps` to the event
  9092. //
  9093. // Returns a function that can be called to undo all the operations.
  9094. //
  9095. // TODO: don't use so many closures. possible memory issues when lots of events with same ID.
  9096. //
  9097. function mutateEvents(events, clearEnd, allDay, dateDelta, durationDelta, miscProps) {
  9098. var isAmbigTimezone = t.getIsAmbigTimezone();
  9099. var undoFunctions = [];
  9100. // normalize zero-length deltas to be null
  9101. if (dateDelta && !dateDelta.valueOf()) { dateDelta = null; }
  9102. if (durationDelta && !durationDelta.valueOf()) { durationDelta = null; }
  9103. $.each(events, function(i, event) {
  9104. var oldProps;
  9105. var newProps;
  9106. // build an object holding all the old values, both date-related and misc.
  9107. // for the undo function.
  9108. oldProps = {
  9109. start: event.start.clone(),
  9110. end: event.end ? event.end.clone() : null,
  9111. allDay: event.allDay
  9112. };
  9113. $.each(miscProps, function(name) {
  9114. oldProps[name] = event[name];
  9115. });
  9116. // new date-related properties. work off the original date snapshot.
  9117. // ok to use references because they will be thrown away when backupEventDates is called.
  9118. newProps = {
  9119. start: event._start,
  9120. end: event._end,
  9121. allDay: allDay // normalize the dates in the same regard as the new properties
  9122. };
  9123. normalizeEventDates(newProps); // massages start/end/allDay
  9124. // strip or ensure the end date
  9125. if (clearEnd) {
  9126. newProps.end = null;
  9127. }
  9128. else if (durationDelta && !newProps.end) { // the duration translation requires an end date
  9129. newProps.end = t.getDefaultEventEnd(newProps.allDay, newProps.start);
  9130. }
  9131. if (dateDelta) {
  9132. newProps.start.add(dateDelta);
  9133. if (newProps.end) {
  9134. newProps.end.add(dateDelta);
  9135. }
  9136. }
  9137. if (durationDelta) {
  9138. newProps.end.add(durationDelta); // end already ensured above
  9139. }
  9140. // if the dates have changed, and we know it is impossible to recompute the
  9141. // timezone offsets, strip the zone.
  9142. if (
  9143. isAmbigTimezone &&
  9144. !newProps.allDay &&
  9145. (dateDelta || durationDelta)
  9146. ) {
  9147. newProps.start.stripZone();
  9148. if (newProps.end) {
  9149. newProps.end.stripZone();
  9150. }
  9151. }
  9152. $.extend(event, miscProps, newProps); // copy over misc props, then date-related props
  9153. backupEventDates(event); // regenerate internal _start/_end/_allDay
  9154. undoFunctions.push(function() {
  9155. $.extend(event, oldProps);
  9156. backupEventDates(event); // regenerate internal _start/_end/_allDay
  9157. });
  9158. });
  9159. return function() {
  9160. for (var i = 0; i < undoFunctions.length; i++) {
  9161. undoFunctions[i]();
  9162. }
  9163. };
  9164. }
  9165. /* Overlapping / Constraining
  9166. -----------------------------------------------------------------------------------------*/
  9167. t.isEventSpanAllowed = isEventSpanAllowed;
  9168. t.isExternalSpanAllowed = isExternalSpanAllowed;
  9169. t.isSelectionSpanAllowed = isSelectionSpanAllowed;
  9170. // Determines if the given event can be relocated to the given span (unzoned start/end with other misc data)
  9171. function isEventSpanAllowed(span, event) {
  9172. var source = event.source || {};
  9173. var constraint = firstDefined(
  9174. event.constraint,
  9175. source.constraint,
  9176. t.options.eventConstraint
  9177. );
  9178. var overlap = firstDefined(
  9179. event.overlap,
  9180. source.overlap,
  9181. t.options.eventOverlap
  9182. );
  9183. return isSpanAllowed(span, constraint, overlap, event);
  9184. }
  9185. // Determines if an external event can be relocated to the given span (unzoned start/end with other misc data)
  9186. function isExternalSpanAllowed(eventSpan, eventLocation, eventProps) {
  9187. var eventInput;
  9188. var event;
  9189. // note: very similar logic is in View's reportExternalDrop
  9190. if (eventProps) {
  9191. eventInput = $.extend({}, eventProps, eventLocation);
  9192. event = expandEvent(buildEventFromInput(eventInput))[0];
  9193. }
  9194. if (event) {
  9195. return isEventSpanAllowed(eventSpan, event);
  9196. }
  9197. else { // treat it as a selection
  9198. return isSelectionSpanAllowed(eventSpan);
  9199. }
  9200. }
  9201. // Determines the given span (unzoned start/end with other misc data) can be selected.
  9202. function isSelectionSpanAllowed(span) {
  9203. return isSpanAllowed(span, t.options.selectConstraint, t.options.selectOverlap);
  9204. }
  9205. // Returns true if the given span (caused by an event drop/resize or a selection) is allowed to exist
  9206. // according to the constraint/overlap settings.
  9207. // `event` is not required if checking a selection.
  9208. function isSpanAllowed(span, constraint, overlap, event) {
  9209. var constraintEvents;
  9210. var anyContainment;
  9211. var peerEvents;
  9212. var i, peerEvent;
  9213. var peerOverlap;
  9214. // the range must be fully contained by at least one of produced constraint events
  9215. if (constraint != null) {
  9216. // not treated as an event! intermediate data structure
  9217. // TODO: use ranges in the future
  9218. constraintEvents = constraintToEvents(constraint);
  9219. anyContainment = false;
  9220. for (i = 0; i < constraintEvents.length; i++) {
  9221. if (t.spanContainsSpan(constraintEvents[i], span)) {
  9222. anyContainment = true;
  9223. break;
  9224. }
  9225. }
  9226. if (!anyContainment) {
  9227. return false;
  9228. }
  9229. }
  9230. peerEvents = t.getPeerEvents(span, event);
  9231. for (i = 0; i < peerEvents.length; i++) {
  9232. peerEvent = peerEvents[i];
  9233. // there needs to be an actual intersection before disallowing anything
  9234. if (eventIntersectsRange(peerEvent, span)) {
  9235. // evaluate overlap for the given range and short-circuit if necessary
  9236. if (overlap === false) {
  9237. return false;
  9238. }
  9239. // if the event's overlap is a test function, pass the peer event in question as the first param
  9240. else if (typeof overlap === 'function' && !overlap(peerEvent, event)) {
  9241. return false;
  9242. }
  9243. // if we are computing if the given range is allowable for an event, consider the other event's
  9244. // EventObject-specific or Source-specific `overlap` property
  9245. if (event) {
  9246. peerOverlap = firstDefined(
  9247. peerEvent.overlap,
  9248. (peerEvent.source || {}).overlap
  9249. // we already considered the global `eventOverlap`
  9250. );
  9251. if (peerOverlap === false) {
  9252. return false;
  9253. }
  9254. // if the peer event's overlap is a test function, pass the subject event as the first param
  9255. if (typeof peerOverlap === 'function' && !peerOverlap(event, peerEvent)) {
  9256. return false;
  9257. }
  9258. }
  9259. }
  9260. }
  9261. return true;
  9262. }
  9263. // Given an event input from the API, produces an array of event objects. Possible event inputs:
  9264. // 'businessHours'
  9265. // An event ID (number or string)
  9266. // An object with specific start/end dates or a recurring event (like what businessHours accepts)
  9267. function constraintToEvents(constraintInput) {
  9268. if (constraintInput === 'businessHours') {
  9269. return t.getCurrentBusinessHourEvents();
  9270. }
  9271. if (typeof constraintInput === 'object') {
  9272. return expandEvent(buildEventFromInput(constraintInput));
  9273. }
  9274. return clientEvents(constraintInput); // probably an ID
  9275. }
  9276. // Does the event's date range intersect with the given range?
  9277. // start/end already assumed to have stripped zones :(
  9278. function eventIntersectsRange(event, range) {
  9279. var eventStart = event.start.clone().stripZone();
  9280. var eventEnd = t.getEventEnd(event).stripZone();
  9281. return range.start < eventEnd && range.end > eventStart;
  9282. }
  9283. t.getEventCache = function() {
  9284. return cache;
  9285. };
  9286. }
  9287. // hook for external libs to manipulate event properties upon creation.
  9288. // should manipulate the event in-place.
  9289. Calendar.prototype.normalizeEvent = function(event) {
  9290. };
  9291. // Does the given span (start, end, and other location information)
  9292. // fully contain the other?
  9293. Calendar.prototype.spanContainsSpan = function(outerSpan, innerSpan) {
  9294. var eventStart = outerSpan.start.clone().stripZone();
  9295. var eventEnd = this.getEventEnd(outerSpan).stripZone();
  9296. return innerSpan.start >= eventStart && innerSpan.end <= eventEnd;
  9297. };
  9298. // Returns a list of events that the given event should be compared against when being considered for a move to
  9299. // the specified span. Attached to the Calendar's prototype because EventManager is a mixin for a Calendar.
  9300. Calendar.prototype.getPeerEvents = function(span, event) {
  9301. var cache = this.getEventCache();
  9302. var peerEvents = [];
  9303. var i, otherEvent;
  9304. for (i = 0; i < cache.length; i++) {
  9305. otherEvent = cache[i];
  9306. if (
  9307. !event ||
  9308. event._id !== otherEvent._id // don't compare the event to itself or other related [repeating] events
  9309. ) {
  9310. peerEvents.push(otherEvent);
  9311. }
  9312. }
  9313. return peerEvents;
  9314. };
  9315. // updates the "backup" properties, which are preserved in order to compute diffs later on.
  9316. function backupEventDates(event) {
  9317. event._allDay = event.allDay;
  9318. event._start = event.start.clone();
  9319. event._end = event.end ? event.end.clone() : null;
  9320. }
  9321. /* Business Hours
  9322. -----------------------------------------------------------------------------------------*/
  9323. var BUSINESS_HOUR_EVENT_DEFAULTS = {
  9324. id: '_fcBusinessHours', // will relate events from different calls to expandEvent
  9325. start: '09:00',
  9326. end: '17:00',
  9327. dow: [ 1, 2, 3, 4, 5 ], // monday - friday
  9328. rendering: 'inverse-background'
  9329. // classNames are defined in businessHoursSegClasses
  9330. };
  9331. // Return events objects for business hours within the current view.
  9332. // Abuse of our event system :(
  9333. Calendar.prototype.getCurrentBusinessHourEvents = function(wholeDay) {
  9334. return this.computeBusinessHourEvents(wholeDay, this.options.businessHours);
  9335. };
  9336. // Given a raw input value from options, return events objects for business hours within the current view.
  9337. Calendar.prototype.computeBusinessHourEvents = function(wholeDay, input) {
  9338. if (input === true) {
  9339. return this.expandBusinessHourEvents(wholeDay, [ {} ]);
  9340. }
  9341. else if ($.isPlainObject(input)) {
  9342. return this.expandBusinessHourEvents(wholeDay, [ input ]);
  9343. }
  9344. else if ($.isArray(input)) {
  9345. return this.expandBusinessHourEvents(wholeDay, input, true);
  9346. }
  9347. else {
  9348. return [];
  9349. }
  9350. };
  9351. // inputs expected to be an array of objects.
  9352. // if ignoreNoDow is true, will ignore entries that don't specify a day-of-week (dow) key.
  9353. Calendar.prototype.expandBusinessHourEvents = function(wholeDay, inputs, ignoreNoDow) {
  9354. var view = this.getView();
  9355. var events = [];
  9356. var i, input;
  9357. for (i = 0; i < inputs.length; i++) {
  9358. input = inputs[i];
  9359. if (ignoreNoDow && !input.dow) {
  9360. continue;
  9361. }
  9362. // give defaults. will make a copy
  9363. input = $.extend({}, BUSINESS_HOUR_EVENT_DEFAULTS, input);
  9364. // if a whole-day series is requested, clear the start/end times
  9365. if (wholeDay) {
  9366. input.start = null;
  9367. input.end = null;
  9368. }
  9369. events.push.apply(events, // append
  9370. this.expandEvent(
  9371. this.buildEventFromInput(input),
  9372. view.start,
  9373. view.end
  9374. )
  9375. );
  9376. }
  9377. return events;
  9378. };
  9379. ;;
  9380. /* An abstract class for the "basic" views, as well as month view. Renders one or more rows of day cells.
  9381. ----------------------------------------------------------------------------------------------------------------------*/
  9382. // It is a manager for a DayGrid subcomponent, which does most of the heavy lifting.
  9383. // It is responsible for managing width/height.
  9384. var BasicView = FC.BasicView = View.extend({
  9385. scroller: null,
  9386. dayGridClass: DayGrid, // class the dayGrid will be instantiated from (overridable by subclasses)
  9387. dayGrid: null, // the main subcomponent that does most of the heavy lifting
  9388. dayNumbersVisible: false, // display day numbers on each day cell?
  9389. weekNumbersVisible: false, // display week numbers along the side?
  9390. weekNumberWidth: null, // width of all the week-number cells running down the side
  9391. headContainerEl: null, // div that hold's the dayGrid's rendered date header
  9392. headRowEl: null, // the fake row element of the day-of-week header
  9393. initialize: function() {
  9394. this.dayGrid = this.instantiateDayGrid();
  9395. this.scroller = new Scroller({
  9396. overflowX: 'hidden',
  9397. overflowY: 'auto'
  9398. });
  9399. },
  9400. // Generates the DayGrid object this view needs. Draws from this.dayGridClass
  9401. instantiateDayGrid: function() {
  9402. // generate a subclass on the fly with BasicView-specific behavior
  9403. // TODO: cache this subclass
  9404. var subclass = this.dayGridClass.extend(basicDayGridMethods);
  9405. return new subclass(this);
  9406. },
  9407. // Sets the display range and computes all necessary dates
  9408. setRange: function(range) {
  9409. View.prototype.setRange.call(this, range); // call the super-method
  9410. this.dayGrid.breakOnWeeks = /year|month|week/.test(this.intervalUnit); // do before setRange
  9411. this.dayGrid.setRange(range);
  9412. },
  9413. // Compute the value to feed into setRange. Overrides superclass.
  9414. computeRange: function(date) {
  9415. var range = View.prototype.computeRange.call(this, date); // get value from the super-method
  9416. // year and month views should be aligned with weeks. this is already done for week
  9417. if (/year|month/.test(range.intervalUnit)) {
  9418. range.start.startOf('week');
  9419. range.start = this.skipHiddenDays(range.start);
  9420. // make end-of-week if not already
  9421. if (range.end.weekday()) {
  9422. range.end.add(1, 'week').startOf('week');
  9423. range.end = this.skipHiddenDays(range.end, -1, true); // exclusively move backwards
  9424. }
  9425. }
  9426. return range;
  9427. },
  9428. // Renders the view into `this.el`, which should already be assigned
  9429. renderDates: function() {
  9430. this.dayNumbersVisible = this.dayGrid.rowCnt > 1; // TODO: make grid responsible
  9431. this.weekNumbersVisible = this.opt('weekNumbers');
  9432. this.dayGrid.numbersVisible = this.dayNumbersVisible || this.weekNumbersVisible;
  9433. this.el.addClass('fc-basic-view').html(this.renderSkeletonHtml());
  9434. this.renderHead();
  9435. this.scroller.render();
  9436. var dayGridContainerEl = this.scroller.el.addClass('fc-day-grid-container');
  9437. var dayGridEl = $('<div class="fc-day-grid" />').appendTo(dayGridContainerEl);
  9438. this.el.find('.fc-body > tr > td').append(dayGridContainerEl);
  9439. this.dayGrid.setElement(dayGridEl);
  9440. this.dayGrid.renderDates(this.hasRigidRows());
  9441. },
  9442. // render the day-of-week headers
  9443. renderHead: function() {
  9444. this.headContainerEl =
  9445. this.el.find('.fc-head-container')
  9446. .html(this.dayGrid.renderHeadHtml());
  9447. this.headRowEl = this.headContainerEl.find('.fc-row');
  9448. },
  9449. // Unrenders the content of the view. Since we haven't separated skeleton rendering from date rendering,
  9450. // always completely kill the dayGrid's rendering.
  9451. unrenderDates: function() {
  9452. this.dayGrid.unrenderDates();
  9453. this.dayGrid.removeElement();
  9454. this.scroller.destroy();
  9455. },
  9456. renderBusinessHours: function() {
  9457. this.dayGrid.renderBusinessHours();
  9458. },
  9459. unrenderBusinessHours: function() {
  9460. this.dayGrid.unrenderBusinessHours();
  9461. },
  9462. // Builds the HTML skeleton for the view.
  9463. // The day-grid component will render inside of a container defined by this HTML.
  9464. renderSkeletonHtml: function() {
  9465. return '' +
  9466. '<table>' +
  9467. '<thead class="fc-head">' +
  9468. '<tr>' +
  9469. '<td class="fc-head-container ' + this.widgetHeaderClass + '"></td>' +
  9470. '</tr>' +
  9471. '</thead>' +
  9472. '<tbody class="fc-body">' +
  9473. '<tr>' +
  9474. '<td class="' + this.widgetContentClass + '"></td>' +
  9475. '</tr>' +
  9476. '</tbody>' +
  9477. '</table>';
  9478. },
  9479. // Generates an HTML attribute string for setting the width of the week number column, if it is known
  9480. weekNumberStyleAttr: function() {
  9481. if (this.weekNumberWidth !== null) {
  9482. return 'style="width:' + this.weekNumberWidth + 'px"';
  9483. }
  9484. return '';
  9485. },
  9486. // Determines whether each row should have a constant height
  9487. hasRigidRows: function() {
  9488. var eventLimit = this.opt('eventLimit');
  9489. return eventLimit && typeof eventLimit !== 'number';
  9490. },
  9491. /* Dimensions
  9492. ------------------------------------------------------------------------------------------------------------------*/
  9493. // Refreshes the horizontal dimensions of the view
  9494. updateWidth: function() {
  9495. if (this.weekNumbersVisible) {
  9496. // Make sure all week number cells running down the side have the same width.
  9497. // Record the width for cells created later.
  9498. this.weekNumberWidth = matchCellWidths(
  9499. this.el.find('.fc-week-number')
  9500. );
  9501. }
  9502. },
  9503. // Adjusts the vertical dimensions of the view to the specified values
  9504. setHeight: function(totalHeight, isAuto) {
  9505. var eventLimit = this.opt('eventLimit');
  9506. var scrollerHeight;
  9507. var scrollbarWidths;
  9508. // reset all heights to be natural
  9509. this.scroller.clear();
  9510. uncompensateScroll(this.headRowEl);
  9511. this.dayGrid.removeSegPopover(); // kill the "more" popover if displayed
  9512. // is the event limit a constant level number?
  9513. if (eventLimit && typeof eventLimit === 'number') {
  9514. this.dayGrid.limitRows(eventLimit); // limit the levels first so the height can redistribute after
  9515. }
  9516. // distribute the height to the rows
  9517. // (totalHeight is a "recommended" value if isAuto)
  9518. scrollerHeight = this.computeScrollerHeight(totalHeight);
  9519. this.setGridHeight(scrollerHeight, isAuto);
  9520. // is the event limit dynamically calculated?
  9521. if (eventLimit && typeof eventLimit !== 'number') {
  9522. this.dayGrid.limitRows(eventLimit); // limit the levels after the grid's row heights have been set
  9523. }
  9524. if (!isAuto) { // should we force dimensions of the scroll container?
  9525. this.scroller.setHeight(scrollerHeight);
  9526. scrollbarWidths = this.scroller.getScrollbarWidths();
  9527. if (scrollbarWidths.left || scrollbarWidths.right) { // using scrollbars?
  9528. compensateScroll(this.headRowEl, scrollbarWidths);
  9529. // doing the scrollbar compensation might have created text overflow which created more height. redo
  9530. scrollerHeight = this.computeScrollerHeight(totalHeight);
  9531. this.scroller.setHeight(scrollerHeight);
  9532. }
  9533. // guarantees the same scrollbar widths
  9534. this.scroller.lockOverflow(scrollbarWidths);
  9535. }
  9536. },
  9537. // given a desired total height of the view, returns what the height of the scroller should be
  9538. computeScrollerHeight: function(totalHeight) {
  9539. return totalHeight -
  9540. subtractInnerElHeight(this.el, this.scroller.el); // everything that's NOT the scroller
  9541. },
  9542. // Sets the height of just the DayGrid component in this view
  9543. setGridHeight: function(height, isAuto) {
  9544. if (isAuto) {
  9545. undistributeHeight(this.dayGrid.rowEls); // let the rows be their natural height with no expanding
  9546. }
  9547. else {
  9548. distributeHeight(this.dayGrid.rowEls, height, true); // true = compensate for height-hogging rows
  9549. }
  9550. },
  9551. /* Scroll
  9552. ------------------------------------------------------------------------------------------------------------------*/
  9553. queryScroll: function() {
  9554. return this.scroller.getScrollTop();
  9555. },
  9556. setScroll: function(top) {
  9557. this.scroller.setScrollTop(top);
  9558. },
  9559. /* Hit Areas
  9560. ------------------------------------------------------------------------------------------------------------------*/
  9561. // forward all hit-related method calls to dayGrid
  9562. prepareHits: function() {
  9563. this.dayGrid.prepareHits();
  9564. },
  9565. releaseHits: function() {
  9566. this.dayGrid.releaseHits();
  9567. },
  9568. queryHit: function(left, top) {
  9569. return this.dayGrid.queryHit(left, top);
  9570. },
  9571. getHitSpan: function(hit) {
  9572. return this.dayGrid.getHitSpan(hit);
  9573. },
  9574. getHitEl: function(hit) {
  9575. return this.dayGrid.getHitEl(hit);
  9576. },
  9577. /* Events
  9578. ------------------------------------------------------------------------------------------------------------------*/
  9579. // Renders the given events onto the view and populates the segments array
  9580. renderEvents: function(events) {
  9581. this.dayGrid.renderEvents(events);
  9582. this.updateHeight(); // must compensate for events that overflow the row
  9583. },
  9584. // Retrieves all segment objects that are rendered in the view
  9585. getEventSegs: function() {
  9586. return this.dayGrid.getEventSegs();
  9587. },
  9588. // Unrenders all event elements and clears internal segment data
  9589. unrenderEvents: function() {
  9590. this.dayGrid.unrenderEvents();
  9591. // we DON'T need to call updateHeight() because:
  9592. // A) a renderEvents() call always happens after this, which will eventually call updateHeight()
  9593. // B) in IE8, this causes a flash whenever events are rerendered
  9594. },
  9595. /* Dragging (for both events and external elements)
  9596. ------------------------------------------------------------------------------------------------------------------*/
  9597. // A returned value of `true` signals that a mock "helper" event has been rendered.
  9598. renderDrag: function(dropLocation, seg) {
  9599. return this.dayGrid.renderDrag(dropLocation, seg);
  9600. },
  9601. unrenderDrag: function() {
  9602. this.dayGrid.unrenderDrag();
  9603. },
  9604. /* Selection
  9605. ------------------------------------------------------------------------------------------------------------------*/
  9606. // Renders a visual indication of a selection
  9607. renderSelection: function(span) {
  9608. this.dayGrid.renderSelection(span);
  9609. },
  9610. // Unrenders a visual indications of a selection
  9611. unrenderSelection: function() {
  9612. this.dayGrid.unrenderSelection();
  9613. }
  9614. });
  9615. // Methods that will customize the rendering behavior of the BasicView's dayGrid
  9616. var basicDayGridMethods = {
  9617. // Generates the HTML that will go before the day-of week header cells
  9618. renderHeadIntroHtml: function() {
  9619. var view = this.view;
  9620. if (view.weekNumbersVisible) {
  9621. return '' +
  9622. '<th class="fc-week-number ' + view.widgetHeaderClass + '" ' + view.weekNumberStyleAttr() + '>' +
  9623. '<span>' + // needed for matchCellWidths
  9624. htmlEscape(view.opt('weekNumberTitle')) +
  9625. '</span>' +
  9626. '</th>';
  9627. }
  9628. return '';
  9629. },
  9630. // Generates the HTML that will go before content-skeleton cells that display the day/week numbers
  9631. renderNumberIntroHtml: function(row) {
  9632. var view = this.view;
  9633. if (view.weekNumbersVisible) {
  9634. return '' +
  9635. '<td class="fc-week-number" ' + view.weekNumberStyleAttr() + '>' +
  9636. '<span>' + // needed for matchCellWidths
  9637. this.getCellDate(row, 0).format('w') +
  9638. '</span>' +
  9639. '</td>';
  9640. }
  9641. return '';
  9642. },
  9643. // Generates the HTML that goes before the day bg cells for each day-row
  9644. renderBgIntroHtml: function() {
  9645. var view = this.view;
  9646. if (view.weekNumbersVisible) {
  9647. return '<td class="fc-week-number ' + view.widgetContentClass + '" ' +
  9648. view.weekNumberStyleAttr() + '></td>';
  9649. }
  9650. return '';
  9651. },
  9652. // Generates the HTML that goes before every other type of row generated by DayGrid.
  9653. // Affects helper-skeleton and highlight-skeleton rows.
  9654. renderIntroHtml: function() {
  9655. var view = this.view;
  9656. if (view.weekNumbersVisible) {
  9657. return '<td class="fc-week-number" ' + view.weekNumberStyleAttr() + '></td>';
  9658. }
  9659. return '';
  9660. }
  9661. };
  9662. ;;
  9663. /* A month view with day cells running in rows (one-per-week) and columns
  9664. ----------------------------------------------------------------------------------------------------------------------*/
  9665. var MonthView = FC.MonthView = BasicView.extend({
  9666. // Produces information about what range to display
  9667. computeRange: function(date) {
  9668. var range = BasicView.prototype.computeRange.call(this, date); // get value from super-method
  9669. var rowCnt;
  9670. // ensure 6 weeks
  9671. if (this.isFixedWeeks()) {
  9672. rowCnt = Math.ceil(range.end.diff(range.start, 'weeks', true)); // could be partial weeks due to hiddenDays
  9673. range.end.add(6 - rowCnt, 'weeks');
  9674. }
  9675. return range;
  9676. },
  9677. // Overrides the default BasicView behavior to have special multi-week auto-height logic
  9678. setGridHeight: function(height, isAuto) {
  9679. isAuto = isAuto || this.opt('weekMode') === 'variable'; // LEGACY: weekMode is deprecated
  9680. // if auto, make the height of each row the height that it would be if there were 6 weeks
  9681. if (isAuto) {
  9682. height *= this.rowCnt / 6;
  9683. }
  9684. distributeHeight(this.dayGrid.rowEls, height, !isAuto); // if auto, don't compensate for height-hogging rows
  9685. },
  9686. isFixedWeeks: function() {
  9687. var weekMode = this.opt('weekMode'); // LEGACY: weekMode is deprecated
  9688. if (weekMode) {
  9689. return weekMode === 'fixed'; // if any other type of weekMode, assume NOT fixed
  9690. }
  9691. return this.opt('fixedWeekCount');
  9692. }
  9693. });
  9694. ;;
  9695. fcViews.basic = {
  9696. 'class': BasicView
  9697. };
  9698. fcViews.basicDay = {
  9699. type: 'basic',
  9700. duration: { days: 1 }
  9701. };
  9702. fcViews.basicWeek = {
  9703. type: 'basic',
  9704. duration: { weeks: 1 }
  9705. };
  9706. fcViews.month = {
  9707. 'class': MonthView,
  9708. duration: { months: 1 }, // important for prev/next
  9709. defaults: {
  9710. fixedWeekCount: true
  9711. }
  9712. };
  9713. ;;
  9714. /* An abstract class for all agenda-related views. Displays one more columns with time slots running vertically.
  9715. ----------------------------------------------------------------------------------------------------------------------*/
  9716. // Is a manager for the TimeGrid subcomponent and possibly the DayGrid subcomponent (if allDaySlot is on).
  9717. // Responsible for managing width/height.
  9718. var AgendaView = FC.AgendaView = View.extend({
  9719. scroller: null,
  9720. timeGridClass: TimeGrid, // class used to instantiate the timeGrid. subclasses can override
  9721. timeGrid: null, // the main time-grid subcomponent of this view
  9722. dayGridClass: DayGrid, // class used to instantiate the dayGrid. subclasses can override
  9723. dayGrid: null, // the "all-day" subcomponent. if all-day is turned off, this will be null
  9724. axisWidth: null, // the width of the time axis running down the side
  9725. headContainerEl: null, // div that hold's the timeGrid's rendered date header
  9726. noScrollRowEls: null, // set of fake row elements that must compensate when scroller has scrollbars
  9727. // when the time-grid isn't tall enough to occupy the given height, we render an <hr> underneath
  9728. bottomRuleEl: null,
  9729. initialize: function() {
  9730. this.timeGrid = this.instantiateTimeGrid();
  9731. if (this.opt('allDaySlot')) { // should we display the "all-day" area?
  9732. this.dayGrid = this.instantiateDayGrid(); // the all-day subcomponent of this view
  9733. }
  9734. this.scroller = new Scroller({
  9735. overflowX: 'hidden',
  9736. overflowY: 'auto'
  9737. });
  9738. },
  9739. // Instantiates the TimeGrid object this view needs. Draws from this.timeGridClass
  9740. instantiateTimeGrid: function() {
  9741. var subclass = this.timeGridClass.extend(agendaTimeGridMethods);
  9742. return new subclass(this);
  9743. },
  9744. // Instantiates the DayGrid object this view might need. Draws from this.dayGridClass
  9745. instantiateDayGrid: function() {
  9746. var subclass = this.dayGridClass.extend(agendaDayGridMethods);
  9747. return new subclass(this);
  9748. },
  9749. /* Rendering
  9750. ------------------------------------------------------------------------------------------------------------------*/
  9751. // Sets the display range and computes all necessary dates
  9752. setRange: function(range) {
  9753. View.prototype.setRange.call(this, range); // call the super-method
  9754. this.timeGrid.setRange(range);
  9755. if (this.dayGrid) {
  9756. this.dayGrid.setRange(range);
  9757. }
  9758. },
  9759. // Renders the view into `this.el`, which has already been assigned
  9760. renderDates: function() {
  9761. this.el.addClass('fc-agenda-view').html(this.renderSkeletonHtml());
  9762. this.renderHead();
  9763. this.scroller.render();
  9764. var timeGridWrapEl = this.scroller.el.addClass('fc-time-grid-container');
  9765. var timeGridEl = $('<div class="fc-time-grid" />').appendTo(timeGridWrapEl);
  9766. this.el.find('.fc-body > tr > td').append(timeGridWrapEl);
  9767. this.timeGrid.setElement(timeGridEl);
  9768. this.timeGrid.renderDates();
  9769. // the <hr> that sometimes displays under the time-grid
  9770. this.bottomRuleEl = $('<hr class="fc-divider ' + this.widgetHeaderClass + '"/>')
  9771. .appendTo(this.timeGrid.el); // inject it into the time-grid
  9772. if (this.dayGrid) {
  9773. this.dayGrid.setElement(this.el.find('.fc-day-grid'));
  9774. this.dayGrid.renderDates();
  9775. // have the day-grid extend it's coordinate area over the <hr> dividing the two grids
  9776. this.dayGrid.bottomCoordPadding = this.dayGrid.el.next('hr').outerHeight();
  9777. }
  9778. this.noScrollRowEls = this.el.find('.fc-row:not(.fc-scroller *)'); // fake rows not within the scroller
  9779. },
  9780. // render the day-of-week headers
  9781. renderHead: function() {
  9782. this.headContainerEl =
  9783. this.el.find('.fc-head-container')
  9784. .html(this.timeGrid.renderHeadHtml());
  9785. },
  9786. // Unrenders the content of the view. Since we haven't separated skeleton rendering from date rendering,
  9787. // always completely kill each grid's rendering.
  9788. unrenderDates: function() {
  9789. this.timeGrid.unrenderDates();
  9790. this.timeGrid.removeElement();
  9791. if (this.dayGrid) {
  9792. this.dayGrid.unrenderDates();
  9793. this.dayGrid.removeElement();
  9794. }
  9795. this.scroller.destroy();
  9796. },
  9797. // Builds the HTML skeleton for the view.
  9798. // The day-grid and time-grid components will render inside containers defined by this HTML.
  9799. renderSkeletonHtml: function() {
  9800. return '' +
  9801. '<table>' +
  9802. '<thead class="fc-head">' +
  9803. '<tr>' +
  9804. '<td class="fc-head-container ' + this.widgetHeaderClass + '"></td>' +
  9805. '</tr>' +
  9806. '</thead>' +
  9807. '<tbody class="fc-body">' +
  9808. '<tr>' +
  9809. '<td class="' + this.widgetContentClass + '">' +
  9810. (this.dayGrid ?
  9811. '<div class="fc-day-grid"/>' +
  9812. '<hr class="fc-divider ' + this.widgetHeaderClass + '"/>' :
  9813. ''
  9814. ) +
  9815. '</td>' +
  9816. '</tr>' +
  9817. '</tbody>' +
  9818. '</table>';
  9819. },
  9820. // Generates an HTML attribute string for setting the width of the axis, if it is known
  9821. axisStyleAttr: function() {
  9822. if (this.axisWidth !== null) {
  9823. return 'style="width:' + this.axisWidth + 'px"';
  9824. }
  9825. return '';
  9826. },
  9827. /* Business Hours
  9828. ------------------------------------------------------------------------------------------------------------------*/
  9829. renderBusinessHours: function() {
  9830. this.timeGrid.renderBusinessHours();
  9831. if (this.dayGrid) {
  9832. this.dayGrid.renderBusinessHours();
  9833. }
  9834. },
  9835. unrenderBusinessHours: function() {
  9836. this.timeGrid.unrenderBusinessHours();
  9837. if (this.dayGrid) {
  9838. this.dayGrid.unrenderBusinessHours();
  9839. }
  9840. },
  9841. /* Now Indicator
  9842. ------------------------------------------------------------------------------------------------------------------*/
  9843. getNowIndicatorUnit: function() {
  9844. return this.timeGrid.getNowIndicatorUnit();
  9845. },
  9846. renderNowIndicator: function(date) {
  9847. this.timeGrid.renderNowIndicator(date);
  9848. },
  9849. unrenderNowIndicator: function() {
  9850. this.timeGrid.unrenderNowIndicator();
  9851. },
  9852. /* Dimensions
  9853. ------------------------------------------------------------------------------------------------------------------*/
  9854. updateSize: function(isResize) {
  9855. this.timeGrid.updateSize(isResize);
  9856. View.prototype.updateSize.call(this, isResize); // call the super-method
  9857. },
  9858. // Refreshes the horizontal dimensions of the view
  9859. updateWidth: function() {
  9860. // make all axis cells line up, and record the width so newly created axis cells will have it
  9861. this.axisWidth = matchCellWidths(this.el.find('.fc-axis'));
  9862. },
  9863. // Adjusts the vertical dimensions of the view to the specified values
  9864. setHeight: function(totalHeight, isAuto) {
  9865. var eventLimit;
  9866. var scrollerHeight;
  9867. var scrollbarWidths;
  9868. // reset all dimensions back to the original state
  9869. this.bottomRuleEl.hide(); // .show() will be called later if this <hr> is necessary
  9870. this.scroller.clear(); // sets height to 'auto' and clears overflow
  9871. uncompensateScroll(this.noScrollRowEls);
  9872. // limit number of events in the all-day area
  9873. if (this.dayGrid) {
  9874. this.dayGrid.removeSegPopover(); // kill the "more" popover if displayed
  9875. eventLimit = this.opt('eventLimit');
  9876. if (eventLimit && typeof eventLimit !== 'number') {
  9877. eventLimit = AGENDA_ALL_DAY_EVENT_LIMIT; // make sure "auto" goes to a real number
  9878. }
  9879. if (eventLimit) {
  9880. this.dayGrid.limitRows(eventLimit);
  9881. }
  9882. }
  9883. if (!isAuto) { // should we force dimensions of the scroll container?
  9884. scrollerHeight = this.computeScrollerHeight(totalHeight);
  9885. this.scroller.setHeight(scrollerHeight);
  9886. scrollbarWidths = this.scroller.getScrollbarWidths();
  9887. if (scrollbarWidths.left || scrollbarWidths.right) { // using scrollbars?
  9888. // make the all-day and header rows lines up
  9889. compensateScroll(this.noScrollRowEls, scrollbarWidths);
  9890. // the scrollbar compensation might have changed text flow, which might affect height, so recalculate
  9891. // and reapply the desired height to the scroller.
  9892. scrollerHeight = this.computeScrollerHeight(totalHeight);
  9893. this.scroller.setHeight(scrollerHeight);
  9894. }
  9895. // guarantees the same scrollbar widths
  9896. this.scroller.lockOverflow(scrollbarWidths);
  9897. // if there's any space below the slats, show the horizontal rule.
  9898. // this won't cause any new overflow, because lockOverflow already called.
  9899. if (this.timeGrid.getTotalSlatHeight() < scrollerHeight) {
  9900. this.bottomRuleEl.show();
  9901. }
  9902. }
  9903. },
  9904. // given a desired total height of the view, returns what the height of the scroller should be
  9905. computeScrollerHeight: function(totalHeight) {
  9906. return totalHeight -
  9907. subtractInnerElHeight(this.el, this.scroller.el); // everything that's NOT the scroller
  9908. },
  9909. /* Scroll
  9910. ------------------------------------------------------------------------------------------------------------------*/
  9911. // Computes the initial pre-configured scroll state prior to allowing the user to change it
  9912. computeInitialScroll: function() {
  9913. var scrollTime = moment.duration(this.opt('scrollTime'));
  9914. var top = this.timeGrid.computeTimeTop(scrollTime);
  9915. // zoom can give weird floating-point values. rather scroll a little bit further
  9916. top = Math.ceil(top);
  9917. if (top) {
  9918. top++; // to overcome top border that slots beyond the first have. looks better
  9919. }
  9920. return top;
  9921. },
  9922. queryScroll: function() {
  9923. return this.scroller.getScrollTop();
  9924. },
  9925. setScroll: function(top) {
  9926. this.scroller.setScrollTop(top);
  9927. },
  9928. /* Hit Areas
  9929. ------------------------------------------------------------------------------------------------------------------*/
  9930. // forward all hit-related method calls to the grids (dayGrid might not be defined)
  9931. prepareHits: function() {
  9932. this.timeGrid.prepareHits();
  9933. if (this.dayGrid) {
  9934. this.dayGrid.prepareHits();
  9935. }
  9936. },
  9937. releaseHits: function() {
  9938. this.timeGrid.releaseHits();
  9939. if (this.dayGrid) {
  9940. this.dayGrid.releaseHits();
  9941. }
  9942. },
  9943. queryHit: function(left, top) {
  9944. var hit = this.timeGrid.queryHit(left, top);
  9945. if (!hit && this.dayGrid) {
  9946. hit = this.dayGrid.queryHit(left, top);
  9947. }
  9948. return hit;
  9949. },
  9950. getHitSpan: function(hit) {
  9951. // TODO: hit.component is set as a hack to identify where the hit came from
  9952. return hit.component.getHitSpan(hit);
  9953. },
  9954. getHitEl: function(hit) {
  9955. // TODO: hit.component is set as a hack to identify where the hit came from
  9956. return hit.component.getHitEl(hit);
  9957. },
  9958. /* Events
  9959. ------------------------------------------------------------------------------------------------------------------*/
  9960. // Renders events onto the view and populates the View's segment array
  9961. renderEvents: function(events) {
  9962. var dayEvents = [];
  9963. var timedEvents = [];
  9964. var daySegs = [];
  9965. var timedSegs;
  9966. var i;
  9967. // separate the events into all-day and timed
  9968. for (i = 0; i < events.length; i++) {
  9969. if (events[i].allDay) {
  9970. dayEvents.push(events[i]);
  9971. }
  9972. else {
  9973. timedEvents.push(events[i]);
  9974. }
  9975. }
  9976. // render the events in the subcomponents
  9977. timedSegs = this.timeGrid.renderEvents(timedEvents);
  9978. if (this.dayGrid) {
  9979. daySegs = this.dayGrid.renderEvents(dayEvents);
  9980. }
  9981. // the all-day area is flexible and might have a lot of events, so shift the height
  9982. this.updateHeight();
  9983. },
  9984. // Retrieves all segment objects that are rendered in the view
  9985. getEventSegs: function() {
  9986. return this.timeGrid.getEventSegs().concat(
  9987. this.dayGrid ? this.dayGrid.getEventSegs() : []
  9988. );
  9989. },
  9990. // Unrenders all event elements and clears internal segment data
  9991. unrenderEvents: function() {
  9992. // unrender the events in the subcomponents
  9993. this.timeGrid.unrenderEvents();
  9994. if (this.dayGrid) {
  9995. this.dayGrid.unrenderEvents();
  9996. }
  9997. // we DON'T need to call updateHeight() because:
  9998. // A) a renderEvents() call always happens after this, which will eventually call updateHeight()
  9999. // B) in IE8, this causes a flash whenever events are rerendered
  10000. },
  10001. /* Dragging (for events and external elements)
  10002. ------------------------------------------------------------------------------------------------------------------*/
  10003. // A returned value of `true` signals that a mock "helper" event has been rendered.
  10004. renderDrag: function(dropLocation, seg) {
  10005. if (dropLocation.start.hasTime()) {
  10006. return this.timeGrid.renderDrag(dropLocation, seg);
  10007. }
  10008. else if (this.dayGrid) {
  10009. return this.dayGrid.renderDrag(dropLocation, seg);
  10010. }
  10011. },
  10012. unrenderDrag: function() {
  10013. this.timeGrid.unrenderDrag();
  10014. if (this.dayGrid) {
  10015. this.dayGrid.unrenderDrag();
  10016. }
  10017. },
  10018. /* Selection
  10019. ------------------------------------------------------------------------------------------------------------------*/
  10020. // Renders a visual indication of a selection
  10021. renderSelection: function(span) {
  10022. if (span.start.hasTime() || span.end.hasTime()) {
  10023. this.timeGrid.renderSelection(span);
  10024. }
  10025. else if (this.dayGrid) {
  10026. this.dayGrid.renderSelection(span);
  10027. }
  10028. },
  10029. // Unrenders a visual indications of a selection
  10030. unrenderSelection: function() {
  10031. this.timeGrid.unrenderSelection();
  10032. if (this.dayGrid) {
  10033. this.dayGrid.unrenderSelection();
  10034. }
  10035. }
  10036. });
  10037. // Methods that will customize the rendering behavior of the AgendaView's timeGrid
  10038. // TODO: move into TimeGrid
  10039. var agendaTimeGridMethods = {
  10040. // Generates the HTML that will go before the day-of week header cells
  10041. renderHeadIntroHtml: function() {
  10042. var view = this.view;
  10043. var weekText;
  10044. if (view.opt('weekNumbers')) {
  10045. weekText = this.start.format(view.opt('smallWeekFormat'));
  10046. return '' +
  10047. '<th class="fc-axis fc-week-number ' + view.widgetHeaderClass + '" ' + view.axisStyleAttr() + '>' +
  10048. '<span>' + // needed for matchCellWidths
  10049. htmlEscape(weekText) +
  10050. '</span>' +
  10051. '</th>';
  10052. }
  10053. else {
  10054. return '<th class="fc-axis ' + view.widgetHeaderClass + '" ' + view.axisStyleAttr() + '></th>';
  10055. }
  10056. },
  10057. // Generates the HTML that goes before the bg of the TimeGrid slot area. Long vertical column.
  10058. renderBgIntroHtml: function() {
  10059. var view = this.view;
  10060. return '<td class="fc-axis ' + view.widgetContentClass + '" ' + view.axisStyleAttr() + '></td>';
  10061. },
  10062. // Generates the HTML that goes before all other types of cells.
  10063. // Affects content-skeleton, helper-skeleton, highlight-skeleton for both the time-grid and day-grid.
  10064. renderIntroHtml: function() {
  10065. var view = this.view;
  10066. return '<td class="fc-axis" ' + view.axisStyleAttr() + '></td>';
  10067. }
  10068. };
  10069. // Methods that will customize the rendering behavior of the AgendaView's dayGrid
  10070. var agendaDayGridMethods = {
  10071. // Generates the HTML that goes before the all-day cells
  10072. renderBgIntroHtml: function() {
  10073. var view = this.view;
  10074. return '' +
  10075. '<td class="fc-axis ' + view.widgetContentClass + '" ' + view.axisStyleAttr() + '>' +
  10076. '<span>' + // needed for matchCellWidths
  10077. (view.opt('allDayHtml') || htmlEscape(view.opt('allDayText'))) +
  10078. '</span>' +
  10079. '</td>';
  10080. },
  10081. // Generates the HTML that goes before all other types of cells.
  10082. // Affects content-skeleton, helper-skeleton, highlight-skeleton for both the time-grid and day-grid.
  10083. renderIntroHtml: function() {
  10084. var view = this.view;
  10085. return '<td class="fc-axis" ' + view.axisStyleAttr() + '></td>';
  10086. }
  10087. };
  10088. ;;
  10089. var AGENDA_ALL_DAY_EVENT_LIMIT = 5;
  10090. // potential nice values for the slot-duration and interval-duration
  10091. // from largest to smallest
  10092. var AGENDA_STOCK_SUB_DURATIONS = [
  10093. { hours: 1 },
  10094. { minutes: 30 },
  10095. { minutes: 15 },
  10096. { seconds: 30 },
  10097. { seconds: 15 }
  10098. ];
  10099. fcViews.agenda = {
  10100. 'class': AgendaView,
  10101. defaults: {
  10102. allDaySlot: true,
  10103. allDayText: 'all-day',
  10104. slotDuration: '00:30:00',
  10105. minTime: '00:00:00',
  10106. maxTime: '24:00:00',
  10107. slotEventOverlap: true // a bad name. confused with overlap/constraint system
  10108. }
  10109. };
  10110. fcViews.agendaDay = {
  10111. type: 'agenda',
  10112. duration: { days: 1 }
  10113. };
  10114. fcViews.agendaWeek = {
  10115. type: 'agenda',
  10116. duration: { weeks: 1 }
  10117. };
  10118. ;;
  10119. return FC; // export for Node/CommonJS
  10120. });