fullcalendar.js 174 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083
  1. /*!
  2. * FullCalendar v2.0.2
  3. * Docs & License: http://arshaw.com/fullcalendar/
  4. * (c) 2013 Adam Shaw
  5. */
  6. (function(factory) {
  7. if (typeof define === 'function' && define.amd) {
  8. define([ 'jquery', 'moment' ], factory);
  9. }
  10. else {
  11. factory(jQuery, moment);
  12. }
  13. })(function($, moment) {
  14. ;;
  15. var defaults = {
  16. lang: 'en',
  17. defaultTimedEventDuration: '02:00:00',
  18. defaultAllDayEventDuration: { days: 1 },
  19. forceEventDuration: false,
  20. nextDayThreshold: '09:00:00', // 9am
  21. // display
  22. defaultView: 'month',
  23. aspectRatio: 1.35,
  24. header: {
  25. left: 'title',
  26. center: '',
  27. right: 'today prev,next'
  28. },
  29. weekends: true,
  30. weekNumbers: false,
  31. weekNumberTitle: 'W',
  32. weekNumberCalculation: 'local',
  33. //editable: false,
  34. // event ajax
  35. lazyFetching: true,
  36. startParam: 'start',
  37. endParam: 'end',
  38. timezoneParam: 'timezone',
  39. timezone: false,
  40. //allDayDefault: undefined,
  41. // time formats
  42. titleFormat: {
  43. month: 'MMMM YYYY', // like "September 1986". each language will override this
  44. week: 'll', // like "Sep 4 1986"
  45. day: 'LL' // like "September 4 1986"
  46. },
  47. columnFormat: {
  48. month: 'ddd', // like "Sat"
  49. week: generateWeekColumnFormat,
  50. day: 'dddd' // like "Saturday"
  51. },
  52. timeFormat: { // for event elements
  53. 'default': generateShortTimeFormat
  54. },
  55. displayEventEnd: {
  56. month: false,
  57. basicWeek: false,
  58. 'default': true
  59. },
  60. // locale
  61. isRTL: false,
  62. defaultButtonText: {
  63. prev: "prev",
  64. next: "next",
  65. prevYear: "prev year",
  66. nextYear: "next year",
  67. today: 'today',
  68. month: 'month',
  69. week: 'week',
  70. day: 'day'
  71. },
  72. buttonIcons: {
  73. prev: 'left-single-arrow',
  74. next: 'right-single-arrow',
  75. prevYear: 'left-double-arrow',
  76. nextYear: 'right-double-arrow'
  77. },
  78. // jquery-ui theming
  79. theme: false,
  80. themeButtonIcons: {
  81. prev: 'circle-triangle-w',
  82. next: 'circle-triangle-e',
  83. prevYear: 'seek-prev',
  84. nextYear: 'seek-next'
  85. },
  86. //selectable: false,
  87. unselectAuto: true,
  88. dropAccept: '*',
  89. handleWindowResize: true,
  90. windowResizeDelay: 200 // milliseconds before a rerender happens
  91. };
  92. function generateShortTimeFormat(options, langData) {
  93. return langData.longDateFormat('LT')
  94. .replace(':mm', '(:mm)')
  95. .replace(/(\Wmm)$/, '($1)') // like above, but for foreign langs
  96. .replace(/\s*a$/i, 't'); // convert to AM/PM/am/pm to lowercase one-letter. remove any spaces beforehand
  97. }
  98. function generateWeekColumnFormat(options, langData) {
  99. var format = langData.longDateFormat('L'); // for the format like "MM/DD/YYYY"
  100. format = format.replace(/^Y+[^\w\s]*|[^\w\s]*Y+$/g, ''); // strip the year off the edge, as well as other misc non-whitespace chars
  101. if (options.isRTL) {
  102. format += ' ddd'; // for RTL, add day-of-week to end
  103. }
  104. else {
  105. format = 'ddd ' + format; // for LTR, add day-of-week to beginning
  106. }
  107. return format;
  108. }
  109. var langOptionHash = {
  110. en: {
  111. columnFormat: {
  112. week: 'ddd M/D' // override for english. different from the generated default, which is MM/DD
  113. }
  114. }
  115. };
  116. // right-to-left defaults
  117. var rtlDefaults = {
  118. header: {
  119. left: 'next,prev today',
  120. center: '',
  121. right: 'title'
  122. },
  123. buttonIcons: {
  124. prev: 'right-single-arrow',
  125. next: 'left-single-arrow',
  126. prevYear: 'right-double-arrow',
  127. nextYear: 'left-double-arrow'
  128. },
  129. themeButtonIcons: {
  130. prev: 'circle-triangle-e',
  131. next: 'circle-triangle-w',
  132. nextYear: 'seek-prev',
  133. prevYear: 'seek-next'
  134. }
  135. };
  136. ;;
  137. var fc = $.fullCalendar = { version: "2.0.2" };
  138. var fcViews = fc.views = {};
  139. $.fn.fullCalendar = function(options) {
  140. var args = Array.prototype.slice.call(arguments, 1); // for a possible method call
  141. var res = this; // what this function will return (this jQuery object by default)
  142. this.each(function(i, _element) { // loop each DOM element involved
  143. var element = $(_element);
  144. var calendar = element.data('fullCalendar'); // get the existing calendar object (if any)
  145. var singleRes; // the returned value of this single method call
  146. // a method call
  147. if (typeof options === 'string') {
  148. if (calendar && $.isFunction(calendar[options])) {
  149. singleRes = calendar[options].apply(calendar, args);
  150. if (!i) {
  151. res = singleRes; // record the first method call result
  152. }
  153. if (options === 'destroy') { // for the destroy method, must remove Calendar object data
  154. element.removeData('fullCalendar');
  155. }
  156. }
  157. }
  158. // a new calendar initialization
  159. else if (!calendar) { // don't initialize twice
  160. calendar = new Calendar(element, options);
  161. element.data('fullCalendar', calendar);
  162. calendar.render();
  163. }
  164. });
  165. return res;
  166. };
  167. // function for adding/overriding defaults
  168. function setDefaults(d) {
  169. mergeOptions(defaults, d);
  170. }
  171. // Recursively combines option hash-objects.
  172. // Better than `$.extend(true, ...)` because arrays are not traversed/copied.
  173. //
  174. // called like:
  175. // mergeOptions(target, obj1, obj2, ...)
  176. //
  177. function mergeOptions(target) {
  178. function mergeIntoTarget(name, value) {
  179. if ($.isPlainObject(value) && $.isPlainObject(target[name]) && !isForcedAtomicOption(name)) {
  180. // merge into a new object to avoid destruction
  181. target[name] = mergeOptions({}, target[name], value); // combine. `value` object takes precedence
  182. }
  183. else if (value !== undefined) { // only use values that are set and not undefined
  184. target[name] = value;
  185. }
  186. }
  187. for (var i=1; i<arguments.length; i++) {
  188. $.each(arguments[i], mergeIntoTarget);
  189. }
  190. return target;
  191. }
  192. // overcome sucky view-option-hash and option-merging behavior messing with options it shouldn't
  193. function isForcedAtomicOption(name) {
  194. // Any option that ends in "Time" or "Duration" is probably a Duration,
  195. // and these will commonly be specified as plain objects, which we don't want to mess up.
  196. return /(Time|Duration)$/.test(name);
  197. }
  198. // FIX: find a different solution for view-option-hashes and have a whitelist
  199. // for options that can be recursively merged.
  200. ;;
  201. //var langOptionHash = {}; // initialized in defaults.js
  202. fc.langs = langOptionHash; // expose
  203. // Initialize jQuery UI Datepicker translations while using some of the translations
  204. // for our own purposes. Will set this as the default language for datepicker.
  205. // Called from a translation file.
  206. fc.datepickerLang = function(langCode, datepickerLangCode, options) {
  207. var langOptions = langOptionHash[langCode];
  208. // initialize FullCalendar's lang hash for this language
  209. if (!langOptions) {
  210. langOptions = langOptionHash[langCode] = {};
  211. }
  212. // merge certain Datepicker options into FullCalendar's options
  213. mergeOptions(langOptions, {
  214. isRTL: options.isRTL,
  215. weekNumberTitle: options.weekHeader,
  216. titleFormat: {
  217. month: options.showMonthAfterYear ?
  218. 'YYYY[' + options.yearSuffix + '] MMMM' :
  219. 'MMMM YYYY[' + options.yearSuffix + ']'
  220. },
  221. defaultButtonText: {
  222. // the translations sometimes wrongly contain HTML entities
  223. prev: stripHTMLEntities(options.prevText),
  224. next: stripHTMLEntities(options.nextText),
  225. today: stripHTMLEntities(options.currentText)
  226. }
  227. });
  228. // is jQuery UI Datepicker is on the page?
  229. if ($.datepicker) {
  230. // Register the language data.
  231. // FullCalendar and MomentJS use language codes like "pt-br" but Datepicker
  232. // does it like "pt-BR" or if it doesn't have the language, maybe just "pt".
  233. // Make an alias so the language can be referenced either way.
  234. $.datepicker.regional[datepickerLangCode] =
  235. $.datepicker.regional[langCode] = // alias
  236. options;
  237. // Alias 'en' to the default language data. Do this every time.
  238. $.datepicker.regional.en = $.datepicker.regional[''];
  239. // Set as Datepicker's global defaults.
  240. $.datepicker.setDefaults(options);
  241. }
  242. };
  243. // Sets FullCalendar-specific translations. Also sets the language as the global default.
  244. // Called from a translation file.
  245. fc.lang = function(langCode, options) {
  246. var langOptions;
  247. if (options) {
  248. langOptions = langOptionHash[langCode];
  249. // initialize the hash for this language
  250. if (!langOptions) {
  251. langOptions = langOptionHash[langCode] = {};
  252. }
  253. mergeOptions(langOptions, options || {});
  254. }
  255. // set it as the default language for FullCalendar
  256. defaults.lang = langCode;
  257. };
  258. ;;
  259. function Calendar(element, instanceOptions) {
  260. var t = this;
  261. // Build options object
  262. // -----------------------------------------------------------------------------------
  263. // Precedence (lowest to highest): defaults, rtlDefaults, langOptions, instanceOptions
  264. instanceOptions = instanceOptions || {};
  265. var options = mergeOptions({}, defaults, instanceOptions);
  266. var langOptions;
  267. // determine language options
  268. if (options.lang in langOptionHash) {
  269. langOptions = langOptionHash[options.lang];
  270. }
  271. else {
  272. langOptions = langOptionHash[defaults.lang];
  273. }
  274. if (langOptions) { // if language options exist, rebuild...
  275. options = mergeOptions({}, defaults, langOptions, instanceOptions);
  276. }
  277. if (options.isRTL) { // is isRTL, rebuild...
  278. options = mergeOptions({}, defaults, rtlDefaults, langOptions || {}, instanceOptions);
  279. }
  280. // Exports
  281. // -----------------------------------------------------------------------------------
  282. t.options = options;
  283. t.render = render;
  284. t.destroy = destroy;
  285. t.refetchEvents = refetchEvents;
  286. t.reportEvents = reportEvents;
  287. t.reportEventChange = reportEventChange;
  288. t.rerenderEvents = rerenderEvents;
  289. t.changeView = changeView;
  290. t.select = select;
  291. t.unselect = unselect;
  292. t.prev = prev;
  293. t.next = next;
  294. t.prevYear = prevYear;
  295. t.nextYear = nextYear;
  296. t.today = today;
  297. t.gotoDate = gotoDate;
  298. t.incrementDate = incrementDate;
  299. t.getDate = getDate;
  300. t.getCalendar = getCalendar;
  301. t.getView = getView;
  302. t.option = option;
  303. t.trigger = trigger;
  304. // Language-data Internals
  305. // -----------------------------------------------------------------------------------
  306. // Apply overrides to the current language's data
  307. var langData = createObject( // make a cheap clone
  308. moment.langData(options.lang)
  309. );
  310. if (options.monthNames) {
  311. langData._months = options.monthNames;
  312. }
  313. if (options.monthNamesShort) {
  314. langData._monthsShort = options.monthNamesShort;
  315. }
  316. if (options.dayNames) {
  317. langData._weekdays = options.dayNames;
  318. }
  319. if (options.dayNamesShort) {
  320. langData._weekdaysShort = options.dayNamesShort;
  321. }
  322. if (options.firstDay != null) {
  323. var _week = createObject(langData._week); // _week: { dow: # }
  324. _week.dow = options.firstDay;
  325. langData._week = _week;
  326. }
  327. // Calendar-specific Date Utilities
  328. // -----------------------------------------------------------------------------------
  329. t.defaultAllDayEventDuration = moment.duration(options.defaultAllDayEventDuration);
  330. t.defaultTimedEventDuration = moment.duration(options.defaultTimedEventDuration);
  331. // Builds a moment using the settings of the current calendar: timezone and language.
  332. // Accepts anything the vanilla moment() constructor accepts.
  333. t.moment = function() {
  334. var mom;
  335. if (options.timezone === 'local') {
  336. mom = fc.moment.apply(null, arguments);
  337. // Force the moment to be local, because fc.moment doesn't guarantee it.
  338. if (mom.hasTime()) { // don't give ambiguously-timed moments a local zone
  339. mom.local();
  340. }
  341. }
  342. else if (options.timezone === 'UTC') {
  343. mom = fc.moment.utc.apply(null, arguments); // process as UTC
  344. }
  345. else {
  346. mom = fc.moment.parseZone.apply(null, arguments); // let the input decide the zone
  347. }
  348. mom._lang = langData;
  349. return mom;
  350. };
  351. // Returns a boolean about whether or not the calendar knows how to calculate
  352. // the timezone offset of arbitrary dates in the current timezone.
  353. t.getIsAmbigTimezone = function() {
  354. return options.timezone !== 'local' && options.timezone !== 'UTC';
  355. };
  356. // Returns a copy of the given date in the current timezone of it is ambiguously zoned.
  357. // This will also give the date an unambiguous time.
  358. t.rezoneDate = function(date) {
  359. return t.moment(date.toArray());
  360. };
  361. // Returns a moment for the current date, as defined by the client's computer,
  362. // or overridden by the `now` option.
  363. t.getNow = function() {
  364. var now = options.now;
  365. if (typeof now === 'function') {
  366. now = now();
  367. }
  368. return t.moment(now);
  369. };
  370. // Calculates the week number for a moment according to the calendar's
  371. // `weekNumberCalculation` setting.
  372. t.calculateWeekNumber = function(mom) {
  373. var calc = options.weekNumberCalculation;
  374. if (typeof calc === 'function') {
  375. return calc(mom);
  376. }
  377. else if (calc === 'local') {
  378. return mom.week();
  379. }
  380. else if (calc.toUpperCase() === 'ISO') {
  381. return mom.isoWeek();
  382. }
  383. };
  384. // Get an event's normalized end date. If not present, calculate it from the defaults.
  385. t.getEventEnd = function(event) {
  386. if (event.end) {
  387. return event.end.clone();
  388. }
  389. else {
  390. return t.getDefaultEventEnd(event.allDay, event.start);
  391. }
  392. };
  393. // Given an event's allDay status and start date, return swhat its fallback end date should be.
  394. t.getDefaultEventEnd = function(allDay, start) { // TODO: rename to computeDefaultEventEnd
  395. var end = start.clone();
  396. if (allDay) {
  397. end.stripTime().add(t.defaultAllDayEventDuration);
  398. }
  399. else {
  400. end.add(t.defaultTimedEventDuration);
  401. }
  402. if (t.getIsAmbigTimezone()) {
  403. end.stripZone(); // we don't know what the tzo should be
  404. }
  405. return end;
  406. };
  407. // Date-formatting Utilities
  408. // -----------------------------------------------------------------------------------
  409. // Like the vanilla formatRange, but with calendar-specific settings applied.
  410. t.formatRange = function(m1, m2, formatStr) {
  411. // a function that returns a formatStr // TODO: in future, precompute this
  412. if (typeof formatStr === 'function') {
  413. formatStr = formatStr.call(t, options, langData);
  414. }
  415. return formatRange(m1, m2, formatStr, null, options.isRTL);
  416. };
  417. // Like the vanilla formatDate, but with calendar-specific settings applied.
  418. t.formatDate = function(mom, formatStr) {
  419. // a function that returns a formatStr // TODO: in future, precompute this
  420. if (typeof formatStr === 'function') {
  421. formatStr = formatStr.call(t, options, langData);
  422. }
  423. return formatDate(mom, formatStr);
  424. };
  425. // Imports
  426. // -----------------------------------------------------------------------------------
  427. EventManager.call(t, options);
  428. var isFetchNeeded = t.isFetchNeeded;
  429. var fetchEvents = t.fetchEvents;
  430. // Locals
  431. // -----------------------------------------------------------------------------------
  432. var _element = element[0];
  433. var header;
  434. var headerElement;
  435. var content;
  436. var tm; // for making theme classes
  437. var currentView;
  438. var elementOuterWidth;
  439. var suggestedViewHeight;
  440. var resizeUID = 0;
  441. var ignoreWindowResize = 0;
  442. var date;
  443. var events = [];
  444. var _dragElement;
  445. // Main Rendering
  446. // -----------------------------------------------------------------------------------
  447. if (options.defaultDate != null) {
  448. date = t.moment(options.defaultDate);
  449. }
  450. else {
  451. date = t.getNow();
  452. }
  453. function render(inc) {
  454. if (!content) {
  455. initialRender();
  456. }
  457. else if (elementVisible()) {
  458. // mainly for the public API
  459. calcSize();
  460. _renderView(inc);
  461. }
  462. }
  463. function initialRender() {
  464. tm = options.theme ? 'ui' : 'fc';
  465. element.addClass('fc');
  466. if (options.isRTL) {
  467. element.addClass('fc-rtl');
  468. }
  469. else {
  470. element.addClass('fc-ltr');
  471. }
  472. if (options.theme) {
  473. element.addClass('ui-widget');
  474. }
  475. content = $("<div class='fc-content' />")
  476. .prependTo(element);
  477. header = new Header(t, options);
  478. headerElement = header.render();
  479. if (headerElement) {
  480. element.prepend(headerElement);
  481. }
  482. changeView(options.defaultView);
  483. if (options.handleWindowResize) {
  484. $(window).resize(windowResize);
  485. }
  486. // needed for IE in a 0x0 iframe, b/c when it is resized, never triggers a windowResize
  487. if (!bodyVisible()) {
  488. lateRender();
  489. }
  490. }
  491. // called when we know the calendar couldn't be rendered when it was initialized,
  492. // but we think it's ready now
  493. function lateRender() {
  494. setTimeout(function() { // IE7 needs this so dimensions are calculated correctly
  495. if (!currentView.start && bodyVisible()) { // !currentView.start makes sure this never happens more than once
  496. renderView();
  497. }
  498. },0);
  499. }
  500. function destroy() {
  501. if (currentView) {
  502. trigger('viewDestroy', currentView, currentView, currentView.element);
  503. currentView.triggerEventDestroy();
  504. }
  505. $(window).unbind('resize', windowResize);
  506. if (options.droppable) {
  507. $(document)
  508. .off('dragstart', droppableDragStart)
  509. .off('dragstop', droppableDragStop);
  510. }
  511. if (currentView.selectionManagerDestroy) {
  512. currentView.selectionManagerDestroy();
  513. }
  514. header.destroy();
  515. content.remove();
  516. element.removeClass('fc fc-ltr fc-rtl ui-widget');
  517. }
  518. function elementVisible() {
  519. return element.is(':visible');
  520. }
  521. function bodyVisible() {
  522. return $('body').is(':visible');
  523. }
  524. // View Rendering
  525. // -----------------------------------------------------------------------------------
  526. function changeView(newViewName) {
  527. if (!currentView || newViewName != currentView.name) {
  528. _changeView(newViewName);
  529. }
  530. }
  531. function _changeView(newViewName) {
  532. ignoreWindowResize++;
  533. if (currentView) {
  534. trigger('viewDestroy', currentView, currentView, currentView.element);
  535. unselect();
  536. currentView.triggerEventDestroy(); // trigger 'eventDestroy' for each event
  537. freezeContentHeight();
  538. currentView.element.remove();
  539. header.deactivateButton(currentView.name);
  540. }
  541. header.activateButton(newViewName);
  542. currentView = new fcViews[newViewName](
  543. $("<div class='fc-view fc-view-" + newViewName + "' />")
  544. .appendTo(content),
  545. t // the calendar object
  546. );
  547. renderView();
  548. unfreezeContentHeight();
  549. ignoreWindowResize--;
  550. }
  551. function renderView(inc) {
  552. if (
  553. !currentView.start || // never rendered before
  554. inc || // explicit date window change
  555. !date.isWithin(currentView.intervalStart, currentView.intervalEnd) // implicit date window change
  556. ) {
  557. if (elementVisible()) {
  558. _renderView(inc);
  559. }
  560. }
  561. }
  562. function _renderView(inc) { // assumes elementVisible
  563. ignoreWindowResize++;
  564. if (currentView.start) { // already been rendered?
  565. trigger('viewDestroy', currentView, currentView, currentView.element);
  566. unselect();
  567. clearEvents();
  568. }
  569. freezeContentHeight();
  570. if (inc) {
  571. date = currentView.incrementDate(date, inc);
  572. }
  573. currentView.render(date.clone()); // the view's render method ONLY renders the skeleton, nothing else
  574. setSize();
  575. unfreezeContentHeight();
  576. (currentView.afterRender || noop)();
  577. updateTitle();
  578. updateTodayButton();
  579. trigger('viewRender', currentView, currentView, currentView.element);
  580. ignoreWindowResize--;
  581. getAndRenderEvents();
  582. }
  583. // Resizing
  584. // -----------------------------------------------------------------------------------
  585. function updateSize() {
  586. if (elementVisible()) {
  587. unselect();
  588. clearEvents();
  589. calcSize();
  590. setSize();
  591. renderEvents();
  592. }
  593. }
  594. function calcSize() { // assumes elementVisible
  595. if (options.contentHeight) {
  596. suggestedViewHeight = options.contentHeight;
  597. }
  598. else if (options.height) {
  599. suggestedViewHeight = options.height - (headerElement ? headerElement.height() : 0) - vsides(content);
  600. }
  601. else {
  602. suggestedViewHeight = Math.round(content.width() / Math.max(options.aspectRatio, .5));
  603. }
  604. }
  605. function setSize() { // assumes elementVisible
  606. if (suggestedViewHeight === undefined) {
  607. calcSize(); // for first time
  608. // NOTE: we don't want to recalculate on every renderView because
  609. // it could result in oscillating heights due to scrollbars.
  610. }
  611. ignoreWindowResize++;
  612. currentView.setHeight(suggestedViewHeight);
  613. currentView.setWidth(content.width());
  614. ignoreWindowResize--;
  615. elementOuterWidth = element.outerWidth();
  616. }
  617. function windowResize(ev) {
  618. if (
  619. !ignoreWindowResize &&
  620. ev.target === window // so we don't process jqui "resize" events that have bubbled up
  621. ) {
  622. if (currentView.start) { // view has already been rendered
  623. var uid = ++resizeUID;
  624. setTimeout(function() { // add a delay
  625. if (uid == resizeUID && !ignoreWindowResize && elementVisible()) {
  626. if (elementOuterWidth != (elementOuterWidth = element.outerWidth())) {
  627. ignoreWindowResize++; // in case the windowResize callback changes the height
  628. updateSize();
  629. currentView.trigger('windowResize', _element);
  630. ignoreWindowResize--;
  631. }
  632. }
  633. }, options.windowResizeDelay);
  634. }else{
  635. // calendar must have been initialized in a 0x0 iframe that has just been resized
  636. lateRender();
  637. }
  638. }
  639. }
  640. /* Event Fetching/Rendering
  641. -----------------------------------------------------------------------------*/
  642. // TODO: going forward, most of this stuff should be directly handled by the view
  643. function refetchEvents() { // can be called as an API method
  644. clearEvents();
  645. fetchAndRenderEvents();
  646. }
  647. function rerenderEvents(modifiedEventID) { // can be called as an API method
  648. clearEvents();
  649. renderEvents(modifiedEventID);
  650. }
  651. function renderEvents(modifiedEventID) { // TODO: remove modifiedEventID hack
  652. if (elementVisible()) {
  653. currentView.renderEvents(events, modifiedEventID); // actually render the DOM elements
  654. currentView.trigger('eventAfterAllRender');
  655. }
  656. }
  657. function clearEvents() {
  658. currentView.triggerEventDestroy(); // trigger 'eventDestroy' for each event
  659. currentView.clearEvents(); // actually remove the DOM elements
  660. currentView.clearEventData(); // for View.js, TODO: unify with clearEvents
  661. }
  662. function getAndRenderEvents() {
  663. if (!options.lazyFetching || isFetchNeeded(currentView.start, currentView.end)) {
  664. fetchAndRenderEvents();
  665. }
  666. else {
  667. renderEvents();
  668. }
  669. }
  670. function fetchAndRenderEvents() {
  671. fetchEvents(currentView.start, currentView.end);
  672. // ... will call reportEvents
  673. // ... which will call renderEvents
  674. }
  675. // called when event data arrives
  676. function reportEvents(_events) {
  677. events = _events;
  678. renderEvents();
  679. }
  680. // called when a single event's data has been changed
  681. function reportEventChange(eventID) {
  682. rerenderEvents(eventID);
  683. }
  684. /* Header Updating
  685. -----------------------------------------------------------------------------*/
  686. function updateTitle() {
  687. header.updateTitle(currentView.title);
  688. }
  689. function updateTodayButton() {
  690. var now = t.getNow();
  691. if (now.isWithin(currentView.intervalStart, currentView.intervalEnd)) {
  692. header.disableButton('today');
  693. }
  694. else {
  695. header.enableButton('today');
  696. }
  697. }
  698. /* Selection
  699. -----------------------------------------------------------------------------*/
  700. function select(start, end) {
  701. currentView.select(start, end);
  702. }
  703. function unselect() { // safe to be called before renderView
  704. if (currentView) {
  705. currentView.unselect();
  706. }
  707. }
  708. /* Date
  709. -----------------------------------------------------------------------------*/
  710. function prev() {
  711. renderView(-1);
  712. }
  713. function next() {
  714. renderView(1);
  715. }
  716. function prevYear() {
  717. date.add('years', -1);
  718. renderView();
  719. }
  720. function nextYear() {
  721. date.add('years', 1);
  722. renderView();
  723. }
  724. function today() {
  725. date = t.getNow();
  726. renderView();
  727. }
  728. function gotoDate(dateInput) {
  729. date = t.moment(dateInput);
  730. renderView();
  731. }
  732. function incrementDate(delta) {
  733. date.add(moment.duration(delta));
  734. renderView();
  735. }
  736. function getDate() {
  737. return date.clone();
  738. }
  739. /* Height "Freezing"
  740. -----------------------------------------------------------------------------*/
  741. function freezeContentHeight() {
  742. content.css({
  743. width: '100%',
  744. height: content.height(),
  745. overflow: 'hidden'
  746. });
  747. }
  748. function unfreezeContentHeight() {
  749. content.css({
  750. width: '',
  751. height: '',
  752. overflow: ''
  753. });
  754. }
  755. /* Misc
  756. -----------------------------------------------------------------------------*/
  757. function getCalendar() {
  758. return t;
  759. }
  760. function getView() {
  761. return currentView;
  762. }
  763. function option(name, value) {
  764. if (value === undefined) {
  765. return options[name];
  766. }
  767. if (name == 'height' || name == 'contentHeight' || name == 'aspectRatio') {
  768. options[name] = value;
  769. updateSize();
  770. }
  771. }
  772. function trigger(name, thisObj) {
  773. if (options[name]) {
  774. return options[name].apply(
  775. thisObj || _element,
  776. Array.prototype.slice.call(arguments, 2)
  777. );
  778. }
  779. }
  780. /* External Dragging
  781. ------------------------------------------------------------------------*/
  782. if (options.droppable) {
  783. // TODO: unbind on destroy
  784. $(document)
  785. .on('dragstart', droppableDragStart)
  786. .on('dragstop', droppableDragStop);
  787. // this is undone in destroy
  788. }
  789. function droppableDragStart(ev, ui) {
  790. var _e = ev.target;
  791. var e = $(_e);
  792. if (!e.parents('.fc').length) { // not already inside a calendar
  793. var accept = options.dropAccept;
  794. if ($.isFunction(accept) ? accept.call(_e, e) : e.is(accept)) {
  795. _dragElement = _e;
  796. currentView.dragStart(_dragElement, ev, ui);
  797. }
  798. }
  799. }
  800. function droppableDragStop(ev, ui) {
  801. if (_dragElement) {
  802. currentView.dragStop(_dragElement, ev, ui);
  803. _dragElement = null;
  804. }
  805. }
  806. }
  807. ;;
  808. function Header(calendar, options) {
  809. var t = this;
  810. // exports
  811. t.render = render;
  812. t.destroy = destroy;
  813. t.updateTitle = updateTitle;
  814. t.activateButton = activateButton;
  815. t.deactivateButton = deactivateButton;
  816. t.disableButton = disableButton;
  817. t.enableButton = enableButton;
  818. // locals
  819. var element = $([]);
  820. var tm;
  821. function render() {
  822. tm = options.theme ? 'ui' : 'fc';
  823. var sections = options.header;
  824. if (sections) {
  825. element = $("<table class='fc-header' style='width:100%'/>")
  826. .append(
  827. $("<tr/>")
  828. .append(renderSection('left'))
  829. .append(renderSection('center'))
  830. .append(renderSection('right'))
  831. );
  832. return element;
  833. }
  834. }
  835. function destroy() {
  836. element.remove();
  837. }
  838. function renderSection(position) {
  839. var e = $("<td class='fc-header-" + position + "'/>");
  840. var buttonStr = options.header[position];
  841. if (buttonStr) {
  842. $.each(buttonStr.split(' '), function(i) {
  843. if (i > 0) {
  844. e.append("<span class='fc-header-space'/>");
  845. }
  846. var prevButton;
  847. $.each(this.split(','), function(j, buttonName) {
  848. if (buttonName == 'title') {
  849. e.append("<span class='fc-header-title'><h2>&nbsp;</h2></span>");
  850. if (prevButton) {
  851. prevButton.addClass(tm + '-corner-right');
  852. }
  853. prevButton = null;
  854. }else{
  855. var buttonClick;
  856. if (calendar[buttonName]) {
  857. buttonClick = calendar[buttonName]; // calendar method
  858. }
  859. else if (fcViews[buttonName]) {
  860. buttonClick = function() {
  861. button.removeClass(tm + '-state-hover'); // forget why
  862. calendar.changeView(buttonName);
  863. };
  864. }
  865. if (buttonClick) {
  866. // smartProperty allows different text per view button (ex: "Agenda Week" vs "Basic Week")
  867. var themeIcon = smartProperty(options.themeButtonIcons, buttonName);
  868. var normalIcon = smartProperty(options.buttonIcons, buttonName);
  869. var defaultText = smartProperty(options.defaultButtonText, buttonName);
  870. var customText = smartProperty(options.buttonText, buttonName);
  871. var html;
  872. if (customText) {
  873. html = htmlEscape(customText);
  874. }
  875. else if (themeIcon && options.theme) {
  876. html = "<span class='ui-icon ui-icon-" + themeIcon + "'></span>";
  877. }
  878. else if (normalIcon && !options.theme) {
  879. html = "<span class='fc-icon fc-icon-" + normalIcon + "'></span>";
  880. }
  881. else {
  882. html = htmlEscape(defaultText || buttonName);
  883. }
  884. var button = $(
  885. "<span class='fc-button fc-button-" + buttonName + " " + tm + "-state-default'>" +
  886. html +
  887. "</span>"
  888. )
  889. .click(function() {
  890. if (!button.hasClass(tm + '-state-disabled')) {
  891. buttonClick();
  892. }
  893. })
  894. .mousedown(function() {
  895. button
  896. .not('.' + tm + '-state-active')
  897. .not('.' + tm + '-state-disabled')
  898. .addClass(tm + '-state-down');
  899. })
  900. .mouseup(function() {
  901. button.removeClass(tm + '-state-down');
  902. })
  903. .hover(
  904. function() {
  905. button
  906. .not('.' + tm + '-state-active')
  907. .not('.' + tm + '-state-disabled')
  908. .addClass(tm + '-state-hover');
  909. },
  910. function() {
  911. button
  912. .removeClass(tm + '-state-hover')
  913. .removeClass(tm + '-state-down');
  914. }
  915. )
  916. .appendTo(e);
  917. disableTextSelection(button);
  918. if (!prevButton) {
  919. button.addClass(tm + '-corner-left');
  920. }
  921. prevButton = button;
  922. }
  923. }
  924. });
  925. if (prevButton) {
  926. prevButton.addClass(tm + '-corner-right');
  927. }
  928. });
  929. }
  930. return e;
  931. }
  932. function updateTitle(html) {
  933. element.find('h2')
  934. .html(html);
  935. }
  936. function activateButton(buttonName) {
  937. element.find('span.fc-button-' + buttonName)
  938. .addClass(tm + '-state-active');
  939. }
  940. function deactivateButton(buttonName) {
  941. element.find('span.fc-button-' + buttonName)
  942. .removeClass(tm + '-state-active');
  943. }
  944. function disableButton(buttonName) {
  945. element.find('span.fc-button-' + buttonName)
  946. .addClass(tm + '-state-disabled');
  947. }
  948. function enableButton(buttonName) {
  949. element.find('span.fc-button-' + buttonName)
  950. .removeClass(tm + '-state-disabled');
  951. }
  952. }
  953. ;;
  954. fc.sourceNormalizers = [];
  955. fc.sourceFetchers = [];
  956. var ajaxDefaults = {
  957. dataType: 'json',
  958. cache: false
  959. };
  960. var eventGUID = 1;
  961. function EventManager(options) { // assumed to be a calendar
  962. var t = this;
  963. // exports
  964. t.isFetchNeeded = isFetchNeeded;
  965. t.fetchEvents = fetchEvents;
  966. t.addEventSource = addEventSource;
  967. t.removeEventSource = removeEventSource;
  968. t.updateEvent = updateEvent;
  969. t.renderEvent = renderEvent;
  970. t.removeEvents = removeEvents;
  971. t.clientEvents = clientEvents;
  972. t.mutateEvent = mutateEvent;
  973. // imports
  974. var trigger = t.trigger;
  975. var getView = t.getView;
  976. var reportEvents = t.reportEvents;
  977. var getEventEnd = t.getEventEnd;
  978. // locals
  979. var stickySource = { events: [] };
  980. var sources = [ stickySource ];
  981. var rangeStart, rangeEnd;
  982. var currentFetchID = 0;
  983. var pendingSourceCnt = 0;
  984. var loadingLevel = 0;
  985. var cache = [];
  986. $.each(
  987. (options.events ? [ options.events ] : []).concat(options.eventSources || []),
  988. function(i, sourceInput) {
  989. var source = buildEventSource(sourceInput);
  990. if (source) {
  991. sources.push(source);
  992. }
  993. }
  994. );
  995. /* Fetching
  996. -----------------------------------------------------------------------------*/
  997. function isFetchNeeded(start, end) {
  998. return !rangeStart || // nothing has been fetched yet?
  999. // or, a part of the new range is outside of the old range? (after normalizing)
  1000. start.clone().stripZone() < rangeStart.clone().stripZone() ||
  1001. end.clone().stripZone() > rangeEnd.clone().stripZone();
  1002. }
  1003. function fetchEvents(start, end) {
  1004. rangeStart = start;
  1005. rangeEnd = end;
  1006. cache = [];
  1007. var fetchID = ++currentFetchID;
  1008. var len = sources.length;
  1009. pendingSourceCnt = len;
  1010. for (var i=0; i<len; i++) {
  1011. fetchEventSource(sources[i], fetchID);
  1012. }
  1013. }
  1014. function fetchEventSource(source, fetchID) {
  1015. _fetchEventSource(source, function(events) {
  1016. var isArraySource = $.isArray(source.events);
  1017. var i;
  1018. var event;
  1019. if (fetchID == currentFetchID) {
  1020. if (events) {
  1021. for (i=0; i<events.length; i++) {
  1022. event = events[i];
  1023. // event array sources have already been convert to Event Objects
  1024. if (!isArraySource) {
  1025. event = buildEvent(event, source);
  1026. }
  1027. if (event) {
  1028. cache.push(event);
  1029. }
  1030. }
  1031. }
  1032. pendingSourceCnt--;
  1033. if (!pendingSourceCnt) {
  1034. reportEvents(cache);
  1035. }
  1036. }
  1037. });
  1038. }
  1039. function _fetchEventSource(source, callback) {
  1040. var i;
  1041. var fetchers = fc.sourceFetchers;
  1042. var res;
  1043. for (i=0; i<fetchers.length; i++) {
  1044. res = fetchers[i].call(
  1045. t, // this, the Calendar object
  1046. source,
  1047. rangeStart.clone(),
  1048. rangeEnd.clone(),
  1049. options.timezone,
  1050. callback
  1051. );
  1052. if (res === true) {
  1053. // the fetcher is in charge. made its own async request
  1054. return;
  1055. }
  1056. else if (typeof res == 'object') {
  1057. // the fetcher returned a new source. process it
  1058. _fetchEventSource(res, callback);
  1059. return;
  1060. }
  1061. }
  1062. var events = source.events;
  1063. if (events) {
  1064. if ($.isFunction(events)) {
  1065. pushLoading();
  1066. events.call(
  1067. t, // this, the Calendar object
  1068. rangeStart.clone(),
  1069. rangeEnd.clone(),
  1070. options.timezone,
  1071. function(events) {
  1072. callback(events);
  1073. popLoading();
  1074. }
  1075. );
  1076. }
  1077. else if ($.isArray(events)) {
  1078. callback(events);
  1079. }
  1080. else {
  1081. callback();
  1082. }
  1083. }else{
  1084. var url = source.url;
  1085. if (url) {
  1086. var success = source.success;
  1087. var error = source.error;
  1088. var complete = source.complete;
  1089. // retrieve any outbound GET/POST $.ajax data from the options
  1090. var customData;
  1091. if ($.isFunction(source.data)) {
  1092. // supplied as a function that returns a key/value object
  1093. customData = source.data();
  1094. }
  1095. else {
  1096. // supplied as a straight key/value object
  1097. customData = source.data;
  1098. }
  1099. // use a copy of the custom data so we can modify the parameters
  1100. // and not affect the passed-in object.
  1101. var data = $.extend({}, customData || {});
  1102. var startParam = firstDefined(source.startParam, options.startParam);
  1103. var endParam = firstDefined(source.endParam, options.endParam);
  1104. var timezoneParam = firstDefined(source.timezoneParam, options.timezoneParam);
  1105. if (startParam) {
  1106. data[startParam] = rangeStart.format();
  1107. }
  1108. if (endParam) {
  1109. data[endParam] = rangeEnd.format();
  1110. }
  1111. if (options.timezone && options.timezone != 'local') {
  1112. data[timezoneParam] = options.timezone;
  1113. }
  1114. pushLoading();
  1115. $.ajax($.extend({}, ajaxDefaults, source, {
  1116. data: data,
  1117. success: function(events) {
  1118. events = events || [];
  1119. var res = applyAll(success, this, arguments);
  1120. if ($.isArray(res)) {
  1121. events = res;
  1122. }
  1123. callback(events);
  1124. },
  1125. error: function() {
  1126. applyAll(error, this, arguments);
  1127. callback();
  1128. },
  1129. complete: function() {
  1130. applyAll(complete, this, arguments);
  1131. popLoading();
  1132. }
  1133. }));
  1134. }else{
  1135. callback();
  1136. }
  1137. }
  1138. }
  1139. /* Sources
  1140. -----------------------------------------------------------------------------*/
  1141. function addEventSource(sourceInput) {
  1142. var source = buildEventSource(sourceInput);
  1143. if (source) {
  1144. sources.push(source);
  1145. pendingSourceCnt++;
  1146. fetchEventSource(source, currentFetchID); // will eventually call reportEvents
  1147. }
  1148. }
  1149. function buildEventSource(sourceInput) { // will return undefined if invalid source
  1150. var normalizers = fc.sourceNormalizers;
  1151. var source;
  1152. var i;
  1153. if ($.isFunction(sourceInput) || $.isArray(sourceInput)) {
  1154. source = { events: sourceInput };
  1155. }
  1156. else if (typeof sourceInput === 'string') {
  1157. source = { url: sourceInput };
  1158. }
  1159. else if (typeof sourceInput === 'object') {
  1160. source = $.extend({}, sourceInput); // shallow copy
  1161. if (typeof source.className === 'string') {
  1162. // TODO: repeat code, same code for event classNames
  1163. source.className = source.className.split(/\s+/);
  1164. }
  1165. }
  1166. if (source) {
  1167. // for array sources, we convert to standard Event Objects up front
  1168. if ($.isArray(source.events)) {
  1169. source.events = $.map(source.events, function(eventInput) {
  1170. return buildEvent(eventInput, source);
  1171. });
  1172. }
  1173. for (i=0; i<normalizers.length; i++) {
  1174. normalizers[i].call(t, source);
  1175. }
  1176. return source;
  1177. }
  1178. }
  1179. function removeEventSource(source) {
  1180. sources = $.grep(sources, function(src) {
  1181. return !isSourcesEqual(src, source);
  1182. });
  1183. // remove all client events from that source
  1184. cache = $.grep(cache, function(e) {
  1185. return !isSourcesEqual(e.source, source);
  1186. });
  1187. reportEvents(cache);
  1188. }
  1189. function isSourcesEqual(source1, source2) {
  1190. return source1 && source2 && getSourcePrimitive(source1) == getSourcePrimitive(source2);
  1191. }
  1192. function getSourcePrimitive(source) {
  1193. return ((typeof source == 'object') ? (source.events || source.url) : '') || source;
  1194. }
  1195. /* Manipulation
  1196. -----------------------------------------------------------------------------*/
  1197. function updateEvent(event) {
  1198. event.start = t.moment(event.start);
  1199. if (event.end) {
  1200. event.end = t.moment(event.end);
  1201. }
  1202. mutateEvent(event);
  1203. propagateMiscProperties(event);
  1204. reportEvents(cache); // reports event modifications (so we can redraw)
  1205. }
  1206. var miscCopyableProps = [
  1207. 'title',
  1208. 'url',
  1209. 'allDay',
  1210. 'className',
  1211. 'editable',
  1212. 'color',
  1213. 'backgroundColor',
  1214. 'borderColor',
  1215. 'textColor'
  1216. ];
  1217. function propagateMiscProperties(event) {
  1218. var i;
  1219. var cachedEvent;
  1220. var j;
  1221. var prop;
  1222. for (i=0; i<cache.length; i++) {
  1223. cachedEvent = cache[i];
  1224. if (cachedEvent._id == event._id && cachedEvent !== event) {
  1225. for (j=0; j<miscCopyableProps.length; j++) {
  1226. prop = miscCopyableProps[j];
  1227. if (event[prop] !== undefined) {
  1228. cachedEvent[prop] = event[prop];
  1229. }
  1230. }
  1231. }
  1232. }
  1233. }
  1234. function renderEvent(eventData, stick) {
  1235. var event = buildEvent(eventData);
  1236. if (event) {
  1237. if (!event.source) {
  1238. if (stick) {
  1239. stickySource.events.push(event);
  1240. event.source = stickySource;
  1241. }
  1242. cache.push(event);
  1243. }
  1244. reportEvents(cache);
  1245. }
  1246. }
  1247. function removeEvents(filter) {
  1248. var eventID;
  1249. var i;
  1250. if (filter == null) { // null or undefined. remove all events
  1251. filter = function() { return true; }; // will always match
  1252. }
  1253. else if (!$.isFunction(filter)) { // an event ID
  1254. eventID = filter + '';
  1255. filter = function(event) {
  1256. return event._id == eventID;
  1257. };
  1258. }
  1259. // Purge event(s) from our local cache
  1260. cache = $.grep(cache, filter, true); // inverse=true
  1261. // Remove events from array sources.
  1262. // This works because they have been converted to official Event Objects up front.
  1263. // (and as a result, event._id has been calculated).
  1264. for (i=0; i<sources.length; i++) {
  1265. if ($.isArray(sources[i].events)) {
  1266. sources[i].events = $.grep(sources[i].events, filter, true);
  1267. }
  1268. }
  1269. reportEvents(cache);
  1270. }
  1271. function clientEvents(filter) {
  1272. if ($.isFunction(filter)) {
  1273. return $.grep(cache, filter);
  1274. }
  1275. else if (filter != null) { // not null, not undefined. an event ID
  1276. filter += '';
  1277. return $.grep(cache, function(e) {
  1278. return e._id == filter;
  1279. });
  1280. }
  1281. return cache; // else, return all
  1282. }
  1283. /* Loading State
  1284. -----------------------------------------------------------------------------*/
  1285. function pushLoading() {
  1286. if (!(loadingLevel++)) {
  1287. trigger('loading', null, true, getView());
  1288. }
  1289. }
  1290. function popLoading() {
  1291. if (!(--loadingLevel)) {
  1292. trigger('loading', null, false, getView());
  1293. }
  1294. }
  1295. /* Event Normalization
  1296. -----------------------------------------------------------------------------*/
  1297. function buildEvent(data, source) { // source may be undefined!
  1298. var out = {};
  1299. var start;
  1300. var end;
  1301. var allDay;
  1302. var allDayDefault;
  1303. if (options.eventDataTransform) {
  1304. data = options.eventDataTransform(data);
  1305. }
  1306. if (source && source.eventDataTransform) {
  1307. data = source.eventDataTransform(data);
  1308. }
  1309. start = t.moment(data.start || data.date); // "date" is an alias for "start"
  1310. if (!start.isValid()) {
  1311. return;
  1312. }
  1313. end = null;
  1314. if (data.end) {
  1315. end = t.moment(data.end);
  1316. if (!end.isValid()) {
  1317. return;
  1318. }
  1319. }
  1320. allDay = data.allDay;
  1321. if (allDay === undefined) {
  1322. allDayDefault = firstDefined(
  1323. source ? source.allDayDefault : undefined,
  1324. options.allDayDefault
  1325. );
  1326. if (allDayDefault !== undefined) {
  1327. // use the default
  1328. allDay = allDayDefault;
  1329. }
  1330. else {
  1331. // all dates need to have ambig time for the event to be considered allDay
  1332. allDay = !start.hasTime() && (!end || !end.hasTime());
  1333. }
  1334. }
  1335. // normalize the date based on allDay
  1336. if (allDay) {
  1337. // neither date should have a time
  1338. if (start.hasTime()) {
  1339. start.stripTime();
  1340. }
  1341. if (end && end.hasTime()) {
  1342. end.stripTime();
  1343. }
  1344. }
  1345. else {
  1346. // force a time/zone up the dates
  1347. if (!start.hasTime()) {
  1348. start = t.rezoneDate(start);
  1349. }
  1350. if (end && !end.hasTime()) {
  1351. end = t.rezoneDate(end);
  1352. }
  1353. }
  1354. // Copy all properties over to the resulting object.
  1355. // The special-case properties will be copied over afterwards.
  1356. $.extend(out, data);
  1357. if (source) {
  1358. out.source = source;
  1359. }
  1360. out._id = data._id || (data.id === undefined ? '_fc' + eventGUID++ : data.id + '');
  1361. if (data.className) {
  1362. if (typeof data.className == 'string') {
  1363. out.className = data.className.split(/\s+/);
  1364. }
  1365. else { // assumed to be an array
  1366. out.className = data.className;
  1367. }
  1368. }
  1369. else {
  1370. out.className = [];
  1371. }
  1372. out.allDay = allDay;
  1373. out.start = start;
  1374. out.end = end;
  1375. if (options.forceEventDuration && !out.end) {
  1376. out.end = getEventEnd(out);
  1377. }
  1378. backupEventDates(out);
  1379. return out;
  1380. }
  1381. /* Event Modification Math
  1382. -----------------------------------------------------------------------------------------*/
  1383. // Modify the date(s) of an event and make this change propagate to all other events with
  1384. // the same ID (related repeating events).
  1385. //
  1386. // If `newStart`/`newEnd` are not specified, the "new" dates are assumed to be `event.start` and `event.end`.
  1387. // The "old" dates to be compare against are always `event._start` and `event._end` (set by EventManager).
  1388. //
  1389. // Returns an object with delta information and a function to undo all operations.
  1390. //
  1391. function mutateEvent(event, newStart, newEnd) {
  1392. var oldAllDay = event._allDay;
  1393. var oldStart = event._start;
  1394. var oldEnd = event._end;
  1395. var clearEnd = false;
  1396. var newAllDay;
  1397. var dateDelta;
  1398. var durationDelta;
  1399. var undoFunc;
  1400. // if no new dates were passed in, compare against the event's existing dates
  1401. if (!newStart && !newEnd) {
  1402. newStart = event.start;
  1403. newEnd = event.end;
  1404. }
  1405. // NOTE: throughout this function, the initial values of `newStart` and `newEnd` are
  1406. // preserved. These values may be undefined.
  1407. // detect new allDay
  1408. if (event.allDay != oldAllDay) { // if value has changed, use it
  1409. newAllDay = event.allDay;
  1410. }
  1411. else { // otherwise, see if any of the new dates are allDay
  1412. newAllDay = !(newStart || newEnd).hasTime();
  1413. }
  1414. // normalize the new dates based on allDay
  1415. if (newAllDay) {
  1416. if (newStart) {
  1417. newStart = newStart.clone().stripTime();
  1418. }
  1419. if (newEnd) {
  1420. newEnd = newEnd.clone().stripTime();
  1421. }
  1422. }
  1423. // compute dateDelta
  1424. if (newStart) {
  1425. if (newAllDay) {
  1426. dateDelta = dayishDiff(newStart, oldStart.clone().stripTime()); // treat oldStart as allDay
  1427. }
  1428. else {
  1429. dateDelta = dayishDiff(newStart, oldStart);
  1430. }
  1431. }
  1432. if (newAllDay != oldAllDay) {
  1433. // if allDay has changed, always throw away the end
  1434. clearEnd = true;
  1435. }
  1436. else if (newEnd) {
  1437. durationDelta = dayishDiff(
  1438. // new duration
  1439. newEnd || t.getDefaultEventEnd(newAllDay, newStart || oldStart),
  1440. newStart || oldStart
  1441. ).subtract(dayishDiff(
  1442. // subtract old duration
  1443. oldEnd || t.getDefaultEventEnd(oldAllDay, oldStart),
  1444. oldStart
  1445. ));
  1446. }
  1447. undoFunc = mutateEvents(
  1448. clientEvents(event._id), // get events with this ID
  1449. clearEnd,
  1450. newAllDay,
  1451. dateDelta,
  1452. durationDelta
  1453. );
  1454. return {
  1455. dateDelta: dateDelta,
  1456. durationDelta: durationDelta,
  1457. undo: undoFunc
  1458. };
  1459. }
  1460. // Modifies an array of events in the following ways (operations are in order):
  1461. // - clear the event's `end`
  1462. // - convert the event to allDay
  1463. // - add `dateDelta` to the start and end
  1464. // - add `durationDelta` to the event's duration
  1465. //
  1466. // Returns a function that can be called to undo all the operations.
  1467. //
  1468. function mutateEvents(events, clearEnd, forceAllDay, dateDelta, durationDelta) {
  1469. var isAmbigTimezone = t.getIsAmbigTimezone();
  1470. var undoFunctions = [];
  1471. $.each(events, function(i, event) {
  1472. var oldAllDay = event._allDay;
  1473. var oldStart = event._start;
  1474. var oldEnd = event._end;
  1475. var newAllDay = forceAllDay != null ? forceAllDay : oldAllDay;
  1476. var newStart = oldStart.clone();
  1477. var newEnd = (!clearEnd && oldEnd) ? oldEnd.clone() : null;
  1478. // NOTE: this function is responsible for transforming `newStart` and `newEnd`,
  1479. // which were initialized to the OLD values first. `newEnd` may be null.
  1480. // normlize newStart/newEnd to be consistent with newAllDay
  1481. if (newAllDay) {
  1482. newStart.stripTime();
  1483. if (newEnd) {
  1484. newEnd.stripTime();
  1485. }
  1486. }
  1487. else {
  1488. if (!newStart.hasTime()) {
  1489. newStart = t.rezoneDate(newStart);
  1490. }
  1491. if (newEnd && !newEnd.hasTime()) {
  1492. newEnd = t.rezoneDate(newEnd);
  1493. }
  1494. }
  1495. // ensure we have an end date if necessary
  1496. if (!newEnd && (options.forceEventDuration || +durationDelta)) {
  1497. newEnd = t.getDefaultEventEnd(newAllDay, newStart);
  1498. }
  1499. // translate the dates
  1500. newStart.add(dateDelta);
  1501. if (newEnd) {
  1502. newEnd.add(dateDelta).add(durationDelta);
  1503. }
  1504. // if the dates have changed, and we know it is impossible to recompute the
  1505. // timezone offsets, strip the zone.
  1506. if (isAmbigTimezone) {
  1507. if (+dateDelta || +durationDelta) {
  1508. newStart.stripZone();
  1509. if (newEnd) {
  1510. newEnd.stripZone();
  1511. }
  1512. }
  1513. }
  1514. event.allDay = newAllDay;
  1515. event.start = newStart;
  1516. event.end = newEnd;
  1517. backupEventDates(event);
  1518. undoFunctions.push(function() {
  1519. event.allDay = oldAllDay;
  1520. event.start = oldStart;
  1521. event.end = oldEnd;
  1522. backupEventDates(event);
  1523. });
  1524. });
  1525. return function() {
  1526. for (var i=0; i<undoFunctions.length; i++) {
  1527. undoFunctions[i]();
  1528. }
  1529. };
  1530. }
  1531. }
  1532. // updates the "backup" properties, which are preserved in order to compute diffs later on.
  1533. function backupEventDates(event) {
  1534. event._allDay = event.allDay;
  1535. event._start = event.start.clone();
  1536. event._end = event.end ? event.end.clone() : null;
  1537. }
  1538. ;;
  1539. fc.applyAll = applyAll;
  1540. // Create an object that has the given prototype.
  1541. // Just like Object.create
  1542. function createObject(proto) {
  1543. var f = function() {};
  1544. f.prototype = proto;
  1545. return new f();
  1546. }
  1547. // Copies specifically-owned (non-protoype) properties of `b` onto `a`.
  1548. // FYI, $.extend would copy *all* properties of `b` onto `a`.
  1549. function extend(a, b) {
  1550. for (var i in b) {
  1551. if (b.hasOwnProperty(i)) {
  1552. a[i] = b[i];
  1553. }
  1554. }
  1555. }
  1556. /* Date
  1557. -----------------------------------------------------------------------------*/
  1558. var dayIDs = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
  1559. // diffs the two moments into a Duration where full-days are recorded first,
  1560. // then the remaining time.
  1561. function dayishDiff(d1, d0) {
  1562. return moment.duration({
  1563. days: d1.clone().stripTime().diff(d0.clone().stripTime(), 'days'),
  1564. ms: d1.time() - d0.time()
  1565. });
  1566. }
  1567. function isNativeDate(input) {
  1568. return Object.prototype.toString.call(input) === '[object Date]' ||
  1569. input instanceof Date;
  1570. }
  1571. /* Event Element Binding
  1572. -----------------------------------------------------------------------------*/
  1573. function lazySegBind(container, segs, bindHandlers) {
  1574. container.unbind('mouseover').mouseover(function(ev) {
  1575. var parent=ev.target, e,
  1576. i, seg;
  1577. while (parent != this) {
  1578. e = parent;
  1579. parent = parent.parentNode;
  1580. }
  1581. if ((i = e._fci) !== undefined) {
  1582. e._fci = undefined;
  1583. seg = segs[i];
  1584. bindHandlers(seg.event, seg.element, seg);
  1585. $(ev.target).trigger(ev);
  1586. }
  1587. ev.stopPropagation();
  1588. });
  1589. }
  1590. /* Element Dimensions
  1591. -----------------------------------------------------------------------------*/
  1592. function setOuterWidth(element, width, includeMargins) {
  1593. for (var i=0, e; i<element.length; i++) {
  1594. e = $(element[i]);
  1595. e.width(Math.max(0, width - hsides(e, includeMargins)));
  1596. }
  1597. }
  1598. function setOuterHeight(element, height, includeMargins) {
  1599. for (var i=0, e; i<element.length; i++) {
  1600. e = $(element[i]);
  1601. e.height(Math.max(0, height - vsides(e, includeMargins)));
  1602. }
  1603. }
  1604. function hsides(element, includeMargins) {
  1605. return hpadding(element) + hborders(element) + (includeMargins ? hmargins(element) : 0);
  1606. }
  1607. function hpadding(element) {
  1608. return (parseFloat($.css(element[0], 'paddingLeft', true)) || 0) +
  1609. (parseFloat($.css(element[0], 'paddingRight', true)) || 0);
  1610. }
  1611. function hmargins(element) {
  1612. return (parseFloat($.css(element[0], 'marginLeft', true)) || 0) +
  1613. (parseFloat($.css(element[0], 'marginRight', true)) || 0);
  1614. }
  1615. function hborders(element) {
  1616. return (parseFloat($.css(element[0], 'borderLeftWidth', true)) || 0) +
  1617. (parseFloat($.css(element[0], 'borderRightWidth', true)) || 0);
  1618. }
  1619. function vsides(element, includeMargins) {
  1620. return vpadding(element) + vborders(element) + (includeMargins ? vmargins(element) : 0);
  1621. }
  1622. function vpadding(element) {
  1623. return (parseFloat($.css(element[0], 'paddingTop', true)) || 0) +
  1624. (parseFloat($.css(element[0], 'paddingBottom', true)) || 0);
  1625. }
  1626. function vmargins(element) {
  1627. return (parseFloat($.css(element[0], 'marginTop', true)) || 0) +
  1628. (parseFloat($.css(element[0], 'marginBottom', true)) || 0);
  1629. }
  1630. function vborders(element) {
  1631. return (parseFloat($.css(element[0], 'borderTopWidth', true)) || 0) +
  1632. (parseFloat($.css(element[0], 'borderBottomWidth', true)) || 0);
  1633. }
  1634. /* Misc Utils
  1635. -----------------------------------------------------------------------------*/
  1636. //TODO: arraySlice
  1637. //TODO: isFunction, grep ?
  1638. function noop() { }
  1639. function dateCompare(a, b) { // works with moments too
  1640. return a - b;
  1641. }
  1642. function arrayMax(a) {
  1643. return Math.max.apply(Math, a);
  1644. }
  1645. function smartProperty(obj, name) { // get a camel-cased/namespaced property of an object
  1646. obj = obj || {};
  1647. if (obj[name] !== undefined) {
  1648. return obj[name];
  1649. }
  1650. var parts = name.split(/(?=[A-Z])/),
  1651. i=parts.length-1, res;
  1652. for (; i>=0; i--) {
  1653. res = obj[parts[i].toLowerCase()];
  1654. if (res !== undefined) {
  1655. return res;
  1656. }
  1657. }
  1658. return obj['default'];
  1659. }
  1660. function htmlEscape(s) {
  1661. return (s + '').replace(/&/g, '&amp;')
  1662. .replace(/</g, '&lt;')
  1663. .replace(/>/g, '&gt;')
  1664. .replace(/'/g, '&#039;')
  1665. .replace(/"/g, '&quot;')
  1666. .replace(/\n/g, '<br />');
  1667. }
  1668. function stripHTMLEntities(text) {
  1669. return text.replace(/&.*?;/g, '');
  1670. }
  1671. function disableTextSelection(element) {
  1672. element
  1673. .attr('unselectable', 'on')
  1674. .css('MozUserSelect', 'none')
  1675. .bind('selectstart.ui', function() { return false; });
  1676. }
  1677. /*
  1678. function enableTextSelection(element) {
  1679. element
  1680. .attr('unselectable', 'off')
  1681. .css('MozUserSelect', '')
  1682. .unbind('selectstart.ui');
  1683. }
  1684. */
  1685. function markFirstLast(e) { // TODO: use CSS selectors instead
  1686. e.children()
  1687. .removeClass('fc-first fc-last')
  1688. .filter(':first-child')
  1689. .addClass('fc-first')
  1690. .end()
  1691. .filter(':last-child')
  1692. .addClass('fc-last');
  1693. }
  1694. function getSkinCss(event, opt) {
  1695. var source = event.source || {};
  1696. var eventColor = event.color;
  1697. var sourceColor = source.color;
  1698. var optionColor = opt('eventColor');
  1699. var backgroundColor =
  1700. event.backgroundColor ||
  1701. eventColor ||
  1702. source.backgroundColor ||
  1703. sourceColor ||
  1704. opt('eventBackgroundColor') ||
  1705. optionColor;
  1706. var borderColor =
  1707. event.borderColor ||
  1708. eventColor ||
  1709. source.borderColor ||
  1710. sourceColor ||
  1711. opt('eventBorderColor') ||
  1712. optionColor;
  1713. var textColor =
  1714. event.textColor ||
  1715. source.textColor ||
  1716. opt('eventTextColor');
  1717. var statements = [];
  1718. if (backgroundColor) {
  1719. statements.push('background-color:' + backgroundColor);
  1720. }
  1721. if (borderColor) {
  1722. statements.push('border-color:' + borderColor);
  1723. }
  1724. if (textColor) {
  1725. statements.push('color:' + textColor);
  1726. }
  1727. return statements.join(';');
  1728. }
  1729. function applyAll(functions, thisObj, args) {
  1730. if ($.isFunction(functions)) {
  1731. functions = [ functions ];
  1732. }
  1733. if (functions) {
  1734. var i;
  1735. var ret;
  1736. for (i=0; i<functions.length; i++) {
  1737. ret = functions[i].apply(thisObj, args) || ret;
  1738. }
  1739. return ret;
  1740. }
  1741. }
  1742. function firstDefined() {
  1743. for (var i=0; i<arguments.length; i++) {
  1744. if (arguments[i] !== undefined) {
  1745. return arguments[i];
  1746. }
  1747. }
  1748. }
  1749. ;;
  1750. var ambigDateOfMonthRegex = /^\s*\d{4}-\d\d$/;
  1751. var ambigTimeOrZoneRegex = /^\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+)?)?)?)?)?$/;
  1752. // Creating
  1753. // -------------------------------------------------------------------------------------------------
  1754. // Creates a new moment, similar to the vanilla moment(...) constructor, but with
  1755. // extra features (ambiguous time, enhanced formatting). When gived an existing moment,
  1756. // it will function as a clone (and retain the zone of the moment). Anything else will
  1757. // result in a moment in the local zone.
  1758. fc.moment = function() {
  1759. return makeMoment(arguments);
  1760. };
  1761. // Sames as fc.moment, but forces the resulting moment to be in the UTC timezone.
  1762. fc.moment.utc = function() {
  1763. var mom = makeMoment(arguments, true);
  1764. // Force it into UTC because makeMoment doesn't guarantee it.
  1765. if (mom.hasTime()) { // don't give ambiguously-timed moments a UTC zone
  1766. mom.utc();
  1767. }
  1768. return mom;
  1769. };
  1770. // Same as fc.moment, but when given an ISO8601 string, the timezone offset is preserved.
  1771. // ISO8601 strings with no timezone offset will become ambiguously zoned.
  1772. fc.moment.parseZone = function() {
  1773. return makeMoment(arguments, true, true);
  1774. };
  1775. // Builds an FCMoment from args. When given an existing moment, it clones. When given a native
  1776. // Date, or called with no arguments (the current time), the resulting moment will be local.
  1777. // Anything else needs to be "parsed" (a string or an array), and will be affected by:
  1778. // parseAsUTC - if there is no zone information, should we parse the input in UTC?
  1779. // parseZone - if there is zone information, should we force the zone of the moment?
  1780. function makeMoment(args, parseAsUTC, parseZone) {
  1781. var input = args[0];
  1782. var isSingleString = args.length == 1 && typeof input === 'string';
  1783. var isAmbigTime;
  1784. var isAmbigZone;
  1785. var ambigMatch;
  1786. var output; // an object with fields for the new FCMoment object
  1787. if (moment.isMoment(input)) {
  1788. output = moment.apply(null, args); // clone it
  1789. // the ambig properties have not been preserved in the clone, so reassign them
  1790. if (input._ambigTime) {
  1791. output._ambigTime = true;
  1792. }
  1793. if (input._ambigZone) {
  1794. output._ambigZone = true;
  1795. }
  1796. }
  1797. else if (isNativeDate(input) || input === undefined) {
  1798. output = moment.apply(null, args); // will be local
  1799. }
  1800. else { // "parsing" is required
  1801. isAmbigTime = false;
  1802. isAmbigZone = false;
  1803. if (isSingleString) {
  1804. if (ambigDateOfMonthRegex.test(input)) {
  1805. // accept strings like '2014-05', but convert to the first of the month
  1806. input += '-01';
  1807. args = [ input ]; // for when we pass it on to moment's constructor
  1808. isAmbigTime = true;
  1809. isAmbigZone = true;
  1810. }
  1811. else if ((ambigMatch = ambigTimeOrZoneRegex.exec(input))) {
  1812. isAmbigTime = !ambigMatch[5]; // no time part?
  1813. isAmbigZone = true;
  1814. }
  1815. }
  1816. else if ($.isArray(input)) {
  1817. // arrays have no timezone information, so assume ambiguous zone
  1818. isAmbigZone = true;
  1819. }
  1820. // otherwise, probably a string with a format
  1821. if (parseAsUTC) {
  1822. output = moment.utc.apply(moment, args);
  1823. }
  1824. else {
  1825. output = moment.apply(null, args);
  1826. }
  1827. if (isAmbigTime) {
  1828. output._ambigTime = true;
  1829. output._ambigZone = true; // ambiguous time always means ambiguous zone
  1830. }
  1831. else if (parseZone) { // let's record the inputted zone somehow
  1832. if (isAmbigZone) {
  1833. output._ambigZone = true;
  1834. }
  1835. else if (isSingleString) {
  1836. output.zone(input); // if not a valid zone, will assign UTC
  1837. }
  1838. }
  1839. }
  1840. return new FCMoment(output);
  1841. }
  1842. // Our subclass of Moment.
  1843. // Accepts an object with the internal Moment properties that should be copied over to
  1844. // `this` object (most likely another Moment object). The values in this data must not
  1845. // be referenced by anything else (two moments sharing a Date object for example).
  1846. function FCMoment(internalData) {
  1847. extend(this, internalData);
  1848. }
  1849. // Chain the prototype to Moment's
  1850. FCMoment.prototype = createObject(moment.fn);
  1851. // We need this because Moment's implementation won't create an FCMoment,
  1852. // nor will it copy over the ambig flags.
  1853. FCMoment.prototype.clone = function() {
  1854. return makeMoment([ this ]);
  1855. };
  1856. // Time-of-day
  1857. // -------------------------------------------------------------------------------------------------
  1858. // GETTER
  1859. // Returns a Duration with the hours/minutes/seconds/ms values of the moment.
  1860. // If the moment has an ambiguous time, a duration of 00:00 will be returned.
  1861. //
  1862. // SETTER
  1863. // You can supply a Duration, a Moment, or a Duration-like argument.
  1864. // When setting the time, and the moment has an ambiguous time, it then becomes unambiguous.
  1865. FCMoment.prototype.time = function(time) {
  1866. if (time == null) { // getter
  1867. return moment.duration({
  1868. hours: this.hours(),
  1869. minutes: this.minutes(),
  1870. seconds: this.seconds(),
  1871. milliseconds: this.milliseconds()
  1872. });
  1873. }
  1874. else { // setter
  1875. delete this._ambigTime; // mark that the moment now has a time
  1876. if (!moment.isDuration(time) && !moment.isMoment(time)) {
  1877. time = moment.duration(time);
  1878. }
  1879. // The day value should cause overflow (so 24 hours becomes 00:00:00 of next day).
  1880. // Only for Duration times, not Moment times.
  1881. var dayHours = 0;
  1882. if (moment.isDuration(time)) {
  1883. dayHours = Math.floor(time.asDays()) * 24;
  1884. }
  1885. // We need to set the individual fields.
  1886. // Can't use startOf('day') then add duration. In case of DST at start of day.
  1887. return this.hours(dayHours + time.hours())
  1888. .minutes(time.minutes())
  1889. .seconds(time.seconds())
  1890. .milliseconds(time.milliseconds());
  1891. }
  1892. };
  1893. // Converts the moment to UTC, stripping out its time-of-day and timezone offset,
  1894. // but preserving its YMD. A moment with a stripped time will display no time
  1895. // nor timezone offset when .format() is called.
  1896. FCMoment.prototype.stripTime = function() {
  1897. var a = this.toArray(); // year,month,date,hours,minutes,seconds as an array
  1898. // set the internal UTC flag
  1899. moment.fn.utc.call(this); // call the original method, because we don't want to affect _ambigZone
  1900. this.year(a[0]) // TODO: find a way to do this in one shot
  1901. .month(a[1])
  1902. .date(a[2])
  1903. .hours(0)
  1904. .minutes(0)
  1905. .seconds(0)
  1906. .milliseconds(0);
  1907. // Mark the time as ambiguous. This needs to happen after the .utc() call, which calls .zone(), which
  1908. // clears all ambig flags. Same concept with the .year/month/date calls in the case of moment-timezone.
  1909. this._ambigTime = true;
  1910. this._ambigZone = true; // if ambiguous time, also ambiguous timezone offset
  1911. return this; // for chaining
  1912. };
  1913. // Returns if the moment has a non-ambiguous time (boolean)
  1914. FCMoment.prototype.hasTime = function() {
  1915. return !this._ambigTime;
  1916. };
  1917. // Timezone
  1918. // -------------------------------------------------------------------------------------------------
  1919. // Converts the moment to UTC, stripping out its timezone offset, but preserving its
  1920. // YMD and time-of-day. A moment with a stripped timezone offset will display no
  1921. // timezone offset when .format() is called.
  1922. FCMoment.prototype.stripZone = function() {
  1923. var a = this.toArray(); // year,month,date,hours,minutes,seconds as an array
  1924. var wasAmbigTime = this._ambigTime;
  1925. moment.fn.utc.call(this); // set the internal UTC flag
  1926. this.year(a[0]) // TODO: find a way to do this in one shot
  1927. .month(a[1])
  1928. .date(a[2])
  1929. .hours(a[3])
  1930. .minutes(a[4])
  1931. .seconds(a[5])
  1932. .milliseconds(a[6]);
  1933. if (wasAmbigTime) {
  1934. // the above call to .utc()/.zone() unfortunately clears the ambig flags, so reassign
  1935. this._ambigTime = true;
  1936. }
  1937. // Mark the zone as ambiguous. This needs to happen after the .utc() call, which calls .zone(), which
  1938. // clears all ambig flags. Same concept with the .year/month/date calls in the case of moment-timezone.
  1939. this._ambigZone = true;
  1940. return this; // for chaining
  1941. };
  1942. // Returns of the moment has a non-ambiguous timezone offset (boolean)
  1943. FCMoment.prototype.hasZone = function() {
  1944. return !this._ambigZone;
  1945. };
  1946. // this method implicitly marks a zone
  1947. FCMoment.prototype.zone = function(tzo) {
  1948. if (tzo != null) {
  1949. // FYI, the delete statements need to be before the .zone() call or else chaos ensues
  1950. // for reasons I don't understand.
  1951. delete this._ambigTime;
  1952. delete this._ambigZone;
  1953. }
  1954. return moment.fn.zone.apply(this, arguments);
  1955. };
  1956. // this method implicitly marks a zone
  1957. FCMoment.prototype.local = function() {
  1958. var a = this.toArray(); // year,month,date,hours,minutes,seconds as an array
  1959. var wasAmbigZone = this._ambigZone;
  1960. // will happen anyway via .local()/.zone(), but don't want to rely on internal implementation
  1961. delete this._ambigTime;
  1962. delete this._ambigZone;
  1963. moment.fn.local.apply(this, arguments);
  1964. if (wasAmbigZone) {
  1965. // If the moment was ambiguously zoned, the date fields were stored as UTC.
  1966. // We want to preserve these, but in local time.
  1967. this.year(a[0]) // TODO: find a way to do this in one shot
  1968. .month(a[1])
  1969. .date(a[2])
  1970. .hours(a[3])
  1971. .minutes(a[4])
  1972. .seconds(a[5])
  1973. .milliseconds(a[6]);
  1974. }
  1975. return this; // for chaining
  1976. };
  1977. // this method implicitly marks a zone
  1978. FCMoment.prototype.utc = function() {
  1979. // will happen anyway via .local()/.zone(), but don't want to rely on internal implementation
  1980. delete this._ambigTime;
  1981. delete this._ambigZone;
  1982. return moment.fn.utc.apply(this, arguments);
  1983. };
  1984. // Formatting
  1985. // -------------------------------------------------------------------------------------------------
  1986. FCMoment.prototype.format = function() {
  1987. if (arguments[0]) {
  1988. return formatDate(this, arguments[0]); // our extended formatting
  1989. }
  1990. if (this._ambigTime) {
  1991. return momentFormat(this, 'YYYY-MM-DD');
  1992. }
  1993. if (this._ambigZone) {
  1994. return momentFormat(this, 'YYYY-MM-DD[T]HH:mm:ss');
  1995. }
  1996. return momentFormat(this); // default moment original formatting
  1997. };
  1998. FCMoment.prototype.toISOString = function() {
  1999. if (this._ambigTime) {
  2000. return momentFormat(this, 'YYYY-MM-DD');
  2001. }
  2002. if (this._ambigZone) {
  2003. return momentFormat(this, 'YYYY-MM-DD[T]HH:mm:ss');
  2004. }
  2005. return moment.fn.toISOString.apply(this, arguments);
  2006. };
  2007. // Querying
  2008. // -------------------------------------------------------------------------------------------------
  2009. // Is the moment within the specified range? `end` is exclusive.
  2010. FCMoment.prototype.isWithin = function(start, end) {
  2011. var a = commonlyAmbiguate([ this, start, end ]);
  2012. return a[0] >= a[1] && a[0] < a[2];
  2013. };
  2014. // Make these query methods work with ambiguous moments
  2015. $.each([
  2016. 'isBefore',
  2017. 'isAfter',
  2018. 'isSame'
  2019. ], function(i, methodName) {
  2020. FCMoment.prototype[methodName] = function(input, units) {
  2021. var a = commonlyAmbiguate([ this, input ]);
  2022. return moment.fn[methodName].call(a[0], a[1], units);
  2023. };
  2024. });
  2025. // Misc Internals
  2026. // -------------------------------------------------------------------------------------------------
  2027. // given an array of moment-like inputs, return a parallel array w/ moments similarly ambiguated.
  2028. // for example, of one moment has ambig time, but not others, all moments will have their time stripped.
  2029. function commonlyAmbiguate(inputs) {
  2030. var outputs = [];
  2031. var anyAmbigTime = false;
  2032. var anyAmbigZone = false;
  2033. var i;
  2034. for (i=0; i<inputs.length; i++) {
  2035. outputs.push(fc.moment(inputs[i]));
  2036. anyAmbigTime = anyAmbigTime || outputs[i]._ambigTime;
  2037. anyAmbigZone = anyAmbigZone || outputs[i]._ambigZone;
  2038. }
  2039. for (i=0; i<outputs.length; i++) {
  2040. if (anyAmbigTime) {
  2041. outputs[i].stripTime();
  2042. }
  2043. else if (anyAmbigZone) {
  2044. outputs[i].stripZone();
  2045. }
  2046. }
  2047. return outputs;
  2048. }
  2049. ;;
  2050. // Single Date Formatting
  2051. // -------------------------------------------------------------------------------------------------
  2052. // call this if you want Moment's original format method to be used
  2053. function momentFormat(mom, formatStr) {
  2054. return moment.fn.format.call(mom, formatStr);
  2055. }
  2056. // Formats `date` with a Moment formatting string, but allow our non-zero areas and
  2057. // additional token.
  2058. function formatDate(date, formatStr) {
  2059. return formatDateWithChunks(date, getFormatStringChunks(formatStr));
  2060. }
  2061. function formatDateWithChunks(date, chunks) {
  2062. var s = '';
  2063. var i;
  2064. for (i=0; i<chunks.length; i++) {
  2065. s += formatDateWithChunk(date, chunks[i]);
  2066. }
  2067. return s;
  2068. }
  2069. // addition formatting tokens we want recognized
  2070. var tokenOverrides = {
  2071. t: function(date) { // "a" or "p"
  2072. return momentFormat(date, 'a').charAt(0);
  2073. },
  2074. T: function(date) { // "A" or "P"
  2075. return momentFormat(date, 'A').charAt(0);
  2076. }
  2077. };
  2078. function formatDateWithChunk(date, chunk) {
  2079. var token;
  2080. var maybeStr;
  2081. if (typeof chunk === 'string') { // a literal string
  2082. return chunk;
  2083. }
  2084. else if ((token = chunk.token)) { // a token, like "YYYY"
  2085. if (tokenOverrides[token]) {
  2086. return tokenOverrides[token](date); // use our custom token
  2087. }
  2088. return momentFormat(date, token);
  2089. }
  2090. else if (chunk.maybe) { // a grouping of other chunks that must be non-zero
  2091. maybeStr = formatDateWithChunks(date, chunk.maybe);
  2092. if (maybeStr.match(/[1-9]/)) {
  2093. return maybeStr;
  2094. }
  2095. }
  2096. return '';
  2097. }
  2098. // Date Range Formatting
  2099. // -------------------------------------------------------------------------------------------------
  2100. // TODO: make it work with timezone offset
  2101. // Using a formatting string meant for a single date, generate a range string, like
  2102. // "Sep 2 - 9 2013", that intelligently inserts a separator where the dates differ.
  2103. // If the dates are the same as far as the format string is concerned, just return a single
  2104. // rendering of one date, without any separator.
  2105. function formatRange(date1, date2, formatStr, separator, isRTL) {
  2106. date1 = fc.moment.parseZone(date1);
  2107. date2 = fc.moment.parseZone(date2);
  2108. // Expand localized format strings, like "LL" -> "MMMM D YYYY"
  2109. formatStr = date1.lang().longDateFormat(formatStr) || formatStr;
  2110. // BTW, this is not important for `formatDate` because it is impossible to put custom tokens
  2111. // or non-zero areas in Moment's localized format strings.
  2112. separator = separator || ' - ';
  2113. return formatRangeWithChunks(
  2114. date1,
  2115. date2,
  2116. getFormatStringChunks(formatStr),
  2117. separator,
  2118. isRTL
  2119. );
  2120. }
  2121. fc.formatRange = formatRange; // expose
  2122. function formatRangeWithChunks(date1, date2, chunks, separator, isRTL) {
  2123. var chunkStr; // the rendering of the chunk
  2124. var leftI;
  2125. var leftStr = '';
  2126. var rightI;
  2127. var rightStr = '';
  2128. var middleI;
  2129. var middleStr1 = '';
  2130. var middleStr2 = '';
  2131. var middleStr = '';
  2132. // Start at the leftmost side of the formatting string and continue until you hit a token
  2133. // that is not the same between dates.
  2134. for (leftI=0; leftI<chunks.length; leftI++) {
  2135. chunkStr = formatSimilarChunk(date1, date2, chunks[leftI]);
  2136. if (chunkStr === false) {
  2137. break;
  2138. }
  2139. leftStr += chunkStr;
  2140. }
  2141. // Similarly, start at the rightmost side of the formatting string and move left
  2142. for (rightI=chunks.length-1; rightI>leftI; rightI--) {
  2143. chunkStr = formatSimilarChunk(date1, date2, chunks[rightI]);
  2144. if (chunkStr === false) {
  2145. break;
  2146. }
  2147. rightStr = chunkStr + rightStr;
  2148. }
  2149. // The area in the middle is different for both of the dates.
  2150. // Collect them distinctly so we can jam them together later.
  2151. for (middleI=leftI; middleI<=rightI; middleI++) {
  2152. middleStr1 += formatDateWithChunk(date1, chunks[middleI]);
  2153. middleStr2 += formatDateWithChunk(date2, chunks[middleI]);
  2154. }
  2155. if (middleStr1 || middleStr2) {
  2156. if (isRTL) {
  2157. middleStr = middleStr2 + separator + middleStr1;
  2158. }
  2159. else {
  2160. middleStr = middleStr1 + separator + middleStr2;
  2161. }
  2162. }
  2163. return leftStr + middleStr + rightStr;
  2164. }
  2165. var similarUnitMap = {
  2166. Y: 'year',
  2167. M: 'month',
  2168. D: 'day', // day of month
  2169. d: 'day', // day of week
  2170. // prevents a separator between anything time-related...
  2171. A: 'second', // AM/PM
  2172. a: 'second', // am/pm
  2173. T: 'second', // A/P
  2174. t: 'second', // a/p
  2175. H: 'second', // hour (24)
  2176. h: 'second', // hour (12)
  2177. m: 'second', // minute
  2178. s: 'second' // second
  2179. };
  2180. // TODO: week maybe?
  2181. // Given a formatting chunk, and given that both dates are similar in the regard the
  2182. // formatting chunk is concerned, format date1 against `chunk`. Otherwise, return `false`.
  2183. function formatSimilarChunk(date1, date2, chunk) {
  2184. var token;
  2185. var unit;
  2186. if (typeof chunk === 'string') { // a literal string
  2187. return chunk;
  2188. }
  2189. else if ((token = chunk.token)) {
  2190. unit = similarUnitMap[token.charAt(0)];
  2191. // are the dates the same for this unit of measurement?
  2192. if (unit && date1.isSame(date2, unit)) {
  2193. return momentFormat(date1, token); // would be the same if we used `date2`
  2194. // BTW, don't support custom tokens
  2195. }
  2196. }
  2197. return false; // the chunk is NOT the same for the two dates
  2198. // BTW, don't support splitting on non-zero areas
  2199. }
  2200. // Chunking Utils
  2201. // -------------------------------------------------------------------------------------------------
  2202. var formatStringChunkCache = {};
  2203. function getFormatStringChunks(formatStr) {
  2204. if (formatStr in formatStringChunkCache) {
  2205. return formatStringChunkCache[formatStr];
  2206. }
  2207. return (formatStringChunkCache[formatStr] = chunkFormatString(formatStr));
  2208. }
  2209. // Break the formatting string into an array of chunks
  2210. function chunkFormatString(formatStr) {
  2211. var chunks = [];
  2212. var chunker = /\[([^\]]*)\]|\(([^\)]*)\)|(LT|(\w)\4*o?)|([^\w\[\(]+)/g; // TODO: more descrimination
  2213. var match;
  2214. while ((match = chunker.exec(formatStr))) {
  2215. if (match[1]) { // a literal string inside [ ... ]
  2216. chunks.push(match[1]);
  2217. }
  2218. else if (match[2]) { // non-zero formatting inside ( ... )
  2219. chunks.push({ maybe: chunkFormatString(match[2]) });
  2220. }
  2221. else if (match[3]) { // a formatting token
  2222. chunks.push({ token: match[3] });
  2223. }
  2224. else if (match[5]) { // an unenclosed literal string
  2225. chunks.push(match[5]);
  2226. }
  2227. }
  2228. return chunks;
  2229. }
  2230. ;;
  2231. fcViews.month = MonthView;
  2232. function MonthView(element, calendar) {
  2233. var t = this;
  2234. // exports
  2235. t.incrementDate = incrementDate;
  2236. t.render = render;
  2237. // imports
  2238. BasicView.call(t, element, calendar, 'month');
  2239. function incrementDate(date, delta) {
  2240. return date.clone().stripTime().add('months', delta).startOf('month');
  2241. }
  2242. function render(date) {
  2243. t.intervalStart = date.clone().stripTime().startOf('month');
  2244. t.intervalEnd = t.intervalStart.clone().add('months', 1);
  2245. t.start = t.intervalStart.clone();
  2246. t.start = t.skipHiddenDays(t.start); // move past the first week if no visible days
  2247. t.start.startOf('week');
  2248. t.start = t.skipHiddenDays(t.start); // move past the first invisible days of the week
  2249. t.end = t.intervalEnd.clone();
  2250. t.end = t.skipHiddenDays(t.end, -1, true); // move in from the last week if no visible days
  2251. t.end.add('days', (7 - t.end.weekday()) % 7); // move to end of week if not already
  2252. t.end = t.skipHiddenDays(t.end, -1, true); // move in from the last invisible days of the week
  2253. var rowCnt = Math.ceil( // need to ceil in case there are hidden days
  2254. t.end.diff(t.start, 'weeks', true) // returnfloat=true
  2255. );
  2256. if (t.opt('weekMode') == 'fixed') {
  2257. t.end.add('weeks', 6 - rowCnt);
  2258. rowCnt = 6;
  2259. }
  2260. t.title = calendar.formatDate(t.intervalStart, t.opt('titleFormat'));
  2261. t.renderBasic(rowCnt, t.getCellsPerWeek(), true);
  2262. }
  2263. }
  2264. ;;
  2265. fcViews.basicWeek = BasicWeekView;
  2266. function BasicWeekView(element, calendar) { // TODO: do a WeekView mixin
  2267. var t = this;
  2268. // exports
  2269. t.incrementDate = incrementDate;
  2270. t.render = render;
  2271. // imports
  2272. BasicView.call(t, element, calendar, 'basicWeek');
  2273. function incrementDate(date, delta) {
  2274. return date.clone().stripTime().add('weeks', delta).startOf('week');
  2275. }
  2276. function render(date) {
  2277. t.intervalStart = date.clone().stripTime().startOf('week');
  2278. t.intervalEnd = t.intervalStart.clone().add('weeks', 1);
  2279. t.start = t.skipHiddenDays(t.intervalStart);
  2280. t.end = t.skipHiddenDays(t.intervalEnd, -1, true);
  2281. t.title = calendar.formatRange(
  2282. t.start,
  2283. t.end.clone().subtract(1), // make inclusive by subtracting 1 ms
  2284. t.opt('titleFormat'),
  2285. ' \u2014 ' // emphasized dash
  2286. );
  2287. t.renderBasic(1, t.getCellsPerWeek(), false);
  2288. }
  2289. }
  2290. ;;
  2291. fcViews.basicDay = BasicDayView;
  2292. function BasicDayView(element, calendar) { // TODO: make a DayView mixin
  2293. var t = this;
  2294. // exports
  2295. t.incrementDate = incrementDate;
  2296. t.render = render;
  2297. // imports
  2298. BasicView.call(t, element, calendar, 'basicDay');
  2299. function incrementDate(date, delta) {
  2300. var out = date.clone().stripTime().add('days', delta);
  2301. out = t.skipHiddenDays(out, delta < 0 ? -1 : 1);
  2302. return out;
  2303. }
  2304. function render(date) {
  2305. t.start = t.intervalStart = date.clone().stripTime();
  2306. t.end = t.intervalEnd = t.start.clone().add('days', 1);
  2307. t.title = calendar.formatDate(t.start, t.opt('titleFormat'));
  2308. t.renderBasic(1, 1, false);
  2309. }
  2310. }
  2311. ;;
  2312. setDefaults({
  2313. weekMode: 'fixed'
  2314. });
  2315. function BasicView(element, calendar, viewName) {
  2316. var t = this;
  2317. // exports
  2318. t.renderBasic = renderBasic;
  2319. t.setHeight = setHeight;
  2320. t.setWidth = setWidth;
  2321. t.renderDayOverlay = renderDayOverlay;
  2322. t.defaultSelectionEnd = defaultSelectionEnd;
  2323. t.renderSelection = renderSelection;
  2324. t.clearSelection = clearSelection;
  2325. t.reportDayClick = reportDayClick; // for selection (kinda hacky)
  2326. t.dragStart = dragStart;
  2327. t.dragStop = dragStop;
  2328. t.getHoverListener = function() { return hoverListener; };
  2329. t.colLeft = colLeft;
  2330. t.colRight = colRight;
  2331. t.colContentLeft = colContentLeft;
  2332. t.colContentRight = colContentRight;
  2333. t.getIsCellAllDay = function() { return true; };
  2334. t.allDayRow = allDayRow;
  2335. t.getRowCnt = function() { return rowCnt; };
  2336. t.getColCnt = function() { return colCnt; };
  2337. t.getColWidth = function() { return colWidth; };
  2338. t.getDaySegmentContainer = function() { return daySegmentContainer; };
  2339. // imports
  2340. View.call(t, element, calendar, viewName);
  2341. OverlayManager.call(t);
  2342. SelectionManager.call(t);
  2343. BasicEventRenderer.call(t);
  2344. var opt = t.opt;
  2345. var trigger = t.trigger;
  2346. var renderOverlay = t.renderOverlay;
  2347. var clearOverlays = t.clearOverlays;
  2348. var daySelectionMousedown = t.daySelectionMousedown;
  2349. var cellToDate = t.cellToDate;
  2350. var dateToCell = t.dateToCell;
  2351. var rangeToSegments = t.rangeToSegments;
  2352. var formatDate = calendar.formatDate;
  2353. var calculateWeekNumber = calendar.calculateWeekNumber;
  2354. // locals
  2355. var table;
  2356. var head;
  2357. var headCells;
  2358. var body;
  2359. var bodyRows;
  2360. var bodyCells;
  2361. var bodyFirstCells;
  2362. var firstRowCellInners;
  2363. var firstRowCellContentInners;
  2364. var daySegmentContainer;
  2365. var viewWidth;
  2366. var viewHeight;
  2367. var colWidth;
  2368. var weekNumberWidth;
  2369. var rowCnt, colCnt;
  2370. var showNumbers;
  2371. var coordinateGrid;
  2372. var hoverListener;
  2373. var colPositions;
  2374. var colContentPositions;
  2375. var tm;
  2376. var colFormat;
  2377. var showWeekNumbers;
  2378. /* Rendering
  2379. ------------------------------------------------------------*/
  2380. disableTextSelection(element.addClass('fc-grid'));
  2381. function renderBasic(_rowCnt, _colCnt, _showNumbers) {
  2382. rowCnt = _rowCnt;
  2383. colCnt = _colCnt;
  2384. showNumbers = _showNumbers;
  2385. updateOptions();
  2386. if (!body) {
  2387. buildEventContainer();
  2388. }
  2389. buildTable();
  2390. }
  2391. function updateOptions() {
  2392. tm = opt('theme') ? 'ui' : 'fc';
  2393. colFormat = opt('columnFormat');
  2394. showWeekNumbers = opt('weekNumbers');
  2395. }
  2396. function buildEventContainer() {
  2397. daySegmentContainer =
  2398. $("<div class='fc-event-container' style='position:absolute;z-index:8;top:0;left:0'/>")
  2399. .appendTo(element);
  2400. }
  2401. function buildTable() {
  2402. var html = buildTableHTML();
  2403. if (table) {
  2404. table.remove();
  2405. }
  2406. table = $(html).appendTo(element);
  2407. head = table.find('thead');
  2408. headCells = head.find('.fc-day-header');
  2409. body = table.find('tbody');
  2410. bodyRows = body.find('tr');
  2411. bodyCells = body.find('.fc-day');
  2412. bodyFirstCells = bodyRows.find('td:first-child');
  2413. firstRowCellInners = bodyRows.eq(0).find('.fc-day > div');
  2414. firstRowCellContentInners = bodyRows.eq(0).find('.fc-day-content > div');
  2415. markFirstLast(head.add(head.find('tr'))); // marks first+last tr/th's
  2416. markFirstLast(bodyRows); // marks first+last td's
  2417. bodyRows.eq(0).addClass('fc-first');
  2418. bodyRows.filter(':last').addClass('fc-last');
  2419. bodyCells.each(function(i, _cell) {
  2420. var date = cellToDate(
  2421. Math.floor(i / colCnt),
  2422. i % colCnt
  2423. );
  2424. trigger('dayRender', t, date, $(_cell));
  2425. });
  2426. dayBind(bodyCells);
  2427. }
  2428. /* HTML Building
  2429. -----------------------------------------------------------*/
  2430. function buildTableHTML() {
  2431. var html =
  2432. "<table class='fc-border-separate' style='width:100%' cellspacing='0'>" +
  2433. buildHeadHTML() +
  2434. buildBodyHTML() +
  2435. "</table>";
  2436. return html;
  2437. }
  2438. function buildHeadHTML() {
  2439. var headerClass = tm + "-widget-header";
  2440. var html = '';
  2441. var col;
  2442. var date;
  2443. html += "<thead><tr>";
  2444. if (showWeekNumbers) {
  2445. html +=
  2446. "<th class='fc-week-number " + headerClass + "'>" +
  2447. htmlEscape(opt('weekNumberTitle')) +
  2448. "</th>";
  2449. }
  2450. for (col=0; col<colCnt; col++) {
  2451. date = cellToDate(0, col);
  2452. html +=
  2453. "<th class='fc-day-header fc-" + dayIDs[date.day()] + " " + headerClass + "'>" +
  2454. htmlEscape(formatDate(date, colFormat)) +
  2455. "</th>";
  2456. }
  2457. html += "</tr></thead>";
  2458. return html;
  2459. }
  2460. function buildBodyHTML() {
  2461. var contentClass = tm + "-widget-content";
  2462. var html = '';
  2463. var row;
  2464. var col;
  2465. var date;
  2466. html += "<tbody>";
  2467. for (row=0; row<rowCnt; row++) {
  2468. html += "<tr class='fc-week'>";
  2469. if (showWeekNumbers) {
  2470. date = cellToDate(row, 0);
  2471. html +=
  2472. "<td class='fc-week-number " + contentClass + "'>" +
  2473. "<div>" +
  2474. htmlEscape(calculateWeekNumber(date)) +
  2475. "</div>" +
  2476. "</td>";
  2477. }
  2478. for (col=0; col<colCnt; col++) {
  2479. date = cellToDate(row, col);
  2480. html += buildCellHTML(date);
  2481. }
  2482. html += "</tr>";
  2483. }
  2484. html += "</tbody>";
  2485. return html;
  2486. }
  2487. function buildCellHTML(date) { // date assumed to have stripped time
  2488. var month = t.intervalStart.month();
  2489. var today = calendar.getNow().stripTime();
  2490. var html = '';
  2491. var contentClass = tm + "-widget-content";
  2492. var classNames = [
  2493. 'fc-day',
  2494. 'fc-' + dayIDs[date.day()],
  2495. contentClass
  2496. ];
  2497. if (date.month() != month) {
  2498. classNames.push('fc-other-month');
  2499. }
  2500. if (date.isSame(today, 'day')) {
  2501. classNames.push(
  2502. 'fc-today',
  2503. tm + '-state-highlight'
  2504. );
  2505. }
  2506. else if (date < today) {
  2507. classNames.push('fc-past');
  2508. }
  2509. else {
  2510. classNames.push('fc-future');
  2511. }
  2512. html +=
  2513. "<td" +
  2514. " class='" + classNames.join(' ') + "'" +
  2515. " data-date='" + date.format() + "'" +
  2516. ">" +
  2517. "<div>";
  2518. if (showNumbers) {
  2519. html += "<div class='fc-day-number'>" + date.date() + "</div>";
  2520. }
  2521. html +=
  2522. "<div class='fc-day-content'>" +
  2523. "<div style='position:relative'>&nbsp;</div>" +
  2524. "</div>" +
  2525. "</div>" +
  2526. "</td>";
  2527. return html;
  2528. }
  2529. /* Dimensions
  2530. -----------------------------------------------------------*/
  2531. function setHeight(height) {
  2532. viewHeight = height;
  2533. var bodyHeight = Math.max(viewHeight - head.height(), 0);
  2534. var rowHeight;
  2535. var rowHeightLast;
  2536. var cell;
  2537. if (opt('weekMode') == 'variable') {
  2538. rowHeight = rowHeightLast = Math.floor(bodyHeight / (rowCnt==1 ? 2 : 6));
  2539. }else{
  2540. rowHeight = Math.floor(bodyHeight / rowCnt);
  2541. rowHeightLast = bodyHeight - rowHeight * (rowCnt-1);
  2542. }
  2543. bodyFirstCells.each(function(i, _cell) {
  2544. if (i < rowCnt) {
  2545. cell = $(_cell);
  2546. cell.find('> div').css(
  2547. 'min-height',
  2548. (i==rowCnt-1 ? rowHeightLast : rowHeight) - vsides(cell)
  2549. );
  2550. }
  2551. });
  2552. }
  2553. function setWidth(width) {
  2554. viewWidth = width;
  2555. colPositions.clear();
  2556. colContentPositions.clear();
  2557. weekNumberWidth = 0;
  2558. if (showWeekNumbers) {
  2559. weekNumberWidth = head.find('th.fc-week-number').outerWidth();
  2560. }
  2561. colWidth = Math.floor((viewWidth - weekNumberWidth) / colCnt);
  2562. setOuterWidth(headCells.slice(0, -1), colWidth);
  2563. }
  2564. /* Day clicking and binding
  2565. -----------------------------------------------------------*/
  2566. function dayBind(days) {
  2567. days.click(dayClick)
  2568. .mousedown(daySelectionMousedown);
  2569. }
  2570. function dayClick(ev) {
  2571. if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick
  2572. var date = calendar.moment($(this).data('date'));
  2573. trigger('dayClick', this, date, ev);
  2574. }
  2575. }
  2576. /* Semi-transparent Overlay Helpers
  2577. ------------------------------------------------------*/
  2578. // TODO: should be consolidated with AgendaView's methods
  2579. function renderDayOverlay(overlayStart, overlayEnd, refreshCoordinateGrid) { // overlayEnd is exclusive
  2580. if (refreshCoordinateGrid) {
  2581. coordinateGrid.build();
  2582. }
  2583. var segments = rangeToSegments(overlayStart, overlayEnd);
  2584. for (var i=0; i<segments.length; i++) {
  2585. var segment = segments[i];
  2586. dayBind(
  2587. renderCellOverlay(
  2588. segment.row,
  2589. segment.leftCol,
  2590. segment.row,
  2591. segment.rightCol
  2592. )
  2593. );
  2594. }
  2595. }
  2596. function renderCellOverlay(row0, col0, row1, col1) { // row1,col1 is inclusive
  2597. var rect = coordinateGrid.rect(row0, col0, row1, col1, element);
  2598. return renderOverlay(rect, element);
  2599. }
  2600. /* Selection
  2601. -----------------------------------------------------------------------*/
  2602. function defaultSelectionEnd(start) {
  2603. return start.clone().stripTime().add('days', 1);
  2604. }
  2605. function renderSelection(start, end) { // end is exclusive
  2606. renderDayOverlay(start, end, true); // true = rebuild every time
  2607. }
  2608. function clearSelection() {
  2609. clearOverlays();
  2610. }
  2611. function reportDayClick(date, ev) {
  2612. var cell = dateToCell(date);
  2613. var _element = bodyCells[cell.row*colCnt + cell.col];
  2614. trigger('dayClick', _element, date, ev);
  2615. }
  2616. /* External Dragging
  2617. -----------------------------------------------------------------------*/
  2618. function dragStart(_dragElement, ev, ui) {
  2619. hoverListener.start(function(cell) {
  2620. clearOverlays();
  2621. if (cell) {
  2622. var d1 = cellToDate(cell);
  2623. var d2 = d1.clone().add(calendar.defaultAllDayEventDuration);
  2624. renderDayOverlay(d1, d2);
  2625. }
  2626. }, ev);
  2627. }
  2628. function dragStop(_dragElement, ev, ui) {
  2629. var cell = hoverListener.stop();
  2630. clearOverlays();
  2631. if (cell) {
  2632. trigger(
  2633. 'drop',
  2634. _dragElement,
  2635. cellToDate(cell),
  2636. ev,
  2637. ui
  2638. );
  2639. }
  2640. }
  2641. /* Utilities
  2642. --------------------------------------------------------*/
  2643. coordinateGrid = new CoordinateGrid(function(rows, cols) {
  2644. var e, n, p;
  2645. headCells.each(function(i, _e) {
  2646. e = $(_e);
  2647. n = e.offset().left;
  2648. if (i) {
  2649. p[1] = n;
  2650. }
  2651. p = [n];
  2652. cols[i] = p;
  2653. });
  2654. p[1] = n + e.outerWidth();
  2655. bodyRows.each(function(i, _e) {
  2656. if (i < rowCnt) {
  2657. e = $(_e);
  2658. n = e.offset().top;
  2659. if (i) {
  2660. p[1] = n;
  2661. }
  2662. p = [n];
  2663. rows[i] = p;
  2664. }
  2665. });
  2666. p[1] = n + e.outerHeight();
  2667. });
  2668. hoverListener = new HoverListener(coordinateGrid);
  2669. colPositions = new HorizontalPositionCache(function(col) {
  2670. return firstRowCellInners.eq(col);
  2671. });
  2672. colContentPositions = new HorizontalPositionCache(function(col) {
  2673. return firstRowCellContentInners.eq(col);
  2674. });
  2675. function colLeft(col) {
  2676. return colPositions.left(col);
  2677. }
  2678. function colRight(col) {
  2679. return colPositions.right(col);
  2680. }
  2681. function colContentLeft(col) {
  2682. return colContentPositions.left(col);
  2683. }
  2684. function colContentRight(col) {
  2685. return colContentPositions.right(col);
  2686. }
  2687. function allDayRow(i) {
  2688. return bodyRows.eq(i);
  2689. }
  2690. }
  2691. ;;
  2692. function BasicEventRenderer() {
  2693. var t = this;
  2694. // exports
  2695. t.renderEvents = renderEvents;
  2696. t.clearEvents = clearEvents;
  2697. // imports
  2698. DayEventRenderer.call(t);
  2699. function renderEvents(events, modifiedEventId) {
  2700. t.renderDayEvents(events, modifiedEventId);
  2701. }
  2702. function clearEvents() {
  2703. t.getDaySegmentContainer().empty();
  2704. }
  2705. // TODO: have this class (and AgendaEventRenderer) be responsible for creating the event container div
  2706. }
  2707. ;;
  2708. fcViews.agendaWeek = AgendaWeekView;
  2709. function AgendaWeekView(element, calendar) { // TODO: do a WeekView mixin
  2710. var t = this;
  2711. // exports
  2712. t.incrementDate = incrementDate;
  2713. t.render = render;
  2714. // imports
  2715. AgendaView.call(t, element, calendar, 'agendaWeek');
  2716. function incrementDate(date, delta) {
  2717. return date.clone().stripTime().add('weeks', delta).startOf('week');
  2718. }
  2719. function render(date) {
  2720. t.intervalStart = date.clone().stripTime().startOf('week');
  2721. t.intervalEnd = t.intervalStart.clone().add('weeks', 1);
  2722. t.start = t.skipHiddenDays(t.intervalStart);
  2723. t.end = t.skipHiddenDays(t.intervalEnd, -1, true);
  2724. t.title = calendar.formatRange(
  2725. t.start,
  2726. t.end.clone().subtract(1), // make inclusive by subtracting 1 ms
  2727. t.opt('titleFormat'),
  2728. ' \u2014 ' // emphasized dash
  2729. );
  2730. t.renderAgenda(t.getCellsPerWeek());
  2731. }
  2732. }
  2733. ;;
  2734. fcViews.agendaDay = AgendaDayView;
  2735. function AgendaDayView(element, calendar) { // TODO: make a DayView mixin
  2736. var t = this;
  2737. // exports
  2738. t.incrementDate = incrementDate;
  2739. t.render = render;
  2740. // imports
  2741. AgendaView.call(t, element, calendar, 'agendaDay');
  2742. function incrementDate(date, delta) {
  2743. var out = date.clone().stripTime().add('days', delta);
  2744. out = t.skipHiddenDays(out, delta < 0 ? -1 : 1);
  2745. return out;
  2746. }
  2747. function render(date) {
  2748. t.start = t.intervalStart = date.clone().stripTime();
  2749. t.end = t.intervalEnd = t.start.clone().add('days', 1);
  2750. t.title = calendar.formatDate(t.start, t.opt('titleFormat'));
  2751. t.renderAgenda(1);
  2752. }
  2753. }
  2754. ;;
  2755. setDefaults({
  2756. allDaySlot: true,
  2757. allDayText: 'all-day',
  2758. scrollTime: '06:00:00',
  2759. slotDuration: '00:30:00',
  2760. axisFormat: generateAgendaAxisFormat,
  2761. timeFormat: {
  2762. agenda: generateAgendaTimeFormat
  2763. },
  2764. dragOpacity: {
  2765. agenda: .5
  2766. },
  2767. minTime: '00:00:00',
  2768. maxTime: '24:00:00',
  2769. slotEventOverlap: true
  2770. });
  2771. function generateAgendaAxisFormat(options, langData) {
  2772. return langData.longDateFormat('LT')
  2773. .replace(':mm', '(:mm)')
  2774. .replace(/(\Wmm)$/, '($1)') // like above, but for foreign langs
  2775. .replace(/\s*a$/i, 'a'); // convert AM/PM/am/pm to lowercase. remove any spaces beforehand
  2776. }
  2777. function generateAgendaTimeFormat(options, langData) {
  2778. return langData.longDateFormat('LT')
  2779. .replace(/\s*a$/i, ''); // remove trailing AM/PM
  2780. }
  2781. // TODO: make it work in quirks mode (event corners, all-day height)
  2782. // TODO: test liquid width, especially in IE6
  2783. function AgendaView(element, calendar, viewName) {
  2784. var t = this;
  2785. // exports
  2786. t.renderAgenda = renderAgenda;
  2787. t.setWidth = setWidth;
  2788. t.setHeight = setHeight;
  2789. t.afterRender = afterRender;
  2790. t.computeDateTop = computeDateTop;
  2791. t.getIsCellAllDay = getIsCellAllDay;
  2792. t.allDayRow = function() { return allDayRow; }; // badly named
  2793. t.getCoordinateGrid = function() { return coordinateGrid; }; // specifically for AgendaEventRenderer
  2794. t.getHoverListener = function() { return hoverListener; };
  2795. t.colLeft = colLeft;
  2796. t.colRight = colRight;
  2797. t.colContentLeft = colContentLeft;
  2798. t.colContentRight = colContentRight;
  2799. t.getDaySegmentContainer = function() { return daySegmentContainer; };
  2800. t.getSlotSegmentContainer = function() { return slotSegmentContainer; };
  2801. t.getSlotContainer = function() { return slotContainer; };
  2802. t.getRowCnt = function() { return 1; };
  2803. t.getColCnt = function() { return colCnt; };
  2804. t.getColWidth = function() { return colWidth; };
  2805. t.getSnapHeight = function() { return snapHeight; };
  2806. t.getSnapDuration = function() { return snapDuration; };
  2807. t.getSlotHeight = function() { return slotHeight; };
  2808. t.getSlotDuration = function() { return slotDuration; };
  2809. t.getMinTime = function() { return minTime; };
  2810. t.getMaxTime = function() { return maxTime; };
  2811. t.defaultSelectionEnd = defaultSelectionEnd;
  2812. t.renderDayOverlay = renderDayOverlay;
  2813. t.renderSelection = renderSelection;
  2814. t.clearSelection = clearSelection;
  2815. t.reportDayClick = reportDayClick; // selection mousedown hack
  2816. t.dragStart = dragStart;
  2817. t.dragStop = dragStop;
  2818. // imports
  2819. View.call(t, element, calendar, viewName);
  2820. OverlayManager.call(t);
  2821. SelectionManager.call(t);
  2822. AgendaEventRenderer.call(t);
  2823. var opt = t.opt;
  2824. var trigger = t.trigger;
  2825. var renderOverlay = t.renderOverlay;
  2826. var clearOverlays = t.clearOverlays;
  2827. var reportSelection = t.reportSelection;
  2828. var unselect = t.unselect;
  2829. var daySelectionMousedown = t.daySelectionMousedown;
  2830. var slotSegHtml = t.slotSegHtml;
  2831. var cellToDate = t.cellToDate;
  2832. var dateToCell = t.dateToCell;
  2833. var rangeToSegments = t.rangeToSegments;
  2834. var formatDate = calendar.formatDate;
  2835. var calculateWeekNumber = calendar.calculateWeekNumber;
  2836. // locals
  2837. var dayTable;
  2838. var dayHead;
  2839. var dayHeadCells;
  2840. var dayBody;
  2841. var dayBodyCells;
  2842. var dayBodyCellInners;
  2843. var dayBodyCellContentInners;
  2844. var dayBodyFirstCell;
  2845. var dayBodyFirstCellStretcher;
  2846. var slotLayer;
  2847. var daySegmentContainer;
  2848. var allDayTable;
  2849. var allDayRow;
  2850. var slotScroller;
  2851. var slotContainer;
  2852. var slotSegmentContainer;
  2853. var slotTable;
  2854. var selectionHelper;
  2855. var viewWidth;
  2856. var viewHeight;
  2857. var axisWidth;
  2858. var colWidth;
  2859. var gutterWidth;
  2860. var slotDuration;
  2861. var slotHeight; // TODO: what if slotHeight changes? (see issue 650)
  2862. var snapDuration;
  2863. var snapRatio; // ratio of number of "selection" slots to normal slots. (ex: 1, 2, 4)
  2864. var snapHeight; // holds the pixel hight of a "selection" slot
  2865. var colCnt;
  2866. var slotCnt;
  2867. var coordinateGrid;
  2868. var hoverListener;
  2869. var colPositions;
  2870. var colContentPositions;
  2871. var slotTopCache = {};
  2872. var tm;
  2873. var rtl;
  2874. var minTime;
  2875. var maxTime;
  2876. var colFormat;
  2877. /* Rendering
  2878. -----------------------------------------------------------------------------*/
  2879. disableTextSelection(element.addClass('fc-agenda'));
  2880. function renderAgenda(c) {
  2881. colCnt = c;
  2882. updateOptions();
  2883. if (!dayTable) { // first time rendering?
  2884. buildSkeleton(); // builds day table, slot area, events containers
  2885. }
  2886. else {
  2887. buildDayTable(); // rebuilds day table
  2888. }
  2889. }
  2890. function updateOptions() {
  2891. tm = opt('theme') ? 'ui' : 'fc';
  2892. rtl = opt('isRTL');
  2893. colFormat = opt('columnFormat');
  2894. minTime = moment.duration(opt('minTime'));
  2895. maxTime = moment.duration(opt('maxTime'));
  2896. slotDuration = moment.duration(opt('slotDuration'));
  2897. snapDuration = opt('snapDuration');
  2898. snapDuration = snapDuration ? moment.duration(snapDuration) : slotDuration;
  2899. }
  2900. /* Build DOM
  2901. -----------------------------------------------------------------------*/
  2902. function buildSkeleton() {
  2903. var s;
  2904. var headerClass = tm + "-widget-header";
  2905. var contentClass = tm + "-widget-content";
  2906. var slotTime;
  2907. var slotDate;
  2908. var minutes;
  2909. var slotNormal = slotDuration.asMinutes() % 15 === 0;
  2910. buildDayTable();
  2911. slotLayer =
  2912. $("<div style='position:absolute;z-index:2;left:0;width:100%'/>")
  2913. .appendTo(element);
  2914. if (opt('allDaySlot')) {
  2915. daySegmentContainer =
  2916. $("<div class='fc-event-container' style='position:absolute;z-index:8;top:0;left:0'/>")
  2917. .appendTo(slotLayer);
  2918. s =
  2919. "<table style='width:100%' class='fc-agenda-allday' cellspacing='0'>" +
  2920. "<tr>" +
  2921. "<th class='" + headerClass + " fc-agenda-axis'>" +
  2922. (
  2923. opt('allDayHTML') ||
  2924. htmlEscape(opt('allDayText'))
  2925. ) +
  2926. "</th>" +
  2927. "<td>" +
  2928. "<div class='fc-day-content'><div style='position:relative'/></div>" +
  2929. "</td>" +
  2930. "<th class='" + headerClass + " fc-agenda-gutter'>&nbsp;</th>" +
  2931. "</tr>" +
  2932. "</table>";
  2933. allDayTable = $(s).appendTo(slotLayer);
  2934. allDayRow = allDayTable.find('tr');
  2935. dayBind(allDayRow.find('td'));
  2936. slotLayer.append(
  2937. "<div class='fc-agenda-divider " + headerClass + "'>" +
  2938. "<div class='fc-agenda-divider-inner'/>" +
  2939. "</div>"
  2940. );
  2941. }else{
  2942. daySegmentContainer = $([]); // in jQuery 1.4, we can just do $()
  2943. }
  2944. slotScroller =
  2945. $("<div style='position:absolute;width:100%;overflow-x:hidden;overflow-y:auto'/>")
  2946. .appendTo(slotLayer);
  2947. slotContainer =
  2948. $("<div style='position:relative;width:100%;overflow:hidden'/>")
  2949. .appendTo(slotScroller);
  2950. slotSegmentContainer =
  2951. $("<div class='fc-event-container' style='position:absolute;z-index:8;top:0;left:0'/>")
  2952. .appendTo(slotContainer);
  2953. s =
  2954. "<table class='fc-agenda-slots' style='width:100%' cellspacing='0'>" +
  2955. "<tbody>";
  2956. slotTime = moment.duration(+minTime); // i wish there was .clone() for durations
  2957. slotCnt = 0;
  2958. while (slotTime < maxTime) {
  2959. slotDate = t.start.clone().time(slotTime); // will be in UTC but that's good. to avoid DST issues
  2960. minutes = slotDate.minutes();
  2961. s +=
  2962. "<tr class='fc-slot" + slotCnt + ' ' + (!minutes ? '' : 'fc-minor') + "'>" +
  2963. "<th class='fc-agenda-axis " + headerClass + "'>" +
  2964. ((!slotNormal || !minutes) ?
  2965. htmlEscape(formatDate(slotDate, opt('axisFormat'))) :
  2966. '&nbsp;'
  2967. ) +
  2968. "</th>" +
  2969. "<td class='" + contentClass + "'>" +
  2970. "<div style='position:relative'>&nbsp;</div>" +
  2971. "</td>" +
  2972. "</tr>";
  2973. slotTime.add(slotDuration);
  2974. slotCnt++;
  2975. }
  2976. s +=
  2977. "</tbody>" +
  2978. "</table>";
  2979. slotTable = $(s).appendTo(slotContainer);
  2980. slotBind(slotTable.find('td'));
  2981. }
  2982. /* Build Day Table
  2983. -----------------------------------------------------------------------*/
  2984. function buildDayTable() {
  2985. var html = buildDayTableHTML();
  2986. if (dayTable) {
  2987. dayTable.remove();
  2988. }
  2989. dayTable = $(html).appendTo(element);
  2990. dayHead = dayTable.find('thead');
  2991. dayHeadCells = dayHead.find('th').slice(1, -1); // exclude gutter
  2992. dayBody = dayTable.find('tbody');
  2993. dayBodyCells = dayBody.find('td').slice(0, -1); // exclude gutter
  2994. dayBodyCellInners = dayBodyCells.find('> div');
  2995. dayBodyCellContentInners = dayBodyCells.find('.fc-day-content > div');
  2996. dayBodyFirstCell = dayBodyCells.eq(0);
  2997. dayBodyFirstCellStretcher = dayBodyCellInners.eq(0);
  2998. markFirstLast(dayHead.add(dayHead.find('tr')));
  2999. markFirstLast(dayBody.add(dayBody.find('tr')));
  3000. // TODO: now that we rebuild the cells every time, we should call dayRender
  3001. }
  3002. function buildDayTableHTML() {
  3003. var html =
  3004. "<table style='width:100%' class='fc-agenda-days fc-border-separate' cellspacing='0'>" +
  3005. buildDayTableHeadHTML() +
  3006. buildDayTableBodyHTML() +
  3007. "</table>";
  3008. return html;
  3009. }
  3010. function buildDayTableHeadHTML() {
  3011. var headerClass = tm + "-widget-header";
  3012. var date;
  3013. var html = '';
  3014. var weekText;
  3015. var col;
  3016. html +=
  3017. "<thead>" +
  3018. "<tr>";
  3019. if (opt('weekNumbers')) {
  3020. date = cellToDate(0, 0);
  3021. weekText = calculateWeekNumber(date);
  3022. if (rtl) {
  3023. weekText += opt('weekNumberTitle');
  3024. }
  3025. else {
  3026. weekText = opt('weekNumberTitle') + weekText;
  3027. }
  3028. html +=
  3029. "<th class='fc-agenda-axis fc-week-number " + headerClass + "'>" +
  3030. htmlEscape(weekText) +
  3031. "</th>";
  3032. }
  3033. else {
  3034. html += "<th class='fc-agenda-axis " + headerClass + "'>&nbsp;</th>";
  3035. }
  3036. for (col=0; col<colCnt; col++) {
  3037. date = cellToDate(0, col);
  3038. html +=
  3039. "<th class='fc-" + dayIDs[date.day()] + " fc-col" + col + ' ' + headerClass + "'>" +
  3040. htmlEscape(formatDate(date, colFormat)) +
  3041. "</th>";
  3042. }
  3043. html +=
  3044. "<th class='fc-agenda-gutter " + headerClass + "'>&nbsp;</th>" +
  3045. "</tr>" +
  3046. "</thead>";
  3047. return html;
  3048. }
  3049. function buildDayTableBodyHTML() {
  3050. var headerClass = tm + "-widget-header"; // TODO: make these when updateOptions() called
  3051. var contentClass = tm + "-widget-content";
  3052. var date;
  3053. var today = calendar.getNow().stripTime();
  3054. var col;
  3055. var cellsHTML;
  3056. var cellHTML;
  3057. var classNames;
  3058. var html = '';
  3059. html +=
  3060. "<tbody>" +
  3061. "<tr>" +
  3062. "<th class='fc-agenda-axis " + headerClass + "'>&nbsp;</th>";
  3063. cellsHTML = '';
  3064. for (col=0; col<colCnt; col++) {
  3065. date = cellToDate(0, col);
  3066. classNames = [
  3067. 'fc-col' + col,
  3068. 'fc-' + dayIDs[date.day()],
  3069. contentClass
  3070. ];
  3071. if (date.isSame(today, 'day')) {
  3072. classNames.push(
  3073. tm + '-state-highlight',
  3074. 'fc-today'
  3075. );
  3076. }
  3077. else if (date < today) {
  3078. classNames.push('fc-past');
  3079. }
  3080. else {
  3081. classNames.push('fc-future');
  3082. }
  3083. cellHTML =
  3084. "<td class='" + classNames.join(' ') + "'>" +
  3085. "<div>" +
  3086. "<div class='fc-day-content'>" +
  3087. "<div style='position:relative'>&nbsp;</div>" +
  3088. "</div>" +
  3089. "</div>" +
  3090. "</td>";
  3091. cellsHTML += cellHTML;
  3092. }
  3093. html += cellsHTML;
  3094. html +=
  3095. "<td class='fc-agenda-gutter " + contentClass + "'>&nbsp;</td>" +
  3096. "</tr>" +
  3097. "</tbody>";
  3098. return html;
  3099. }
  3100. // TODO: data-date on the cells
  3101. /* Dimensions
  3102. -----------------------------------------------------------------------*/
  3103. function setHeight(height) {
  3104. if (height === undefined) {
  3105. height = viewHeight;
  3106. }
  3107. viewHeight = height;
  3108. slotTopCache = {};
  3109. var headHeight = dayBody.position().top;
  3110. var allDayHeight = slotScroller.position().top; // including divider
  3111. var bodyHeight = Math.min( // total body height, including borders
  3112. height - headHeight, // when scrollbars
  3113. slotTable.height() + allDayHeight + 1 // when no scrollbars. +1 for bottom border
  3114. );
  3115. dayBodyFirstCellStretcher
  3116. .height(bodyHeight - vsides(dayBodyFirstCell));
  3117. slotLayer.css('top', headHeight);
  3118. slotScroller.height(bodyHeight - allDayHeight - 1);
  3119. // the stylesheet guarantees that the first row has no border.
  3120. // this allows .height() to work well cross-browser.
  3121. var slotHeight0 = slotTable.find('tr:first').height() + 1; // +1 for bottom border
  3122. var slotHeight1 = slotTable.find('tr:eq(1)').height();
  3123. // HACK: i forget why we do this, but i think a cross-browser issue
  3124. slotHeight = (slotHeight0 + slotHeight1) / 2;
  3125. snapRatio = slotDuration / snapDuration;
  3126. snapHeight = slotHeight / snapRatio;
  3127. }
  3128. function setWidth(width) {
  3129. viewWidth = width;
  3130. colPositions.clear();
  3131. colContentPositions.clear();
  3132. var axisFirstCells = dayHead.find('th:first');
  3133. if (allDayTable) {
  3134. axisFirstCells = axisFirstCells.add(allDayTable.find('th:first'));
  3135. }
  3136. axisFirstCells = axisFirstCells.add(slotTable.find('th:first'));
  3137. axisWidth = 0;
  3138. setOuterWidth(
  3139. axisFirstCells
  3140. .width('')
  3141. .each(function(i, _cell) {
  3142. axisWidth = Math.max(axisWidth, $(_cell).outerWidth());
  3143. }),
  3144. axisWidth
  3145. );
  3146. var gutterCells = dayTable.find('.fc-agenda-gutter');
  3147. if (allDayTable) {
  3148. gutterCells = gutterCells.add(allDayTable.find('th.fc-agenda-gutter'));
  3149. }
  3150. var slotTableWidth = slotScroller[0].clientWidth; // needs to be done after axisWidth (for IE7)
  3151. gutterWidth = slotScroller.width() - slotTableWidth;
  3152. if (gutterWidth) {
  3153. setOuterWidth(gutterCells, gutterWidth);
  3154. gutterCells
  3155. .show()
  3156. .prev()
  3157. .removeClass('fc-last');
  3158. }else{
  3159. gutterCells
  3160. .hide()
  3161. .prev()
  3162. .addClass('fc-last');
  3163. }
  3164. colWidth = Math.floor((slotTableWidth - axisWidth) / colCnt);
  3165. setOuterWidth(dayHeadCells.slice(0, -1), colWidth);
  3166. }
  3167. /* Scrolling
  3168. -----------------------------------------------------------------------*/
  3169. function resetScroll() {
  3170. var top = computeTimeTop(
  3171. moment.duration(opt('scrollTime'))
  3172. ) + 1; // +1 for the border
  3173. function scroll() {
  3174. slotScroller.scrollTop(top);
  3175. }
  3176. scroll();
  3177. setTimeout(scroll, 0); // overrides any previous scroll state made by the browser
  3178. }
  3179. function afterRender() { // after the view has been freshly rendered and sized
  3180. resetScroll();
  3181. }
  3182. /* Slot/Day clicking and binding
  3183. -----------------------------------------------------------------------*/
  3184. function dayBind(cells) {
  3185. cells.click(slotClick)
  3186. .mousedown(daySelectionMousedown);
  3187. }
  3188. function slotBind(cells) {
  3189. cells.click(slotClick)
  3190. .mousedown(slotSelectionMousedown);
  3191. }
  3192. function slotClick(ev) {
  3193. if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick
  3194. var col = Math.min(colCnt-1, Math.floor((ev.pageX - dayTable.offset().left - axisWidth) / colWidth));
  3195. var date = cellToDate(0, col);
  3196. var match = this.parentNode.className.match(/fc-slot(\d+)/); // TODO: maybe use data
  3197. if (match) {
  3198. var slotIndex = parseInt(match[1], 10);
  3199. date.add(minTime + slotIndex * slotDuration);
  3200. date = calendar.rezoneDate(date);
  3201. trigger(
  3202. 'dayClick',
  3203. dayBodyCells[col],
  3204. date,
  3205. ev
  3206. );
  3207. }else{
  3208. trigger(
  3209. 'dayClick',
  3210. dayBodyCells[col],
  3211. date,
  3212. ev
  3213. );
  3214. }
  3215. }
  3216. }
  3217. /* Semi-transparent Overlay Helpers
  3218. -----------------------------------------------------*/
  3219. // TODO: should be consolidated with BasicView's methods
  3220. function renderDayOverlay(overlayStart, overlayEnd, refreshCoordinateGrid) { // overlayEnd is exclusive
  3221. if (refreshCoordinateGrid) {
  3222. coordinateGrid.build();
  3223. }
  3224. var segments = rangeToSegments(overlayStart, overlayEnd);
  3225. for (var i=0; i<segments.length; i++) {
  3226. var segment = segments[i];
  3227. dayBind(
  3228. renderCellOverlay(
  3229. segment.row,
  3230. segment.leftCol,
  3231. segment.row,
  3232. segment.rightCol
  3233. )
  3234. );
  3235. }
  3236. }
  3237. function renderCellOverlay(row0, col0, row1, col1) { // only for all-day?
  3238. var rect = coordinateGrid.rect(row0, col0, row1, col1, slotLayer);
  3239. return renderOverlay(rect, slotLayer);
  3240. }
  3241. function renderSlotOverlay(overlayStart, overlayEnd) {
  3242. // normalize, because dayStart/dayEnd have stripped time+zone
  3243. overlayStart = overlayStart.clone().stripZone();
  3244. overlayEnd = overlayEnd.clone().stripZone();
  3245. for (var i=0; i<colCnt; i++) { // loop through the day columns
  3246. var dayStart = cellToDate(0, i);
  3247. var dayEnd = dayStart.clone().add('days', 1);
  3248. var stretchStart = dayStart < overlayStart ? overlayStart : dayStart; // the max of the two
  3249. var stretchEnd = dayEnd < overlayEnd ? dayEnd : overlayEnd; // the min of the two
  3250. if (stretchStart < stretchEnd) {
  3251. var rect = coordinateGrid.rect(0, i, 0, i, slotContainer); // only use it for horizontal coords
  3252. var top = computeDateTop(stretchStart, dayStart);
  3253. var bottom = computeDateTop(stretchEnd, dayStart);
  3254. rect.top = top;
  3255. rect.height = bottom - top;
  3256. slotBind(
  3257. renderOverlay(rect, slotContainer)
  3258. );
  3259. }
  3260. }
  3261. }
  3262. /* Coordinate Utilities
  3263. -----------------------------------------------------------------------------*/
  3264. coordinateGrid = new CoordinateGrid(function(rows, cols) {
  3265. var e, n, p;
  3266. dayHeadCells.each(function(i, _e) {
  3267. e = $(_e);
  3268. n = e.offset().left;
  3269. if (i) {
  3270. p[1] = n;
  3271. }
  3272. p = [n];
  3273. cols[i] = p;
  3274. });
  3275. p[1] = n + e.outerWidth();
  3276. if (opt('allDaySlot')) {
  3277. e = allDayRow;
  3278. n = e.offset().top;
  3279. rows[0] = [n, n+e.outerHeight()];
  3280. }
  3281. var slotTableTop = slotContainer.offset().top;
  3282. var slotScrollerTop = slotScroller.offset().top;
  3283. var slotScrollerBottom = slotScrollerTop + slotScroller.outerHeight();
  3284. function constrain(n) {
  3285. return Math.max(slotScrollerTop, Math.min(slotScrollerBottom, n));
  3286. }
  3287. for (var i=0; i<slotCnt*snapRatio; i++) { // adapt slot count to increased/decreased selection slot count
  3288. rows.push([
  3289. constrain(slotTableTop + snapHeight*i),
  3290. constrain(slotTableTop + snapHeight*(i+1))
  3291. ]);
  3292. }
  3293. });
  3294. hoverListener = new HoverListener(coordinateGrid);
  3295. colPositions = new HorizontalPositionCache(function(col) {
  3296. return dayBodyCellInners.eq(col);
  3297. });
  3298. colContentPositions = new HorizontalPositionCache(function(col) {
  3299. return dayBodyCellContentInners.eq(col);
  3300. });
  3301. function colLeft(col) {
  3302. return colPositions.left(col);
  3303. }
  3304. function colContentLeft(col) {
  3305. return colContentPositions.left(col);
  3306. }
  3307. function colRight(col) {
  3308. return colPositions.right(col);
  3309. }
  3310. function colContentRight(col) {
  3311. return colContentPositions.right(col);
  3312. }
  3313. // NOTE: the row index of these "cells" doesn't correspond to the slot index, but rather the "snap" index
  3314. function getIsCellAllDay(cell) { // TODO: remove because mom.hasTime() from realCellToDate() is better
  3315. return opt('allDaySlot') && !cell.row;
  3316. }
  3317. function realCellToDate(cell) { // ugh "real" ... but blame it on our abuse of the "cell" system
  3318. var date = cellToDate(0, cell.col);
  3319. var snapIndex = cell.row;
  3320. if (opt('allDaySlot')) {
  3321. snapIndex--;
  3322. }
  3323. if (snapIndex >= 0) {
  3324. date.time(moment.duration(minTime + snapIndex * snapDuration));
  3325. date = calendar.rezoneDate(date);
  3326. }
  3327. return date;
  3328. }
  3329. function computeDateTop(date, startOfDayDate) {
  3330. return computeTimeTop(
  3331. moment.duration(
  3332. date.clone().stripZone() - startOfDayDate.clone().stripTime()
  3333. )
  3334. );
  3335. }
  3336. function computeTimeTop(time) { // time is a duration
  3337. if (time < minTime) {
  3338. return 0;
  3339. }
  3340. if (time >= maxTime) {
  3341. return slotTable.height();
  3342. }
  3343. var slots = (time - minTime) / slotDuration;
  3344. var slotIndex = Math.floor(slots);
  3345. var slotPartial = slots - slotIndex;
  3346. var slotTop = slotTopCache[slotIndex];
  3347. // find the position of the corresponding <tr>
  3348. // need to use this tecnhique because not all rows are rendered at same height sometimes.
  3349. if (slotTop === undefined) {
  3350. slotTop = slotTopCache[slotIndex] =
  3351. slotTable.find('tr').eq(slotIndex).find('td div')[0].offsetTop;
  3352. // .eq() is faster than ":eq()" selector
  3353. // [0].offsetTop is faster than .position().top (do we really need this optimization?)
  3354. // a better optimization would be to cache all these divs
  3355. }
  3356. var top =
  3357. slotTop - 1 + // because first row doesn't have a top border
  3358. slotPartial * slotHeight; // part-way through the row
  3359. top = Math.max(top, 0);
  3360. return top;
  3361. }
  3362. /* Selection
  3363. ---------------------------------------------------------------------------------*/
  3364. function defaultSelectionEnd(start) {
  3365. if (start.hasTime()) {
  3366. return start.clone().add(slotDuration);
  3367. }
  3368. else {
  3369. return start.clone().add('days', 1);
  3370. }
  3371. }
  3372. function renderSelection(start, end) {
  3373. if (start.hasTime() || end.hasTime()) {
  3374. renderSlotSelection(start, end);
  3375. }
  3376. else if (opt('allDaySlot')) {
  3377. renderDayOverlay(start, end, true); // true for refreshing coordinate grid
  3378. }
  3379. }
  3380. function renderSlotSelection(startDate, endDate) {
  3381. var helperOption = opt('selectHelper');
  3382. coordinateGrid.build();
  3383. if (helperOption) {
  3384. var col = dateToCell(startDate).col;
  3385. if (col >= 0 && col < colCnt) { // only works when times are on same day
  3386. var rect = coordinateGrid.rect(0, col, 0, col, slotContainer); // only for horizontal coords
  3387. var top = computeDateTop(startDate, startDate);
  3388. var bottom = computeDateTop(endDate, startDate);
  3389. if (bottom > top) { // protect against selections that are entirely before or after visible range
  3390. rect.top = top;
  3391. rect.height = bottom - top;
  3392. rect.left += 2;
  3393. rect.width -= 5;
  3394. if ($.isFunction(helperOption)) {
  3395. var helperRes = helperOption(startDate, endDate);
  3396. if (helperRes) {
  3397. rect.position = 'absolute';
  3398. selectionHelper = $(helperRes)
  3399. .css(rect)
  3400. .appendTo(slotContainer);
  3401. }
  3402. }else{
  3403. rect.isStart = true; // conside rect a "seg" now
  3404. rect.isEnd = true; //
  3405. selectionHelper = $(slotSegHtml(
  3406. {
  3407. title: '',
  3408. start: startDate,
  3409. end: endDate,
  3410. className: ['fc-select-helper'],
  3411. editable: false
  3412. },
  3413. rect
  3414. ));
  3415. selectionHelper.css('opacity', opt('dragOpacity'));
  3416. }
  3417. if (selectionHelper) {
  3418. slotBind(selectionHelper);
  3419. slotContainer.append(selectionHelper);
  3420. setOuterWidth(selectionHelper, rect.width, true); // needs to be after appended
  3421. setOuterHeight(selectionHelper, rect.height, true);
  3422. }
  3423. }
  3424. }
  3425. }else{
  3426. renderSlotOverlay(startDate, endDate);
  3427. }
  3428. }
  3429. function clearSelection() {
  3430. clearOverlays();
  3431. if (selectionHelper) {
  3432. selectionHelper.remove();
  3433. selectionHelper = null;
  3434. }
  3435. }
  3436. function slotSelectionMousedown(ev) {
  3437. if (ev.which == 1 && opt('selectable')) { // ev.which==1 means left mouse button
  3438. unselect(ev);
  3439. var dates;
  3440. hoverListener.start(function(cell, origCell) {
  3441. clearSelection();
  3442. if (cell && cell.col == origCell.col && !getIsCellAllDay(cell)) {
  3443. var d1 = realCellToDate(origCell);
  3444. var d2 = realCellToDate(cell);
  3445. dates = [
  3446. d1,
  3447. d1.clone().add(snapDuration), // calculate minutes depending on selection slot minutes
  3448. d2,
  3449. d2.clone().add(snapDuration)
  3450. ].sort(dateCompare);
  3451. renderSlotSelection(dates[0], dates[3]);
  3452. }else{
  3453. dates = null;
  3454. }
  3455. }, ev);
  3456. $(document).one('mouseup', function(ev) {
  3457. hoverListener.stop();
  3458. if (dates) {
  3459. if (+dates[0] == +dates[1]) {
  3460. reportDayClick(dates[0], ev);
  3461. }
  3462. reportSelection(dates[0], dates[3], ev);
  3463. }
  3464. });
  3465. }
  3466. }
  3467. function reportDayClick(date, ev) {
  3468. trigger('dayClick', dayBodyCells[dateToCell(date).col], date, ev);
  3469. }
  3470. /* External Dragging
  3471. --------------------------------------------------------------------------------*/
  3472. function dragStart(_dragElement, ev, ui) {
  3473. hoverListener.start(function(cell) {
  3474. clearOverlays();
  3475. if (cell) {
  3476. var d1 = realCellToDate(cell);
  3477. var d2 = d1.clone();
  3478. if (d1.hasTime()) {
  3479. d2.add(calendar.defaultTimedEventDuration);
  3480. renderSlotOverlay(d1, d2);
  3481. }
  3482. else {
  3483. d2.add(calendar.defaultAllDayEventDuration);
  3484. renderDayOverlay(d1, d2);
  3485. }
  3486. }
  3487. }, ev);
  3488. }
  3489. function dragStop(_dragElement, ev, ui) {
  3490. var cell = hoverListener.stop();
  3491. clearOverlays();
  3492. if (cell) {
  3493. trigger(
  3494. 'drop',
  3495. _dragElement,
  3496. realCellToDate(cell),
  3497. ev,
  3498. ui
  3499. );
  3500. }
  3501. }
  3502. }
  3503. ;;
  3504. function AgendaEventRenderer() {
  3505. var t = this;
  3506. // exports
  3507. t.renderEvents = renderEvents;
  3508. t.clearEvents = clearEvents;
  3509. t.slotSegHtml = slotSegHtml;
  3510. // imports
  3511. DayEventRenderer.call(t);
  3512. var opt = t.opt;
  3513. var trigger = t.trigger;
  3514. var isEventDraggable = t.isEventDraggable;
  3515. var isEventResizable = t.isEventResizable;
  3516. var eventElementHandlers = t.eventElementHandlers;
  3517. var setHeight = t.setHeight;
  3518. var getDaySegmentContainer = t.getDaySegmentContainer;
  3519. var getSlotSegmentContainer = t.getSlotSegmentContainer;
  3520. var getHoverListener = t.getHoverListener;
  3521. var computeDateTop = t.computeDateTop;
  3522. var getIsCellAllDay = t.getIsCellAllDay;
  3523. var colContentLeft = t.colContentLeft;
  3524. var colContentRight = t.colContentRight;
  3525. var cellToDate = t.cellToDate;
  3526. var getColCnt = t.getColCnt;
  3527. var getColWidth = t.getColWidth;
  3528. var getSnapHeight = t.getSnapHeight;
  3529. var getSnapDuration = t.getSnapDuration;
  3530. var getSlotHeight = t.getSlotHeight;
  3531. var getSlotDuration = t.getSlotDuration;
  3532. var getSlotContainer = t.getSlotContainer;
  3533. var reportEventElement = t.reportEventElement;
  3534. var showEvents = t.showEvents;
  3535. var hideEvents = t.hideEvents;
  3536. var eventDrop = t.eventDrop;
  3537. var eventResize = t.eventResize;
  3538. var renderDayOverlay = t.renderDayOverlay;
  3539. var clearOverlays = t.clearOverlays;
  3540. var renderDayEvents = t.renderDayEvents;
  3541. var getMinTime = t.getMinTime;
  3542. var getMaxTime = t.getMaxTime;
  3543. var calendar = t.calendar;
  3544. var formatDate = calendar.formatDate;
  3545. var getEventEnd = calendar.getEventEnd;
  3546. // overrides
  3547. t.draggableDayEvent = draggableDayEvent;
  3548. /* Rendering
  3549. ----------------------------------------------------------------------------*/
  3550. function renderEvents(events, modifiedEventId) {
  3551. var i, len=events.length,
  3552. dayEvents=[],
  3553. slotEvents=[];
  3554. for (i=0; i<len; i++) {
  3555. if (events[i].allDay) {
  3556. dayEvents.push(events[i]);
  3557. }else{
  3558. slotEvents.push(events[i]);
  3559. }
  3560. }
  3561. if (opt('allDaySlot')) {
  3562. renderDayEvents(dayEvents, modifiedEventId);
  3563. setHeight(); // no params means set to viewHeight
  3564. }
  3565. renderSlotSegs(compileSlotSegs(slotEvents), modifiedEventId);
  3566. }
  3567. function clearEvents() {
  3568. getDaySegmentContainer().empty();
  3569. getSlotSegmentContainer().empty();
  3570. }
  3571. function compileSlotSegs(events) {
  3572. var colCnt = getColCnt(),
  3573. minTime = getMinTime(),
  3574. maxTime = getMaxTime(),
  3575. cellDate,
  3576. i,
  3577. j, seg,
  3578. colSegs,
  3579. segs = [];
  3580. for (i=0; i<colCnt; i++) {
  3581. cellDate = cellToDate(0, i);
  3582. colSegs = sliceSegs(
  3583. events,
  3584. cellDate.clone().time(minTime),
  3585. cellDate.clone().time(maxTime)
  3586. );
  3587. colSegs = placeSlotSegs(colSegs); // returns a new order
  3588. for (j=0; j<colSegs.length; j++) {
  3589. seg = colSegs[j];
  3590. seg.col = i;
  3591. segs.push(seg);
  3592. }
  3593. }
  3594. return segs;
  3595. }
  3596. function sliceSegs(events, rangeStart, rangeEnd) {
  3597. // normalize, because all dates will be compared w/o zones
  3598. rangeStart = rangeStart.clone().stripZone();
  3599. rangeEnd = rangeEnd.clone().stripZone();
  3600. var segs = [],
  3601. i, len=events.length, event,
  3602. eventStart, eventEnd,
  3603. segStart, segEnd,
  3604. isStart, isEnd;
  3605. for (i=0; i<len; i++) {
  3606. event = events[i];
  3607. // get dates, make copies, then strip zone to normalize
  3608. eventStart = event.start.clone().stripZone();
  3609. eventEnd = getEventEnd(event).stripZone();
  3610. if (eventEnd > rangeStart && eventStart < rangeEnd) {
  3611. if (eventStart < rangeStart) {
  3612. segStart = rangeStart.clone();
  3613. isStart = false;
  3614. }
  3615. else {
  3616. segStart = eventStart;
  3617. isStart = true;
  3618. }
  3619. if (eventEnd > rangeEnd) {
  3620. segEnd = rangeEnd.clone();
  3621. isEnd = false;
  3622. }
  3623. else {
  3624. segEnd = eventEnd;
  3625. isEnd = true;
  3626. }
  3627. segs.push({
  3628. event: event,
  3629. start: segStart,
  3630. end: segEnd,
  3631. isStart: isStart,
  3632. isEnd: isEnd
  3633. });
  3634. }
  3635. }
  3636. return segs.sort(compareSlotSegs);
  3637. }
  3638. // renders events in the 'time slots' at the bottom
  3639. // TODO: when we refactor this, when user returns `false` eventRender, don't have empty space
  3640. // TODO: refactor will include using pixels to detect collisions instead of dates (handy for seg cmp)
  3641. function renderSlotSegs(segs, modifiedEventId) {
  3642. var i, segCnt=segs.length, seg,
  3643. event,
  3644. top,
  3645. bottom,
  3646. columnLeft,
  3647. columnRight,
  3648. columnWidth,
  3649. width,
  3650. left,
  3651. right,
  3652. html = '',
  3653. eventElements,
  3654. eventElement,
  3655. triggerRes,
  3656. titleElement,
  3657. height,
  3658. slotSegmentContainer = getSlotSegmentContainer(),
  3659. isRTL = opt('isRTL');
  3660. // calculate position/dimensions, create html
  3661. for (i=0; i<segCnt; i++) {
  3662. seg = segs[i];
  3663. event = seg.event;
  3664. top = computeDateTop(seg.start, seg.start);
  3665. bottom = computeDateTop(seg.end, seg.start);
  3666. columnLeft = colContentLeft(seg.col);
  3667. columnRight = colContentRight(seg.col);
  3668. columnWidth = columnRight - columnLeft;
  3669. // shave off space on right near scrollbars (2.5%)
  3670. // TODO: move this to CSS somehow
  3671. columnRight -= columnWidth * .025;
  3672. columnWidth = columnRight - columnLeft;
  3673. width = columnWidth * (seg.forwardCoord - seg.backwardCoord);
  3674. if (opt('slotEventOverlap')) {
  3675. // double the width while making sure resize handle is visible
  3676. // (assumed to be 20px wide)
  3677. width = Math.max(
  3678. (width - (20/2)) * 2,
  3679. width // narrow columns will want to make the segment smaller than
  3680. // the natural width. don't allow it
  3681. );
  3682. }
  3683. if (isRTL) {
  3684. right = columnRight - seg.backwardCoord * columnWidth;
  3685. left = right - width;
  3686. }
  3687. else {
  3688. left = columnLeft + seg.backwardCoord * columnWidth;
  3689. right = left + width;
  3690. }
  3691. // make sure horizontal coordinates are in bounds
  3692. left = Math.max(left, columnLeft);
  3693. right = Math.min(right, columnRight);
  3694. width = right - left;
  3695. seg.top = top;
  3696. seg.left = left;
  3697. seg.outerWidth = width;
  3698. seg.outerHeight = bottom - top;
  3699. html += slotSegHtml(event, seg);
  3700. }
  3701. slotSegmentContainer[0].innerHTML = html; // faster than html()
  3702. eventElements = slotSegmentContainer.children();
  3703. // retrieve elements, run through eventRender callback, bind event handlers
  3704. for (i=0; i<segCnt; i++) {
  3705. seg = segs[i];
  3706. event = seg.event;
  3707. eventElement = $(eventElements[i]); // faster than eq()
  3708. triggerRes = trigger('eventRender', event, event, eventElement);
  3709. if (triggerRes === false) {
  3710. eventElement.remove();
  3711. }else{
  3712. if (triggerRes && triggerRes !== true) {
  3713. eventElement.remove();
  3714. eventElement = $(triggerRes)
  3715. .css({
  3716. position: 'absolute',
  3717. top: seg.top,
  3718. left: seg.left
  3719. })
  3720. .appendTo(slotSegmentContainer);
  3721. }
  3722. seg.element = eventElement;
  3723. if (event._id === modifiedEventId) {
  3724. bindSlotSeg(event, eventElement, seg);
  3725. }else{
  3726. eventElement[0]._fci = i; // for lazySegBind
  3727. }
  3728. reportEventElement(event, eventElement);
  3729. }
  3730. }
  3731. lazySegBind(slotSegmentContainer, segs, bindSlotSeg);
  3732. // record event sides and title positions
  3733. for (i=0; i<segCnt; i++) {
  3734. seg = segs[i];
  3735. if ((eventElement = seg.element)) {
  3736. seg.vsides = vsides(eventElement, true);
  3737. seg.hsides = hsides(eventElement, true);
  3738. titleElement = eventElement.find('.fc-event-title');
  3739. if (titleElement.length) {
  3740. seg.contentTop = titleElement[0].offsetTop;
  3741. }
  3742. }
  3743. }
  3744. // set all positions/dimensions at once
  3745. for (i=0; i<segCnt; i++) {
  3746. seg = segs[i];
  3747. if ((eventElement = seg.element)) {
  3748. eventElement[0].style.width = Math.max(0, seg.outerWidth - seg.hsides) + 'px';
  3749. height = Math.max(0, seg.outerHeight - seg.vsides);
  3750. eventElement[0].style.height = height + 'px';
  3751. event = seg.event;
  3752. if (seg.contentTop !== undefined && height - seg.contentTop < 10) {
  3753. // not enough room for title, put it in the time (TODO: maybe make both display:inline instead)
  3754. eventElement.find('div.fc-event-time')
  3755. .text(
  3756. formatDate(event.start, opt('timeFormat')) + ' - ' + event.title
  3757. );
  3758. eventElement.find('div.fc-event-title')
  3759. .remove();
  3760. }
  3761. trigger('eventAfterRender', event, event, eventElement);
  3762. }
  3763. }
  3764. }
  3765. function slotSegHtml(event, seg) {
  3766. var html = "<";
  3767. var url = event.url;
  3768. var skinCss = getSkinCss(event, opt);
  3769. var classes = ['fc-event', 'fc-event-vert'];
  3770. if (isEventDraggable(event)) {
  3771. classes.push('fc-event-draggable');
  3772. }
  3773. if (seg.isStart) {
  3774. classes.push('fc-event-start');
  3775. }
  3776. if (seg.isEnd) {
  3777. classes.push('fc-event-end');
  3778. }
  3779. classes = classes.concat(event.className);
  3780. if (event.source) {
  3781. classes = classes.concat(event.source.className || []);
  3782. }
  3783. if (url) {
  3784. html += "a href='" + htmlEscape(event.url) + "'";
  3785. }else{
  3786. html += "div";
  3787. }
  3788. html +=
  3789. " class='" + classes.join(' ') + "'" +
  3790. " style=" +
  3791. "'" +
  3792. "position:absolute;" +
  3793. "top:" + seg.top + "px;" +
  3794. "left:" + seg.left + "px;" +
  3795. skinCss +
  3796. "'" +
  3797. ">" +
  3798. "<div class='fc-event-inner'>" +
  3799. "<div class='fc-event-time'>" +
  3800. htmlEscape(t.getEventTimeText(event)) +
  3801. "</div>" +
  3802. "<div class='fc-event-title'>" +
  3803. htmlEscape(event.title || '') +
  3804. "</div>" +
  3805. "</div>" +
  3806. "<div class='fc-event-bg'></div>";
  3807. if (seg.isEnd && isEventResizable(event)) {
  3808. html +=
  3809. "<div class='ui-resizable-handle ui-resizable-s'>=</div>";
  3810. }
  3811. html +=
  3812. "</" + (url ? "a" : "div") + ">";
  3813. return html;
  3814. }
  3815. function bindSlotSeg(event, eventElement, seg) {
  3816. var timeElement = eventElement.find('div.fc-event-time');
  3817. if (isEventDraggable(event)) {
  3818. draggableSlotEvent(event, eventElement, timeElement);
  3819. }
  3820. if (seg.isEnd && isEventResizable(event)) {
  3821. resizableSlotEvent(event, eventElement, timeElement);
  3822. }
  3823. eventElementHandlers(event, eventElement);
  3824. }
  3825. /* Dragging
  3826. -----------------------------------------------------------------------------------*/
  3827. // when event starts out FULL-DAY
  3828. // overrides DayEventRenderer's version because it needs to account for dragging elements
  3829. // to and from the slot area.
  3830. function draggableDayEvent(event, eventElement, seg) {
  3831. var isStart = seg.isStart;
  3832. var origWidth;
  3833. var revert;
  3834. var allDay = true;
  3835. var dayDelta;
  3836. var hoverListener = getHoverListener();
  3837. var colWidth = getColWidth();
  3838. var minTime = getMinTime();
  3839. var slotDuration = getSlotDuration();
  3840. var slotHeight = getSlotHeight();
  3841. var snapDuration = getSnapDuration();
  3842. var snapHeight = getSnapHeight();
  3843. eventElement.draggable({
  3844. opacity: opt('dragOpacity', 'month'), // use whatever the month view was using
  3845. revertDuration: opt('dragRevertDuration'),
  3846. start: function(ev, ui) {
  3847. trigger('eventDragStart', eventElement[0], event, ev, ui);
  3848. hideEvents(event, eventElement);
  3849. origWidth = eventElement.width();
  3850. hoverListener.start(function(cell, origCell) {
  3851. clearOverlays();
  3852. if (cell) {
  3853. revert = false;
  3854. var origDate = cellToDate(0, origCell.col);
  3855. var date = cellToDate(0, cell.col);
  3856. dayDelta = date.diff(origDate, 'days');
  3857. if (!cell.row) { // on full-days
  3858. renderDayOverlay(
  3859. event.start.clone().add('days', dayDelta),
  3860. getEventEnd(event).add('days', dayDelta)
  3861. );
  3862. resetElement();
  3863. }
  3864. else { // mouse is over bottom slots
  3865. if (isStart) {
  3866. if (allDay) {
  3867. // convert event to temporary slot-event
  3868. eventElement.width(colWidth - 10); // don't use entire width
  3869. setOuterHeight(eventElement, calendar.defaultTimedEventDuration / slotDuration * slotHeight); // the default height
  3870. eventElement.draggable('option', 'grid', [ colWidth, 1 ]);
  3871. allDay = false;
  3872. }
  3873. }
  3874. else {
  3875. revert = true;
  3876. }
  3877. }
  3878. revert = revert || (allDay && !dayDelta);
  3879. }
  3880. else {
  3881. resetElement();
  3882. revert = true;
  3883. }
  3884. eventElement.draggable('option', 'revert', revert);
  3885. }, ev, 'drag');
  3886. },
  3887. stop: function(ev, ui) {
  3888. hoverListener.stop();
  3889. clearOverlays();
  3890. trigger('eventDragStop', eventElement[0], event, ev, ui);
  3891. if (revert) { // hasn't moved or is out of bounds (draggable has already reverted)
  3892. resetElement();
  3893. eventElement.css('filter', ''); // clear IE opacity side-effects
  3894. showEvents(event, eventElement);
  3895. }
  3896. else { // changed!
  3897. var eventStart = event.start.clone().add('days', dayDelta); // already assumed to have a stripped time
  3898. var snapTime;
  3899. var snapIndex;
  3900. if (!allDay) {
  3901. snapIndex = Math.round((eventElement.offset().top - getSlotContainer().offset().top) / snapHeight); // why not use ui.offset.top?
  3902. snapTime = moment.duration(minTime + snapIndex * snapDuration);
  3903. eventStart = calendar.rezoneDate(eventStart.clone().time(snapTime));
  3904. }
  3905. eventDrop(
  3906. eventElement[0],
  3907. event,
  3908. eventStart,
  3909. ev,
  3910. ui
  3911. );
  3912. }
  3913. }
  3914. });
  3915. function resetElement() {
  3916. if (!allDay) {
  3917. eventElement
  3918. .width(origWidth)
  3919. .height('')
  3920. .draggable('option', 'grid', null);
  3921. allDay = true;
  3922. }
  3923. }
  3924. }
  3925. // when event starts out IN TIMESLOTS
  3926. function draggableSlotEvent(event, eventElement, timeElement) {
  3927. var coordinateGrid = t.getCoordinateGrid();
  3928. var colCnt = getColCnt();
  3929. var colWidth = getColWidth();
  3930. var snapHeight = getSnapHeight();
  3931. var snapDuration = getSnapDuration();
  3932. // states
  3933. var origPosition; // original position of the element, not the mouse
  3934. var origCell;
  3935. var isInBounds, prevIsInBounds;
  3936. var isAllDay, prevIsAllDay;
  3937. var colDelta, prevColDelta;
  3938. var dayDelta; // derived from colDelta
  3939. var snapDelta, prevSnapDelta; // the number of snaps away from the original position
  3940. // newly computed
  3941. var eventStart, eventEnd;
  3942. eventElement.draggable({
  3943. scroll: false,
  3944. grid: [ colWidth, snapHeight ],
  3945. axis: colCnt==1 ? 'y' : false,
  3946. opacity: opt('dragOpacity'),
  3947. revertDuration: opt('dragRevertDuration'),
  3948. start: function(ev, ui) {
  3949. trigger('eventDragStart', eventElement[0], event, ev, ui);
  3950. hideEvents(event, eventElement);
  3951. coordinateGrid.build();
  3952. // initialize states
  3953. origPosition = eventElement.position();
  3954. origCell = coordinateGrid.cell(ev.pageX, ev.pageY);
  3955. isInBounds = prevIsInBounds = true;
  3956. isAllDay = prevIsAllDay = getIsCellAllDay(origCell);
  3957. colDelta = prevColDelta = 0;
  3958. dayDelta = 0;
  3959. snapDelta = prevSnapDelta = 0;
  3960. eventStart = null;
  3961. eventEnd = null;
  3962. },
  3963. drag: function(ev, ui) {
  3964. // NOTE: this `cell` value is only useful for determining in-bounds and all-day.
  3965. // Bad for anything else due to the discrepancy between the mouse position and the
  3966. // element position while snapping. (problem revealed in PR #55)
  3967. //
  3968. // PS- the problem exists for draggableDayEvent() when dragging an all-day event to a slot event.
  3969. // We should overhaul the dragging system and stop relying on jQuery UI.
  3970. var cell = coordinateGrid.cell(ev.pageX, ev.pageY);
  3971. // update states
  3972. isInBounds = !!cell;
  3973. if (isInBounds) {
  3974. isAllDay = getIsCellAllDay(cell);
  3975. // calculate column delta
  3976. colDelta = Math.round((ui.position.left - origPosition.left) / colWidth);
  3977. if (colDelta != prevColDelta) {
  3978. // calculate the day delta based off of the original clicked column and the column delta
  3979. var origDate = cellToDate(0, origCell.col);
  3980. var col = origCell.col + colDelta;
  3981. col = Math.max(0, col);
  3982. col = Math.min(colCnt-1, col);
  3983. var date = cellToDate(0, col);
  3984. dayDelta = date.diff(origDate, 'days');
  3985. }
  3986. // calculate minute delta (only if over slots)
  3987. if (!isAllDay) {
  3988. snapDelta = Math.round((ui.position.top - origPosition.top) / snapHeight);
  3989. }
  3990. }
  3991. // any state changes?
  3992. if (
  3993. isInBounds != prevIsInBounds ||
  3994. isAllDay != prevIsAllDay ||
  3995. colDelta != prevColDelta ||
  3996. snapDelta != prevSnapDelta
  3997. ) {
  3998. // compute new dates
  3999. if (isAllDay) {
  4000. eventStart = event.start.clone().stripTime().add('days', dayDelta);
  4001. eventEnd = eventStart.clone().add(calendar.defaultAllDayEventDuration);
  4002. }
  4003. else {
  4004. eventStart = event.start.clone().add(snapDelta * snapDuration).add('days', dayDelta);
  4005. eventEnd = getEventEnd(event).add(snapDelta * snapDuration).add('days', dayDelta);
  4006. }
  4007. updateUI();
  4008. // update previous states for next time
  4009. prevIsInBounds = isInBounds;
  4010. prevIsAllDay = isAllDay;
  4011. prevColDelta = colDelta;
  4012. prevSnapDelta = snapDelta;
  4013. }
  4014. // if out-of-bounds, revert when done, and vice versa.
  4015. eventElement.draggable('option', 'revert', !isInBounds);
  4016. },
  4017. stop: function(ev, ui) {
  4018. clearOverlays();
  4019. trigger('eventDragStop', eventElement[0], event, ev, ui);
  4020. if (isInBounds && (isAllDay || dayDelta || snapDelta)) { // changed!
  4021. eventDrop(
  4022. eventElement[0],
  4023. event,
  4024. eventStart,
  4025. ev,
  4026. ui
  4027. );
  4028. }
  4029. else { // either no change or out-of-bounds (draggable has already reverted)
  4030. // reset states for next time, and for updateUI()
  4031. isInBounds = true;
  4032. isAllDay = false;
  4033. colDelta = 0;
  4034. dayDelta = 0;
  4035. snapDelta = 0;
  4036. updateUI();
  4037. eventElement.css('filter', ''); // clear IE opacity side-effects
  4038. // sometimes fast drags make event revert to wrong position, so reset.
  4039. // also, if we dragged the element out of the area because of snapping,
  4040. // but the *mouse* is still in bounds, we need to reset the position.
  4041. eventElement.css(origPosition);
  4042. showEvents(event, eventElement);
  4043. }
  4044. }
  4045. });
  4046. function updateUI() {
  4047. clearOverlays();
  4048. if (isInBounds) {
  4049. if (isAllDay) {
  4050. timeElement.hide();
  4051. eventElement.draggable('option', 'grid', null); // disable grid snapping
  4052. renderDayOverlay(eventStart, eventEnd);
  4053. }
  4054. else {
  4055. updateTimeText();
  4056. timeElement.css('display', ''); // show() was causing display=inline
  4057. eventElement.draggable('option', 'grid', [colWidth, snapHeight]); // re-enable grid snapping
  4058. }
  4059. }
  4060. }
  4061. function updateTimeText() {
  4062. if (eventStart) { // must of had a state change
  4063. timeElement.text(
  4064. t.getEventTimeText(eventStart, event.end ? eventEnd : null)
  4065. // ^
  4066. // only display the new end if there was an old end
  4067. );
  4068. }
  4069. }
  4070. }
  4071. /* Resizing
  4072. --------------------------------------------------------------------------------------*/
  4073. function resizableSlotEvent(event, eventElement, timeElement) {
  4074. var snapDelta, prevSnapDelta;
  4075. var snapHeight = getSnapHeight();
  4076. var snapDuration = getSnapDuration();
  4077. var eventEnd;
  4078. eventElement.resizable({
  4079. handles: {
  4080. s: '.ui-resizable-handle'
  4081. },
  4082. grid: snapHeight,
  4083. start: function(ev, ui) {
  4084. snapDelta = prevSnapDelta = 0;
  4085. hideEvents(event, eventElement);
  4086. trigger('eventResizeStart', eventElement[0], event, ev, ui);
  4087. },
  4088. resize: function(ev, ui) {
  4089. // don't rely on ui.size.height, doesn't take grid into account
  4090. snapDelta = Math.round((Math.max(snapHeight, eventElement.height()) - ui.originalSize.height) / snapHeight);
  4091. if (snapDelta != prevSnapDelta) {
  4092. eventEnd = getEventEnd(event).add(snapDuration * snapDelta);
  4093. var text;
  4094. if (snapDelta) { // has there been a change?
  4095. text = t.getEventTimeText(event.start, eventEnd);
  4096. }
  4097. else {
  4098. text = t.getEventTimeText(event); // the original time text
  4099. }
  4100. timeElement.text(text);
  4101. prevSnapDelta = snapDelta;
  4102. }
  4103. },
  4104. stop: function(ev, ui) {
  4105. trigger('eventResizeStop', eventElement[0], event, ev, ui);
  4106. if (snapDelta) {
  4107. eventResize(
  4108. eventElement[0],
  4109. event,
  4110. eventEnd,
  4111. ev,
  4112. ui
  4113. );
  4114. }
  4115. else {
  4116. showEvents(event, eventElement);
  4117. // BUG: if event was really short, need to put title back in span
  4118. }
  4119. }
  4120. });
  4121. }
  4122. }
  4123. /* Agenda Event Segment Utilities
  4124. -----------------------------------------------------------------------------*/
  4125. // Sets the seg.backwardCoord and seg.forwardCoord on each segment and returns a new
  4126. // list in the order they should be placed into the DOM (an implicit z-index).
  4127. function placeSlotSegs(segs) {
  4128. var levels = buildSlotSegLevels(segs);
  4129. var level0 = levels[0];
  4130. var i;
  4131. computeForwardSlotSegs(levels);
  4132. if (level0) {
  4133. for (i=0; i<level0.length; i++) {
  4134. computeSlotSegPressures(level0[i]);
  4135. }
  4136. for (i=0; i<level0.length; i++) {
  4137. computeSlotSegCoords(level0[i], 0, 0);
  4138. }
  4139. }
  4140. return flattenSlotSegLevels(levels);
  4141. }
  4142. // Builds an array of segments "levels". The first level will be the leftmost tier of segments
  4143. // if the calendar is left-to-right, or the rightmost if the calendar is right-to-left.
  4144. function buildSlotSegLevels(segs) {
  4145. var levels = [];
  4146. var i, seg;
  4147. var j;
  4148. for (i=0; i<segs.length; i++) {
  4149. seg = segs[i];
  4150. // go through all the levels and stop on the first level where there are no collisions
  4151. for (j=0; j<levels.length; j++) {
  4152. if (!computeSlotSegCollisions(seg, levels[j]).length) {
  4153. break;
  4154. }
  4155. }
  4156. (levels[j] || (levels[j] = [])).push(seg);
  4157. }
  4158. return levels;
  4159. }
  4160. // For every segment, figure out the other segments that are in subsequent
  4161. // levels that also occupy the same vertical space. Accumulate in seg.forwardSegs
  4162. function computeForwardSlotSegs(levels) {
  4163. var i, level;
  4164. var j, seg;
  4165. var k;
  4166. for (i=0; i<levels.length; i++) {
  4167. level = levels[i];
  4168. for (j=0; j<level.length; j++) {
  4169. seg = level[j];
  4170. seg.forwardSegs = [];
  4171. for (k=i+1; k<levels.length; k++) {
  4172. computeSlotSegCollisions(seg, levels[k], seg.forwardSegs);
  4173. }
  4174. }
  4175. }
  4176. }
  4177. // Figure out which path forward (via seg.forwardSegs) results in the longest path until
  4178. // the furthest edge is reached. The number of segments in this path will be seg.forwardPressure
  4179. function computeSlotSegPressures(seg) {
  4180. var forwardSegs = seg.forwardSegs;
  4181. var forwardPressure = 0;
  4182. var i, forwardSeg;
  4183. if (seg.forwardPressure === undefined) { // not already computed
  4184. for (i=0; i<forwardSegs.length; i++) {
  4185. forwardSeg = forwardSegs[i];
  4186. // figure out the child's maximum forward path
  4187. computeSlotSegPressures(forwardSeg);
  4188. // either use the existing maximum, or use the child's forward pressure
  4189. // plus one (for the forwardSeg itself)
  4190. forwardPressure = Math.max(
  4191. forwardPressure,
  4192. 1 + forwardSeg.forwardPressure
  4193. );
  4194. }
  4195. seg.forwardPressure = forwardPressure;
  4196. }
  4197. }
  4198. // Calculate seg.forwardCoord and seg.backwardCoord for the segment, where both values range
  4199. // from 0 to 1. If the calendar is left-to-right, the seg.backwardCoord maps to "left" and
  4200. // seg.forwardCoord maps to "right" (via percentage). Vice-versa if the calendar is right-to-left.
  4201. //
  4202. // The segment might be part of a "series", which means consecutive segments with the same pressure
  4203. // who's width is unknown until an edge has been hit. `seriesBackwardPressure` is the number of
  4204. // segments behind this one in the current series, and `seriesBackwardCoord` is the starting
  4205. // coordinate of the first segment in the series.
  4206. function computeSlotSegCoords(seg, seriesBackwardPressure, seriesBackwardCoord) {
  4207. var forwardSegs = seg.forwardSegs;
  4208. var i;
  4209. if (seg.forwardCoord === undefined) { // not already computed
  4210. if (!forwardSegs.length) {
  4211. // if there are no forward segments, this segment should butt up against the edge
  4212. seg.forwardCoord = 1;
  4213. }
  4214. else {
  4215. // sort highest pressure first
  4216. forwardSegs.sort(compareForwardSlotSegs);
  4217. // this segment's forwardCoord will be calculated from the backwardCoord of the
  4218. // highest-pressure forward segment.
  4219. computeSlotSegCoords(forwardSegs[0], seriesBackwardPressure + 1, seriesBackwardCoord);
  4220. seg.forwardCoord = forwardSegs[0].backwardCoord;
  4221. }
  4222. // calculate the backwardCoord from the forwardCoord. consider the series
  4223. seg.backwardCoord = seg.forwardCoord -
  4224. (seg.forwardCoord - seriesBackwardCoord) / // available width for series
  4225. (seriesBackwardPressure + 1); // # of segments in the series
  4226. // use this segment's coordinates to computed the coordinates of the less-pressurized
  4227. // forward segments
  4228. for (i=0; i<forwardSegs.length; i++) {
  4229. computeSlotSegCoords(forwardSegs[i], 0, seg.forwardCoord);
  4230. }
  4231. }
  4232. }
  4233. // Outputs a flat array of segments, from lowest to highest level
  4234. function flattenSlotSegLevels(levels) {
  4235. var segs = [];
  4236. var i, level;
  4237. var j;
  4238. for (i=0; i<levels.length; i++) {
  4239. level = levels[i];
  4240. for (j=0; j<level.length; j++) {
  4241. segs.push(level[j]);
  4242. }
  4243. }
  4244. return segs;
  4245. }
  4246. // Find all the segments in `otherSegs` that vertically collide with `seg`.
  4247. // Append into an optionally-supplied `results` array and return.
  4248. function computeSlotSegCollisions(seg, otherSegs, results) {
  4249. results = results || [];
  4250. for (var i=0; i<otherSegs.length; i++) {
  4251. if (isSlotSegCollision(seg, otherSegs[i])) {
  4252. results.push(otherSegs[i]);
  4253. }
  4254. }
  4255. return results;
  4256. }
  4257. // Do these segments occupy the same vertical space?
  4258. function isSlotSegCollision(seg1, seg2) {
  4259. return seg1.end > seg2.start && seg1.start < seg2.end;
  4260. }
  4261. // A cmp function for determining which forward segment to rely on more when computing coordinates.
  4262. function compareForwardSlotSegs(seg1, seg2) {
  4263. // put higher-pressure first
  4264. return seg2.forwardPressure - seg1.forwardPressure ||
  4265. // put segments that are closer to initial edge first (and favor ones with no coords yet)
  4266. (seg1.backwardCoord || 0) - (seg2.backwardCoord || 0) ||
  4267. // do normal sorting...
  4268. compareSlotSegs(seg1, seg2);
  4269. }
  4270. // A cmp function for determining which segment should be closer to the initial edge
  4271. // (the left edge on a left-to-right calendar).
  4272. function compareSlotSegs(seg1, seg2) {
  4273. return seg1.start - seg2.start || // earlier start time goes first
  4274. (seg2.end - seg2.start) - (seg1.end - seg1.start) || // tie? longer-duration goes first
  4275. (seg1.event.title || '').localeCompare(seg2.event.title); // tie? alphabetically by title
  4276. }
  4277. ;;
  4278. function View(element, calendar, viewName) {
  4279. var t = this;
  4280. // exports
  4281. t.element = element;
  4282. t.calendar = calendar;
  4283. t.name = viewName;
  4284. t.opt = opt;
  4285. t.trigger = trigger;
  4286. t.isEventDraggable = isEventDraggable;
  4287. t.isEventResizable = isEventResizable;
  4288. t.clearEventData = clearEventData;
  4289. t.reportEventElement = reportEventElement;
  4290. t.triggerEventDestroy = triggerEventDestroy;
  4291. t.eventElementHandlers = eventElementHandlers;
  4292. t.showEvents = showEvents;
  4293. t.hideEvents = hideEvents;
  4294. t.eventDrop = eventDrop;
  4295. t.eventResize = eventResize;
  4296. // t.start, t.end // moments with ambiguous-time
  4297. // t.intervalStart, t.intervalEnd // moments with ambiguous-time
  4298. // imports
  4299. var reportEventChange = calendar.reportEventChange;
  4300. // locals
  4301. var eventElementsByID = {}; // eventID mapped to array of jQuery elements
  4302. var eventElementCouples = []; // array of objects, { event, element } // TODO: unify with segment system
  4303. var options = calendar.options;
  4304. var nextDayThreshold = moment.duration(options.nextDayThreshold);
  4305. function opt(name, viewNameOverride) {
  4306. var v = options[name];
  4307. if ($.isPlainObject(v) && !isForcedAtomicOption(name)) {
  4308. return smartProperty(v, viewNameOverride || viewName);
  4309. }
  4310. return v;
  4311. }
  4312. function trigger(name, thisObj) {
  4313. return calendar.trigger.apply(
  4314. calendar,
  4315. [name, thisObj || t].concat(Array.prototype.slice.call(arguments, 2), [t])
  4316. );
  4317. }
  4318. /* Event Editable Boolean Calculations
  4319. ------------------------------------------------------------------------------*/
  4320. function isEventDraggable(event) {
  4321. var source = event.source || {};
  4322. return firstDefined(
  4323. event.startEditable,
  4324. source.startEditable,
  4325. opt('eventStartEditable'),
  4326. event.editable,
  4327. source.editable,
  4328. opt('editable')
  4329. );
  4330. }
  4331. function isEventResizable(event) { // but also need to make sure the seg.isEnd == true
  4332. var source = event.source || {};
  4333. return firstDefined(
  4334. event.durationEditable,
  4335. source.durationEditable,
  4336. opt('eventDurationEditable'),
  4337. event.editable,
  4338. source.editable,
  4339. opt('editable')
  4340. );
  4341. }
  4342. /* Event Data
  4343. ------------------------------------------------------------------------------*/
  4344. function clearEventData() {
  4345. eventElementsByID = {};
  4346. eventElementCouples = [];
  4347. }
  4348. /* Event Elements
  4349. ------------------------------------------------------------------------------*/
  4350. // report when view creates an element for an event
  4351. function reportEventElement(event, element) {
  4352. eventElementCouples.push({ event: event, element: element });
  4353. if (eventElementsByID[event._id]) {
  4354. eventElementsByID[event._id].push(element);
  4355. }else{
  4356. eventElementsByID[event._id] = [element];
  4357. }
  4358. }
  4359. function triggerEventDestroy() {
  4360. $.each(eventElementCouples, function(i, couple) {
  4361. t.trigger('eventDestroy', couple.event, couple.event, couple.element);
  4362. });
  4363. }
  4364. // attaches eventClick, eventMouseover, eventMouseout
  4365. function eventElementHandlers(event, eventElement) {
  4366. eventElement
  4367. .click(function(ev) {
  4368. if (!eventElement.hasClass('ui-draggable-dragging') &&
  4369. !eventElement.hasClass('ui-resizable-resizing')) {
  4370. return trigger('eventClick', this, event, ev);
  4371. }
  4372. })
  4373. .hover(
  4374. function(ev) {
  4375. trigger('eventMouseover', this, event, ev);
  4376. },
  4377. function(ev) {
  4378. trigger('eventMouseout', this, event, ev);
  4379. }
  4380. );
  4381. // TODO: don't fire eventMouseover/eventMouseout *while* dragging is occuring (on subject element)
  4382. // TODO: same for resizing
  4383. }
  4384. function showEvents(event, exceptElement) {
  4385. eachEventElement(event, exceptElement, 'show');
  4386. }
  4387. function hideEvents(event, exceptElement) {
  4388. eachEventElement(event, exceptElement, 'hide');
  4389. }
  4390. function eachEventElement(event, exceptElement, funcName) {
  4391. // NOTE: there may be multiple events per ID (repeating events)
  4392. // and multiple segments per event
  4393. var elements = eventElementsByID[event._id],
  4394. i, len = elements.length;
  4395. for (i=0; i<len; i++) {
  4396. if (!exceptElement || elements[i][0] != exceptElement[0]) {
  4397. elements[i][funcName]();
  4398. }
  4399. }
  4400. }
  4401. // Compute the text that should be displayed on an event's element.
  4402. // Based off the settings of the view.
  4403. // Given either an event object or two arguments: a start and end date (which can be null)
  4404. t.getEventTimeText = function(event) {
  4405. var start;
  4406. var end;
  4407. if (arguments.length === 2) {
  4408. start = arguments[0];
  4409. end = arguments[1];
  4410. }
  4411. else {
  4412. start = event.start;
  4413. end = event.end;
  4414. }
  4415. if (end && opt('displayEventEnd')) {
  4416. return calendar.formatRange(start, end, opt('timeFormat'));
  4417. }
  4418. else {
  4419. return calendar.formatDate(start, opt('timeFormat'));
  4420. }
  4421. };
  4422. /* Event Modification Reporting
  4423. ---------------------------------------------------------------------------------*/
  4424. function eventDrop(el, event, newStart, ev, ui) {
  4425. var mutateResult = calendar.mutateEvent(event, newStart, null);
  4426. trigger(
  4427. 'eventDrop',
  4428. el,
  4429. event,
  4430. mutateResult.dateDelta,
  4431. function() {
  4432. mutateResult.undo();
  4433. reportEventChange(event._id);
  4434. },
  4435. ev,
  4436. ui
  4437. );
  4438. reportEventChange(event._id);
  4439. }
  4440. function eventResize(el, event, newEnd, ev, ui) {
  4441. var mutateResult = calendar.mutateEvent(event, null, newEnd);
  4442. trigger(
  4443. 'eventResize',
  4444. el,
  4445. event,
  4446. mutateResult.durationDelta,
  4447. function() {
  4448. mutateResult.undo();
  4449. reportEventChange(event._id);
  4450. },
  4451. ev,
  4452. ui
  4453. );
  4454. reportEventChange(event._id);
  4455. }
  4456. // ====================================================================================================
  4457. // Utilities for day "cells"
  4458. // ====================================================================================================
  4459. // The "basic" views are completely made up of day cells.
  4460. // The "agenda" views have day cells at the top "all day" slot.
  4461. // This was the obvious common place to put these utilities, but they should be abstracted out into
  4462. // a more meaningful class (like DayEventRenderer).
  4463. // ====================================================================================================
  4464. // For determining how a given "cell" translates into a "date":
  4465. //
  4466. // 1. Convert the "cell" (row and column) into a "cell offset" (the # of the cell, cronologically from the first).
  4467. // Keep in mind that column indices are inverted with isRTL. This is taken into account.
  4468. //
  4469. // 2. Convert the "cell offset" to a "day offset" (the # of days since the first visible day in the view).
  4470. //
  4471. // 3. Convert the "day offset" into a "date" (a Moment).
  4472. //
  4473. // The reverse transformation happens when transforming a date into a cell.
  4474. // exports
  4475. t.isHiddenDay = isHiddenDay;
  4476. t.skipHiddenDays = skipHiddenDays;
  4477. t.getCellsPerWeek = getCellsPerWeek;
  4478. t.dateToCell = dateToCell;
  4479. t.dateToDayOffset = dateToDayOffset;
  4480. t.dayOffsetToCellOffset = dayOffsetToCellOffset;
  4481. t.cellOffsetToCell = cellOffsetToCell;
  4482. t.cellToDate = cellToDate;
  4483. t.cellToCellOffset = cellToCellOffset;
  4484. t.cellOffsetToDayOffset = cellOffsetToDayOffset;
  4485. t.dayOffsetToDate = dayOffsetToDate;
  4486. t.rangeToSegments = rangeToSegments;
  4487. // internals
  4488. var hiddenDays = opt('hiddenDays') || []; // array of day-of-week indices that are hidden
  4489. var isHiddenDayHash = []; // is the day-of-week hidden? (hash with day-of-week-index -> bool)
  4490. var cellsPerWeek;
  4491. var dayToCellMap = []; // hash from dayIndex -> cellIndex, for one week
  4492. var cellToDayMap = []; // hash from cellIndex -> dayIndex, for one week
  4493. var isRTL = opt('isRTL');
  4494. // initialize important internal variables
  4495. (function() {
  4496. if (opt('weekends') === false) {
  4497. hiddenDays.push(0, 6); // 0=sunday, 6=saturday
  4498. }
  4499. // Loop through a hypothetical week and determine which
  4500. // days-of-week are hidden. Record in both hashes (one is the reverse of the other).
  4501. for (var dayIndex=0, cellIndex=0; dayIndex<7; dayIndex++) {
  4502. dayToCellMap[dayIndex] = cellIndex;
  4503. isHiddenDayHash[dayIndex] = $.inArray(dayIndex, hiddenDays) != -1;
  4504. if (!isHiddenDayHash[dayIndex]) {
  4505. cellToDayMap[cellIndex] = dayIndex;
  4506. cellIndex++;
  4507. }
  4508. }
  4509. cellsPerWeek = cellIndex;
  4510. if (!cellsPerWeek) {
  4511. throw 'invalid hiddenDays'; // all days were hidden? bad.
  4512. }
  4513. })();
  4514. // Is the current day hidden?
  4515. // `day` is a day-of-week index (0-6), or a Moment
  4516. function isHiddenDay(day) {
  4517. if (moment.isMoment(day)) {
  4518. day = day.day();
  4519. }
  4520. return isHiddenDayHash[day];
  4521. }
  4522. function getCellsPerWeek() {
  4523. return cellsPerWeek;
  4524. }
  4525. // Incrementing the current day until it is no longer a hidden day, returning a copy.
  4526. // If the initial value of `date` is not a hidden day, don't do anything.
  4527. // Pass `isExclusive` as `true` if you are dealing with an end date.
  4528. // `inc` defaults to `1` (increment one day forward each time)
  4529. function skipHiddenDays(date, inc, isExclusive) {
  4530. var out = date.clone();
  4531. inc = inc || 1;
  4532. while (
  4533. isHiddenDayHash[(out.day() + (isExclusive ? inc : 0) + 7) % 7]
  4534. ) {
  4535. out.add('days', inc);
  4536. }
  4537. return out;
  4538. }
  4539. //
  4540. // TRANSFORMATIONS: cell -> cell offset -> day offset -> date
  4541. //
  4542. // cell -> date (combines all transformations)
  4543. // Possible arguments:
  4544. // - row, col
  4545. // - { row:#, col: # }
  4546. function cellToDate() {
  4547. var cellOffset = cellToCellOffset.apply(null, arguments);
  4548. var dayOffset = cellOffsetToDayOffset(cellOffset);
  4549. var date = dayOffsetToDate(dayOffset);
  4550. return date;
  4551. }
  4552. // cell -> cell offset
  4553. // Possible arguments:
  4554. // - row, col
  4555. // - { row:#, col:# }
  4556. function cellToCellOffset(row, col) {
  4557. var colCnt = t.getColCnt();
  4558. // rtl variables. wish we could pre-populate these. but where?
  4559. var dis = isRTL ? -1 : 1;
  4560. var dit = isRTL ? colCnt - 1 : 0;
  4561. if (typeof row == 'object') {
  4562. col = row.col;
  4563. row = row.row;
  4564. }
  4565. var cellOffset = row * colCnt + (col * dis + dit); // column, adjusted for RTL (dis & dit)
  4566. return cellOffset;
  4567. }
  4568. // cell offset -> day offset
  4569. function cellOffsetToDayOffset(cellOffset) {
  4570. var day0 = t.start.day(); // first date's day of week
  4571. cellOffset += dayToCellMap[day0]; // normlize cellOffset to beginning-of-week
  4572. return Math.floor(cellOffset / cellsPerWeek) * 7 + // # of days from full weeks
  4573. cellToDayMap[ // # of days from partial last week
  4574. (cellOffset % cellsPerWeek + cellsPerWeek) % cellsPerWeek // crazy math to handle negative cellOffsets
  4575. ] -
  4576. day0; // adjustment for beginning-of-week normalization
  4577. }
  4578. // day offset -> date
  4579. function dayOffsetToDate(dayOffset) {
  4580. return t.start.clone().add('days', dayOffset);
  4581. }
  4582. //
  4583. // TRANSFORMATIONS: date -> day offset -> cell offset -> cell
  4584. //
  4585. // date -> cell (combines all transformations)
  4586. function dateToCell(date) {
  4587. var dayOffset = dateToDayOffset(date);
  4588. var cellOffset = dayOffsetToCellOffset(dayOffset);
  4589. var cell = cellOffsetToCell(cellOffset);
  4590. return cell;
  4591. }
  4592. // date -> day offset
  4593. function dateToDayOffset(date) {
  4594. return date.clone().stripTime().diff(t.start, 'days');
  4595. }
  4596. // day offset -> cell offset
  4597. function dayOffsetToCellOffset(dayOffset) {
  4598. var day0 = t.start.day(); // first date's day of week
  4599. dayOffset += day0; // normalize dayOffset to beginning-of-week
  4600. return Math.floor(dayOffset / 7) * cellsPerWeek + // # of cells from full weeks
  4601. dayToCellMap[ // # of cells from partial last week
  4602. (dayOffset % 7 + 7) % 7 // crazy math to handle negative dayOffsets
  4603. ] -
  4604. dayToCellMap[day0]; // adjustment for beginning-of-week normalization
  4605. }
  4606. // cell offset -> cell (object with row & col keys)
  4607. function cellOffsetToCell(cellOffset) {
  4608. var colCnt = t.getColCnt();
  4609. // rtl variables. wish we could pre-populate these. but where?
  4610. var dis = isRTL ? -1 : 1;
  4611. var dit = isRTL ? colCnt - 1 : 0;
  4612. var row = Math.floor(cellOffset / colCnt);
  4613. var col = ((cellOffset % colCnt + colCnt) % colCnt) * dis + dit; // column, adjusted for RTL (dis & dit)
  4614. return {
  4615. row: row,
  4616. col: col
  4617. };
  4618. }
  4619. //
  4620. // Converts a date range into an array of segment objects.
  4621. // "Segments" are horizontal stretches of time, sliced up by row.
  4622. // A segment object has the following properties:
  4623. // - row
  4624. // - cols
  4625. // - isStart
  4626. // - isEnd
  4627. //
  4628. function rangeToSegments(start, end) {
  4629. var rowCnt = t.getRowCnt();
  4630. var colCnt = t.getColCnt();
  4631. var segments = []; // array of segments to return
  4632. // day offset for given date range
  4633. var rangeDayOffsetStart = dateToDayOffset(start);
  4634. var rangeDayOffsetEnd = dateToDayOffset(end); // an exclusive value
  4635. var endTimeMS = +end.time();
  4636. if (endTimeMS && endTimeMS >= nextDayThreshold) {
  4637. rangeDayOffsetEnd++;
  4638. }
  4639. rangeDayOffsetEnd = Math.max(rangeDayOffsetEnd, rangeDayOffsetStart + 1);
  4640. // first and last cell offset for the given date range
  4641. // "last" implies inclusivity
  4642. var rangeCellOffsetFirst = dayOffsetToCellOffset(rangeDayOffsetStart);
  4643. var rangeCellOffsetLast = dayOffsetToCellOffset(rangeDayOffsetEnd) - 1;
  4644. // loop through all the rows in the view
  4645. for (var row=0; row<rowCnt; row++) {
  4646. // first and last cell offset for the row
  4647. var rowCellOffsetFirst = row * colCnt;
  4648. var rowCellOffsetLast = rowCellOffsetFirst + colCnt - 1;
  4649. // get the segment's cell offsets by constraining the range's cell offsets to the bounds of the row
  4650. var segmentCellOffsetFirst = Math.max(rangeCellOffsetFirst, rowCellOffsetFirst);
  4651. var segmentCellOffsetLast = Math.min(rangeCellOffsetLast, rowCellOffsetLast);
  4652. // make sure segment's offsets are valid and in view
  4653. if (segmentCellOffsetFirst <= segmentCellOffsetLast) {
  4654. // translate to cells
  4655. var segmentCellFirst = cellOffsetToCell(segmentCellOffsetFirst);
  4656. var segmentCellLast = cellOffsetToCell(segmentCellOffsetLast);
  4657. // view might be RTL, so order by leftmost column
  4658. var cols = [ segmentCellFirst.col, segmentCellLast.col ].sort();
  4659. // Determine if segment's first/last cell is the beginning/end of the date range.
  4660. // We need to compare "day offset" because "cell offsets" are often ambiguous and
  4661. // can translate to multiple days, and an edge case reveals itself when we the
  4662. // range's first cell is hidden (we don't want isStart to be true).
  4663. var isStart = cellOffsetToDayOffset(segmentCellOffsetFirst) == rangeDayOffsetStart;
  4664. var isEnd = cellOffsetToDayOffset(segmentCellOffsetLast) + 1 == rangeDayOffsetEnd; // +1 for comparing exclusively
  4665. segments.push({
  4666. row: row,
  4667. leftCol: cols[0],
  4668. rightCol: cols[1],
  4669. isStart: isStart,
  4670. isEnd: isEnd
  4671. });
  4672. }
  4673. }
  4674. return segments;
  4675. }
  4676. }
  4677. ;;
  4678. function DayEventRenderer() {
  4679. var t = this;
  4680. // exports
  4681. t.renderDayEvents = renderDayEvents;
  4682. t.draggableDayEvent = draggableDayEvent; // made public so that subclasses can override
  4683. t.resizableDayEvent = resizableDayEvent; // "
  4684. // imports
  4685. var opt = t.opt;
  4686. var trigger = t.trigger;
  4687. var isEventDraggable = t.isEventDraggable;
  4688. var isEventResizable = t.isEventResizable;
  4689. var reportEventElement = t.reportEventElement;
  4690. var eventElementHandlers = t.eventElementHandlers;
  4691. var showEvents = t.showEvents;
  4692. var hideEvents = t.hideEvents;
  4693. var eventDrop = t.eventDrop;
  4694. var eventResize = t.eventResize;
  4695. var getRowCnt = t.getRowCnt;
  4696. var getColCnt = t.getColCnt;
  4697. var allDayRow = t.allDayRow; // TODO: rename
  4698. var colLeft = t.colLeft;
  4699. var colRight = t.colRight;
  4700. var colContentLeft = t.colContentLeft;
  4701. var colContentRight = t.colContentRight;
  4702. var getDaySegmentContainer = t.getDaySegmentContainer;
  4703. var renderDayOverlay = t.renderDayOverlay;
  4704. var clearOverlays = t.clearOverlays;
  4705. var clearSelection = t.clearSelection;
  4706. var getHoverListener = t.getHoverListener;
  4707. var rangeToSegments = t.rangeToSegments;
  4708. var cellToDate = t.cellToDate;
  4709. var cellToCellOffset = t.cellToCellOffset;
  4710. var cellOffsetToDayOffset = t.cellOffsetToDayOffset;
  4711. var dateToDayOffset = t.dateToDayOffset;
  4712. var dayOffsetToCellOffset = t.dayOffsetToCellOffset;
  4713. var calendar = t.calendar;
  4714. var getEventEnd = calendar.getEventEnd;
  4715. // Render `events` onto the calendar, attach mouse event handlers, and call the `eventAfterRender` callback for each.
  4716. // Mouse event will be lazily applied, except if the event has an ID of `modifiedEventId`.
  4717. // Can only be called when the event container is empty (because it wipes out all innerHTML).
  4718. function renderDayEvents(events, modifiedEventId) {
  4719. // do the actual rendering. Receive the intermediate "segment" data structures.
  4720. var segments = _renderDayEvents(
  4721. events,
  4722. false, // don't append event elements
  4723. true // set the heights of the rows
  4724. );
  4725. // report the elements to the View, for general drag/resize utilities
  4726. segmentElementEach(segments, function(segment, element) {
  4727. reportEventElement(segment.event, element);
  4728. });
  4729. // attach mouse handlers
  4730. attachHandlers(segments, modifiedEventId);
  4731. // call `eventAfterRender` callback for each event
  4732. segmentElementEach(segments, function(segment, element) {
  4733. trigger('eventAfterRender', segment.event, segment.event, element);
  4734. });
  4735. }
  4736. // Render an event on the calendar, but don't report them anywhere, and don't attach mouse handlers.
  4737. // Append this event element to the event container, which might already be populated with events.
  4738. // If an event's segment will have row equal to `adjustRow`, then explicitly set its top coordinate to `adjustTop`.
  4739. // This hack is used to maintain continuity when user is manually resizing an event.
  4740. // Returns an array of DOM elements for the event.
  4741. function renderTempDayEvent(event, adjustRow, adjustTop) {
  4742. // actually render the event. `true` for appending element to container.
  4743. // Recieve the intermediate "segment" data structures.
  4744. var segments = _renderDayEvents(
  4745. [ event ],
  4746. true, // append event elements
  4747. false // don't set the heights of the rows
  4748. );
  4749. var elements = [];
  4750. // Adjust certain elements' top coordinates
  4751. segmentElementEach(segments, function(segment, element) {
  4752. if (segment.row === adjustRow) {
  4753. element.css('top', adjustTop);
  4754. }
  4755. elements.push(element[0]); // accumulate DOM nodes
  4756. });
  4757. return elements;
  4758. }
  4759. // Render events onto the calendar. Only responsible for the VISUAL aspect.
  4760. // Not responsible for attaching handlers or calling callbacks.
  4761. // Set `doAppend` to `true` for rendering elements without clearing the existing container.
  4762. // Set `doRowHeights` to allow setting the height of each row, to compensate for vertical event overflow.
  4763. function _renderDayEvents(events, doAppend, doRowHeights) {
  4764. // where the DOM nodes will eventually end up
  4765. var finalContainer = getDaySegmentContainer();
  4766. // the container where the initial HTML will be rendered.
  4767. // If `doAppend`==true, uses a temporary container.
  4768. var renderContainer = doAppend ? $("<div/>") : finalContainer;
  4769. var segments = buildSegments(events);
  4770. var html;
  4771. var elements;
  4772. // calculate the desired `left` and `width` properties on each segment object
  4773. calculateHorizontals(segments);
  4774. // build the HTML string. relies on `left` property
  4775. html = buildHTML(segments);
  4776. // render the HTML. innerHTML is considerably faster than jQuery's .html()
  4777. renderContainer[0].innerHTML = html;
  4778. // retrieve the individual elements
  4779. elements = renderContainer.children();
  4780. // if we were appending, and thus using a temporary container,
  4781. // re-attach elements to the real container.
  4782. if (doAppend) {
  4783. finalContainer.append(elements);
  4784. }
  4785. // assigns each element to `segment.event`, after filtering them through user callbacks
  4786. resolveElements(segments, elements);
  4787. // Calculate the left and right padding+margin for each element.
  4788. // We need this for setting each element's desired outer width, because of the W3C box model.
  4789. // It's important we do this in a separate pass from acually setting the width on the DOM elements
  4790. // because alternating reading/writing dimensions causes reflow for every iteration.
  4791. segmentElementEach(segments, function(segment, element) {
  4792. segment.hsides = hsides(element, true); // include margins = `true`
  4793. });
  4794. // Set the width of each element
  4795. segmentElementEach(segments, function(segment, element) {
  4796. element.width(
  4797. Math.max(0, segment.outerWidth - segment.hsides)
  4798. );
  4799. });
  4800. // Grab each element's outerHeight (setVerticals uses this).
  4801. // To get an accurate reading, it's important to have each element's width explicitly set already.
  4802. segmentElementEach(segments, function(segment, element) {
  4803. segment.outerHeight = element.outerHeight(true); // include margins = `true`
  4804. });
  4805. // Set the top coordinate on each element (requires segment.outerHeight)
  4806. setVerticals(segments, doRowHeights);
  4807. return segments;
  4808. }
  4809. // Generate an array of "segments" for all events.
  4810. function buildSegments(events) {
  4811. var segments = [];
  4812. for (var i=0; i<events.length; i++) {
  4813. var eventSegments = buildSegmentsForEvent(events[i]);
  4814. segments.push.apply(segments, eventSegments); // append an array to an array
  4815. }
  4816. return segments;
  4817. }
  4818. // Generate an array of segments for a single event.
  4819. // A "segment" is the same data structure that View.rangeToSegments produces,
  4820. // with the addition of the `event` property being set to reference the original event.
  4821. function buildSegmentsForEvent(event) {
  4822. var segments = rangeToSegments(event.start, getEventEnd(event));
  4823. for (var i=0; i<segments.length; i++) {
  4824. segments[i].event = event;
  4825. }
  4826. return segments;
  4827. }
  4828. // Sets the `left` and `outerWidth` property of each segment.
  4829. // These values are the desired dimensions for the eventual DOM elements.
  4830. function calculateHorizontals(segments) {
  4831. var isRTL = opt('isRTL');
  4832. for (var i=0; i<segments.length; i++) {
  4833. var segment = segments[i];
  4834. // Determine functions used for calulating the elements left/right coordinates,
  4835. // depending on whether the view is RTL or not.
  4836. // NOTE:
  4837. // colLeft/colRight returns the coordinate butting up the edge of the cell.
  4838. // colContentLeft/colContentRight is indented a little bit from the edge.
  4839. var leftFunc = (isRTL ? segment.isEnd : segment.isStart) ? colContentLeft : colLeft;
  4840. var rightFunc = (isRTL ? segment.isStart : segment.isEnd) ? colContentRight : colRight;
  4841. var left = leftFunc(segment.leftCol);
  4842. var right = rightFunc(segment.rightCol);
  4843. segment.left = left;
  4844. segment.outerWidth = right - left;
  4845. }
  4846. }
  4847. // Build a concatenated HTML string for an array of segments
  4848. function buildHTML(segments) {
  4849. var html = '';
  4850. for (var i=0; i<segments.length; i++) {
  4851. html += buildHTMLForSegment(segments[i]);
  4852. }
  4853. return html;
  4854. }
  4855. // Build an HTML string for a single segment.
  4856. // Relies on the following properties:
  4857. // - `segment.event` (from `buildSegmentsForEvent`)
  4858. // - `segment.left` (from `calculateHorizontals`)
  4859. function buildHTMLForSegment(segment) {
  4860. var html = '';
  4861. var isRTL = opt('isRTL');
  4862. var event = segment.event;
  4863. var url = event.url;
  4864. // generate the list of CSS classNames
  4865. var classNames = [ 'fc-event', 'fc-event-hori' ];
  4866. if (isEventDraggable(event)) {
  4867. classNames.push('fc-event-draggable');
  4868. }
  4869. if (segment.isStart) {
  4870. classNames.push('fc-event-start');
  4871. }
  4872. if (segment.isEnd) {
  4873. classNames.push('fc-event-end');
  4874. }
  4875. // use the event's configured classNames
  4876. // guaranteed to be an array via `buildEvent`
  4877. classNames = classNames.concat(event.className);
  4878. if (event.source) {
  4879. // use the event's source's classNames, if specified
  4880. classNames = classNames.concat(event.source.className || []);
  4881. }
  4882. // generate a semicolon delimited CSS string for any of the "skin" properties
  4883. // of the event object (`backgroundColor`, `borderColor` and such)
  4884. var skinCss = getSkinCss(event, opt);
  4885. if (url) {
  4886. html += "<a href='" + htmlEscape(url) + "'";
  4887. }else{
  4888. html += "<div";
  4889. }
  4890. html +=
  4891. " class='" + classNames.join(' ') + "'" +
  4892. " style=" +
  4893. "'" +
  4894. "position:absolute;" +
  4895. "left:" + segment.left + "px;" +
  4896. skinCss +
  4897. "'" +
  4898. ">" +
  4899. "<div class='fc-event-inner'>";
  4900. if (!event.allDay && segment.isStart) {
  4901. html +=
  4902. "<span class='fc-event-time'>" +
  4903. htmlEscape(t.getEventTimeText(event)) +
  4904. "</span>";
  4905. }
  4906. html +=
  4907. "<span class='fc-event-title'>" +
  4908. htmlEscape(event.title || '') +
  4909. "</span>" +
  4910. "</div>";
  4911. if (event.allDay && segment.isEnd && isEventResizable(event)) {
  4912. html +=
  4913. "<div class='ui-resizable-handle ui-resizable-" + (isRTL ? 'w' : 'e') + "'>" +
  4914. "&nbsp;&nbsp;&nbsp;" + // makes hit area a lot better for IE6/7
  4915. "</div>";
  4916. }
  4917. html += "</" + (url ? "a" : "div") + ">";
  4918. // TODO:
  4919. // When these elements are initially rendered, they will be briefly visibile on the screen,
  4920. // even though their widths/heights are not set.
  4921. // SOLUTION: initially set them as visibility:hidden ?
  4922. return html;
  4923. }
  4924. // Associate each segment (an object) with an element (a jQuery object),
  4925. // by setting each `segment.element`.
  4926. // Run each element through the `eventRender` filter, which allows developers to
  4927. // modify an existing element, supply a new one, or cancel rendering.
  4928. function resolveElements(segments, elements) {
  4929. for (var i=0; i<segments.length; i++) {
  4930. var segment = segments[i];
  4931. var event = segment.event;
  4932. var element = elements.eq(i);
  4933. // call the trigger with the original element
  4934. var triggerRes = trigger('eventRender', event, event, element);
  4935. if (triggerRes === false) {
  4936. // if `false`, remove the event from the DOM and don't assign it to `segment.event`
  4937. element.remove();
  4938. }
  4939. else {
  4940. if (triggerRes && triggerRes !== true) {
  4941. // the trigger returned a new element, but not `true` (which means keep the existing element)
  4942. // re-assign the important CSS dimension properties that were already assigned in `buildHTMLForSegment`
  4943. triggerRes = $(triggerRes)
  4944. .css({
  4945. position: 'absolute',
  4946. left: segment.left
  4947. });
  4948. element.replaceWith(triggerRes);
  4949. element = triggerRes;
  4950. }
  4951. segment.element = element;
  4952. }
  4953. }
  4954. }
  4955. /* Top-coordinate Methods
  4956. -------------------------------------------------------------------------------------------------*/
  4957. // Sets the "top" CSS property for each element.
  4958. // If `doRowHeights` is `true`, also sets each row's first cell to an explicit height,
  4959. // so that if elements vertically overflow, the cell expands vertically to compensate.
  4960. function setVerticals(segments, doRowHeights) {
  4961. var rowContentHeights = calculateVerticals(segments); // also sets segment.top
  4962. var rowContentElements = getRowContentElements(); // returns 1 inner div per row
  4963. var rowContentTops = [];
  4964. var i;
  4965. // Set each row's height by setting height of first inner div
  4966. if (doRowHeights) {
  4967. for (i=0; i<rowContentElements.length; i++) {
  4968. rowContentElements[i].height(rowContentHeights[i]);
  4969. }
  4970. }
  4971. // Get each row's top, relative to the views's origin.
  4972. // Important to do this after setting each row's height.
  4973. for (i=0; i<rowContentElements.length; i++) {
  4974. rowContentTops.push(
  4975. rowContentElements[i].position().top
  4976. );
  4977. }
  4978. // Set each segment element's CSS "top" property.
  4979. // Each segment object has a "top" property, which is relative to the row's top, but...
  4980. segmentElementEach(segments, function(segment, element) {
  4981. element.css(
  4982. 'top',
  4983. rowContentTops[segment.row] + segment.top // ...now, relative to views's origin
  4984. );
  4985. });
  4986. }
  4987. // Calculate the "top" coordinate for each segment, relative to the "top" of the row.
  4988. // Also, return an array that contains the "content" height for each row
  4989. // (the height displaced by the vertically stacked events in the row).
  4990. // Requires segments to have their `outerHeight` property already set.
  4991. function calculateVerticals(segments) {
  4992. var rowCnt = getRowCnt();
  4993. var colCnt = getColCnt();
  4994. var rowContentHeights = []; // content height for each row
  4995. var segmentRows = buildSegmentRows(segments); // an array of segment arrays, one for each row
  4996. var colI;
  4997. for (var rowI=0; rowI<rowCnt; rowI++) {
  4998. var segmentRow = segmentRows[rowI];
  4999. // an array of running total heights for each column.
  5000. // initialize with all zeros.
  5001. var colHeights = [];
  5002. for (colI=0; colI<colCnt; colI++) {
  5003. colHeights.push(0);
  5004. }
  5005. // loop through every segment
  5006. for (var segmentI=0; segmentI<segmentRow.length; segmentI++) {
  5007. var segment = segmentRow[segmentI];
  5008. // find the segment's top coordinate by looking at the max height
  5009. // of all the columns the segment will be in.
  5010. segment.top = arrayMax(
  5011. colHeights.slice(
  5012. segment.leftCol,
  5013. segment.rightCol + 1 // make exclusive for slice
  5014. )
  5015. );
  5016. // adjust the columns to account for the segment's height
  5017. for (colI=segment.leftCol; colI<=segment.rightCol; colI++) {
  5018. colHeights[colI] = segment.top + segment.outerHeight;
  5019. }
  5020. }
  5021. // the tallest column in the row should be the "content height"
  5022. rowContentHeights.push(arrayMax(colHeights));
  5023. }
  5024. return rowContentHeights;
  5025. }
  5026. // Build an array of segment arrays, each representing the segments that will
  5027. // be in a row of the grid, sorted by which event should be closest to the top.
  5028. function buildSegmentRows(segments) {
  5029. var rowCnt = getRowCnt();
  5030. var segmentRows = [];
  5031. var segmentI;
  5032. var segment;
  5033. var rowI;
  5034. // group segments by row
  5035. for (segmentI=0; segmentI<segments.length; segmentI++) {
  5036. segment = segments[segmentI];
  5037. rowI = segment.row;
  5038. if (segment.element) { // was rendered?
  5039. if (segmentRows[rowI]) {
  5040. // already other segments. append to array
  5041. segmentRows[rowI].push(segment);
  5042. }
  5043. else {
  5044. // first segment in row. create new array
  5045. segmentRows[rowI] = [ segment ];
  5046. }
  5047. }
  5048. }
  5049. // sort each row
  5050. for (rowI=0; rowI<rowCnt; rowI++) {
  5051. segmentRows[rowI] = sortSegmentRow(
  5052. segmentRows[rowI] || [] // guarantee an array, even if no segments
  5053. );
  5054. }
  5055. return segmentRows;
  5056. }
  5057. // Sort an array of segments according to which segment should appear closest to the top
  5058. function sortSegmentRow(segments) {
  5059. var sortedSegments = [];
  5060. // build the subrow array
  5061. var subrows = buildSegmentSubrows(segments);
  5062. // flatten it
  5063. for (var i=0; i<subrows.length; i++) {
  5064. sortedSegments.push.apply(sortedSegments, subrows[i]); // append an array to an array
  5065. }
  5066. return sortedSegments;
  5067. }
  5068. // Take an array of segments, which are all assumed to be in the same row,
  5069. // and sort into subrows.
  5070. function buildSegmentSubrows(segments) {
  5071. // Give preference to elements with certain criteria, so they have
  5072. // a chance to be closer to the top.
  5073. segments.sort(compareDaySegments);
  5074. var subrows = [];
  5075. for (var i=0; i<segments.length; i++) {
  5076. var segment = segments[i];
  5077. // loop through subrows, starting with the topmost, until the segment
  5078. // doesn't collide with other segments.
  5079. for (var j=0; j<subrows.length; j++) {
  5080. if (!isDaySegmentCollision(segment, subrows[j])) {
  5081. break;
  5082. }
  5083. }
  5084. // `j` now holds the desired subrow index
  5085. if (subrows[j]) {
  5086. subrows[j].push(segment);
  5087. }
  5088. else {
  5089. subrows[j] = [ segment ];
  5090. }
  5091. }
  5092. return subrows;
  5093. }
  5094. // Return an array of jQuery objects for the placeholder content containers of each row.
  5095. // The content containers don't actually contain anything, but their dimensions should match
  5096. // the events that are overlaid on top.
  5097. function getRowContentElements() {
  5098. var i;
  5099. var rowCnt = getRowCnt();
  5100. var rowDivs = [];
  5101. for (i=0; i<rowCnt; i++) {
  5102. rowDivs[i] = allDayRow(i)
  5103. .find('div.fc-day-content > div');
  5104. }
  5105. return rowDivs;
  5106. }
  5107. /* Mouse Handlers
  5108. ---------------------------------------------------------------------------------------------------*/
  5109. // TODO: better documentation!
  5110. function attachHandlers(segments, modifiedEventId) {
  5111. var segmentContainer = getDaySegmentContainer();
  5112. segmentElementEach(segments, function(segment, element, i) {
  5113. var event = segment.event;
  5114. if (event._id === modifiedEventId) {
  5115. bindDaySeg(event, element, segment);
  5116. }else{
  5117. element[0]._fci = i; // for lazySegBind
  5118. }
  5119. });
  5120. lazySegBind(segmentContainer, segments, bindDaySeg);
  5121. }
  5122. function bindDaySeg(event, eventElement, segment) {
  5123. if (isEventDraggable(event)) {
  5124. t.draggableDayEvent(event, eventElement, segment); // use `t` so subclasses can override
  5125. }
  5126. if (
  5127. event.allDay &&
  5128. segment.isEnd && // only allow resizing on the final segment for an event
  5129. isEventResizable(event)
  5130. ) {
  5131. t.resizableDayEvent(event, eventElement, segment); // use `t` so subclasses can override
  5132. }
  5133. // attach all other handlers.
  5134. // needs to be after, because resizableDayEvent might stopImmediatePropagation on click
  5135. eventElementHandlers(event, eventElement);
  5136. }
  5137. function draggableDayEvent(event, eventElement) {
  5138. var hoverListener = getHoverListener();
  5139. var dayDelta;
  5140. var eventStart;
  5141. eventElement.draggable({
  5142. delay: 50,
  5143. opacity: opt('dragOpacity'),
  5144. revertDuration: opt('dragRevertDuration'),
  5145. start: function(ev, ui) {
  5146. trigger('eventDragStart', eventElement[0], event, ev, ui);
  5147. hideEvents(event, eventElement);
  5148. hoverListener.start(function(cell, origCell, rowDelta, colDelta) {
  5149. eventElement.draggable('option', 'revert', !cell || !rowDelta && !colDelta);
  5150. clearOverlays();
  5151. if (cell) {
  5152. var origCellDate = cellToDate(origCell);
  5153. var cellDate = cellToDate(cell);
  5154. dayDelta = cellDate.diff(origCellDate, 'days');
  5155. eventStart = event.start.clone().add('days', dayDelta);
  5156. renderDayOverlay(
  5157. eventStart,
  5158. getEventEnd(event).add('days', dayDelta)
  5159. );
  5160. }
  5161. else {
  5162. dayDelta = 0;
  5163. }
  5164. }, ev, 'drag');
  5165. },
  5166. stop: function(ev, ui) {
  5167. hoverListener.stop();
  5168. clearOverlays();
  5169. trigger('eventDragStop', eventElement[0], event, ev, ui);
  5170. if (dayDelta) {
  5171. eventDrop(
  5172. eventElement[0],
  5173. event,
  5174. eventStart,
  5175. ev,
  5176. ui
  5177. );
  5178. }
  5179. else {
  5180. eventElement.css('filter', ''); // clear IE opacity side-effects
  5181. showEvents(event, eventElement);
  5182. }
  5183. }
  5184. });
  5185. }
  5186. function resizableDayEvent(event, element, segment) {
  5187. var isRTL = opt('isRTL');
  5188. var direction = isRTL ? 'w' : 'e';
  5189. var handle = element.find('.ui-resizable-' + direction); // TODO: stop using this class because we aren't using jqui for this
  5190. var isResizing = false;
  5191. // TODO: look into using jquery-ui mouse widget for this stuff
  5192. disableTextSelection(element); // prevent native <a> selection for IE
  5193. element
  5194. .mousedown(function(ev) { // prevent native <a> selection for others
  5195. ev.preventDefault();
  5196. })
  5197. .click(function(ev) {
  5198. if (isResizing) {
  5199. ev.preventDefault(); // prevent link from being visited (only method that worked in IE6)
  5200. ev.stopImmediatePropagation(); // prevent fullcalendar eventClick handler from being called
  5201. // (eventElementHandlers needs to be bound after resizableDayEvent)
  5202. }
  5203. });
  5204. handle.mousedown(function(ev) {
  5205. if (ev.which != 1) {
  5206. return; // needs to be left mouse button
  5207. }
  5208. isResizing = true;
  5209. var hoverListener = getHoverListener();
  5210. var elementTop = element.css('top');
  5211. var dayDelta;
  5212. var eventEnd;
  5213. var helpers;
  5214. var eventCopy = $.extend({}, event);
  5215. var minCellOffset = dayOffsetToCellOffset(dateToDayOffset(event.start));
  5216. clearSelection();
  5217. $('body')
  5218. .css('cursor', direction + '-resize')
  5219. .one('mouseup', mouseup);
  5220. trigger('eventResizeStart', element[0], event, ev, {}); // {} is dummy jqui event
  5221. hoverListener.start(function(cell, origCell) {
  5222. if (cell) {
  5223. var origCellOffset = cellToCellOffset(origCell);
  5224. var cellOffset = cellToCellOffset(cell);
  5225. // don't let resizing move earlier than start date cell
  5226. cellOffset = Math.max(cellOffset, minCellOffset);
  5227. dayDelta =
  5228. cellOffsetToDayOffset(cellOffset) -
  5229. cellOffsetToDayOffset(origCellOffset);
  5230. eventEnd = getEventEnd(event).add('days', dayDelta); // assumed to already have a stripped time
  5231. if (dayDelta) {
  5232. eventCopy.end = eventEnd;
  5233. var oldHelpers = helpers;
  5234. helpers = renderTempDayEvent(eventCopy, segment.row, elementTop);
  5235. helpers = $(helpers); // turn array into a jQuery object
  5236. helpers.find('*').css('cursor', direction + '-resize');
  5237. if (oldHelpers) {
  5238. oldHelpers.remove();
  5239. }
  5240. hideEvents(event);
  5241. }
  5242. else {
  5243. if (helpers) {
  5244. showEvents(event);
  5245. helpers.remove();
  5246. helpers = null;
  5247. }
  5248. }
  5249. clearOverlays();
  5250. renderDayOverlay( // coordinate grid already rebuilt with hoverListener.start()
  5251. event.start,
  5252. eventEnd
  5253. // TODO: instead of calling renderDayOverlay() with dates,
  5254. // call _renderDayOverlay (or whatever) with cell offsets.
  5255. );
  5256. }
  5257. }, ev);
  5258. function mouseup(ev) {
  5259. trigger('eventResizeStop', element[0], event, ev, {}); // {} is dummy jqui event
  5260. $('body').css('cursor', '');
  5261. hoverListener.stop();
  5262. clearOverlays();
  5263. if (dayDelta) {
  5264. eventResize(
  5265. element[0],
  5266. event,
  5267. eventEnd,
  5268. ev,
  5269. {} // dummy jqui event
  5270. );
  5271. // event redraw will clear helpers
  5272. }
  5273. // otherwise, the drag handler already restored the old events
  5274. setTimeout(function() { // make this happen after the element's click event
  5275. isResizing = false;
  5276. },0);
  5277. }
  5278. });
  5279. }
  5280. }
  5281. /* Generalized Segment Utilities
  5282. -------------------------------------------------------------------------------------------------*/
  5283. function isDaySegmentCollision(segment, otherSegments) {
  5284. for (var i=0; i<otherSegments.length; i++) {
  5285. var otherSegment = otherSegments[i];
  5286. if (
  5287. otherSegment.leftCol <= segment.rightCol &&
  5288. otherSegment.rightCol >= segment.leftCol
  5289. ) {
  5290. return true;
  5291. }
  5292. }
  5293. return false;
  5294. }
  5295. function segmentElementEach(segments, callback) { // TODO: use in AgendaView?
  5296. for (var i=0; i<segments.length; i++) {
  5297. var segment = segments[i];
  5298. var element = segment.element;
  5299. if (element) {
  5300. callback(segment, element, i);
  5301. }
  5302. }
  5303. }
  5304. // A cmp function for determining which segments should appear higher up
  5305. function compareDaySegments(a, b) {
  5306. return (b.rightCol - b.leftCol) - (a.rightCol - a.leftCol) || // put wider events first
  5307. b.event.allDay - a.event.allDay || // if tie, put all-day events first (booleans cast to 0/1)
  5308. a.event.start - b.event.start || // if a tie, sort by event start date
  5309. (a.event.title || '').localeCompare(b.event.title); // if a tie, sort by event title
  5310. }
  5311. ;;
  5312. //BUG: unselect needs to be triggered when events are dragged+dropped
  5313. function SelectionManager() {
  5314. var t = this;
  5315. // exports
  5316. t.select = select;
  5317. t.unselect = unselect;
  5318. t.reportSelection = reportSelection;
  5319. t.daySelectionMousedown = daySelectionMousedown;
  5320. t.selectionManagerDestroy = destroy;
  5321. // imports
  5322. var calendar = t.calendar;
  5323. var opt = t.opt;
  5324. var trigger = t.trigger;
  5325. var defaultSelectionEnd = t.defaultSelectionEnd;
  5326. var renderSelection = t.renderSelection;
  5327. var clearSelection = t.clearSelection;
  5328. // locals
  5329. var selected = false;
  5330. // unselectAuto
  5331. if (opt('selectable') && opt('unselectAuto')) {
  5332. $(document).on('mousedown', documentMousedown);
  5333. }
  5334. function documentMousedown(ev) {
  5335. var ignore = opt('unselectCancel');
  5336. if (ignore) {
  5337. if ($(ev.target).parents(ignore).length) { // could be optimized to stop after first match
  5338. return;
  5339. }
  5340. }
  5341. unselect(ev);
  5342. }
  5343. function select(start, end) {
  5344. unselect();
  5345. start = calendar.moment(start);
  5346. if (end) {
  5347. end = calendar.moment(end);
  5348. }
  5349. else {
  5350. end = defaultSelectionEnd(start);
  5351. }
  5352. renderSelection(start, end);
  5353. reportSelection(start, end);
  5354. }
  5355. // TODO: better date normalization. see notes in automated test
  5356. function unselect(ev) {
  5357. if (selected) {
  5358. selected = false;
  5359. clearSelection();
  5360. trigger('unselect', null, ev);
  5361. }
  5362. }
  5363. function reportSelection(start, end, ev) {
  5364. selected = true;
  5365. trigger('select', null, start, end, ev);
  5366. }
  5367. function daySelectionMousedown(ev) { // not really a generic manager method, oh well
  5368. var cellToDate = t.cellToDate;
  5369. var getIsCellAllDay = t.getIsCellAllDay;
  5370. var hoverListener = t.getHoverListener();
  5371. var reportDayClick = t.reportDayClick; // this is hacky and sort of weird
  5372. if (ev.which == 1 && opt('selectable')) { // which==1 means left mouse button
  5373. unselect(ev);
  5374. var dates;
  5375. hoverListener.start(function(cell, origCell) { // TODO: maybe put cellToDate/getIsCellAllDay info in cell
  5376. clearSelection();
  5377. if (cell && getIsCellAllDay(cell)) {
  5378. dates = [ cellToDate(origCell), cellToDate(cell) ].sort(dateCompare);
  5379. renderSelection(
  5380. dates[0],
  5381. dates[1].clone().add('days', 1) // make exclusive
  5382. );
  5383. }else{
  5384. dates = null;
  5385. }
  5386. }, ev);
  5387. $(document).one('mouseup', function(ev) {
  5388. hoverListener.stop();
  5389. if (dates) {
  5390. if (+dates[0] == +dates[1]) {
  5391. reportDayClick(dates[0], ev);
  5392. }
  5393. reportSelection(
  5394. dates[0],
  5395. dates[1].clone().add('days', 1), // make exclusive
  5396. ev
  5397. );
  5398. }
  5399. });
  5400. }
  5401. }
  5402. function destroy() {
  5403. $(document).off('mousedown', documentMousedown);
  5404. }
  5405. }
  5406. ;;
  5407. function OverlayManager() {
  5408. var t = this;
  5409. // exports
  5410. t.renderOverlay = renderOverlay;
  5411. t.clearOverlays = clearOverlays;
  5412. // locals
  5413. var usedOverlays = [];
  5414. var unusedOverlays = [];
  5415. function renderOverlay(rect, parent) {
  5416. var e = unusedOverlays.shift();
  5417. if (!e) {
  5418. e = $("<div class='fc-cell-overlay' style='position:absolute;z-index:3'/>");
  5419. }
  5420. if (e[0].parentNode != parent[0]) {
  5421. e.appendTo(parent);
  5422. }
  5423. usedOverlays.push(e.css(rect).show());
  5424. return e;
  5425. }
  5426. function clearOverlays() {
  5427. var e;
  5428. while ((e = usedOverlays.shift())) {
  5429. unusedOverlays.push(e.hide().unbind());
  5430. }
  5431. }
  5432. }
  5433. ;;
  5434. function CoordinateGrid(buildFunc) {
  5435. var t = this;
  5436. var rows;
  5437. var cols;
  5438. t.build = function() {
  5439. rows = [];
  5440. cols = [];
  5441. buildFunc(rows, cols);
  5442. };
  5443. t.cell = function(x, y) {
  5444. var rowCnt = rows.length;
  5445. var colCnt = cols.length;
  5446. var i, r=-1, c=-1;
  5447. for (i=0; i<rowCnt; i++) {
  5448. if (y >= rows[i][0] && y < rows[i][1]) {
  5449. r = i;
  5450. break;
  5451. }
  5452. }
  5453. for (i=0; i<colCnt; i++) {
  5454. if (x >= cols[i][0] && x < cols[i][1]) {
  5455. c = i;
  5456. break;
  5457. }
  5458. }
  5459. return (r>=0 && c>=0) ? { row: r, col: c } : null;
  5460. };
  5461. t.rect = function(row0, col0, row1, col1, originElement) { // row1,col1 is inclusive
  5462. var origin = originElement.offset();
  5463. return {
  5464. top: rows[row0][0] - origin.top,
  5465. left: cols[col0][0] - origin.left,
  5466. width: cols[col1][1] - cols[col0][0],
  5467. height: rows[row1][1] - rows[row0][0]
  5468. };
  5469. };
  5470. }
  5471. ;;
  5472. function HoverListener(coordinateGrid) {
  5473. var t = this;
  5474. var bindType;
  5475. var change;
  5476. var firstCell;
  5477. var cell;
  5478. t.start = function(_change, ev, _bindType) {
  5479. change = _change;
  5480. firstCell = cell = null;
  5481. coordinateGrid.build();
  5482. mouse(ev);
  5483. bindType = _bindType || 'mousemove';
  5484. $(document).bind(bindType, mouse);
  5485. };
  5486. function mouse(ev) {
  5487. _fixUIEvent(ev); // see below
  5488. var newCell = coordinateGrid.cell(ev.pageX, ev.pageY);
  5489. if (
  5490. Boolean(newCell) !== Boolean(cell) ||
  5491. newCell && (newCell.row != cell.row || newCell.col != cell.col)
  5492. ) {
  5493. if (newCell) {
  5494. if (!firstCell) {
  5495. firstCell = newCell;
  5496. }
  5497. change(newCell, firstCell, newCell.row-firstCell.row, newCell.col-firstCell.col);
  5498. }else{
  5499. change(newCell, firstCell);
  5500. }
  5501. cell = newCell;
  5502. }
  5503. }
  5504. t.stop = function() {
  5505. $(document).unbind(bindType, mouse);
  5506. return cell;
  5507. };
  5508. }
  5509. // this fix was only necessary for jQuery UI 1.8.16 (and jQuery 1.7 or 1.7.1)
  5510. // upgrading to jQuery UI 1.8.17 (and using either jQuery 1.7 or 1.7.1) fixed the problem
  5511. // but keep this in here for 1.8.16 users
  5512. // and maybe remove it down the line
  5513. function _fixUIEvent(event) { // for issue 1168
  5514. if (event.pageX === undefined) {
  5515. event.pageX = event.originalEvent.pageX;
  5516. event.pageY = event.originalEvent.pageY;
  5517. }
  5518. }
  5519. ;;
  5520. function HorizontalPositionCache(getElement) {
  5521. var t = this,
  5522. elements = {},
  5523. lefts = {},
  5524. rights = {};
  5525. function e(i) {
  5526. return (elements[i] = (elements[i] || getElement(i)));
  5527. }
  5528. t.left = function(i) {
  5529. return (lefts[i] = (lefts[i] === undefined ? e(i).position().left : lefts[i]));
  5530. };
  5531. t.right = function(i) {
  5532. return (rights[i] = (rights[i] === undefined ? t.left(i) + e(i).width() : rights[i]));
  5533. };
  5534. t.clear = function() {
  5535. elements = {};
  5536. lefts = {};
  5537. rights = {};
  5538. };
  5539. }
  5540. ;;
  5541. });