20624d5254d419c98a1db495cd93df7ab956c421.svn-base 231 KB

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