fullcalendar.js 398 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668
  1. /*!
  2. * FullCalendar v3.2.0
  3. *
  4. * Docs & License: https://fullcalendar.io/
  5. * (c) 2017 Adam Shaw
  6. */
  7. (function(factory) {
  8. if (typeof define === 'function' && define.amd) {
  9. define([ 'jquery', 'moment' ], factory);
  10. }
  11. else if (typeof exports === 'object') { // Node/CommonJS
  12. module.exports = factory(require('jquery'), require('moment'));
  13. }
  14. else {
  15. factory(jQuery, moment);
  16. }
  17. })(function($, moment) {
  18. ;;
  19. var FC = $.fullCalendar = {
  20. version: "3.2.0",
  21. // When introducing internal API incompatibilities (where fullcalendar plugins would break),
  22. // the minor version of the calendar should be upped (ex: 2.7.2 -> 2.8.0)
  23. // and the below integer should be incremented.
  24. internalApiVersion: 8
  25. };
  26. var fcViews = FC.views = {};
  27. $.fn.fullCalendar = function(options) {
  28. var args = Array.prototype.slice.call(arguments, 1); // for a possible method call
  29. var res = this; // what this function will return (this jQuery object by default)
  30. this.each(function(i, _element) { // loop each DOM element involved
  31. var element = $(_element);
  32. var calendar = element.data('fullCalendar'); // get the existing calendar object (if any)
  33. var singleRes; // the returned value of this single method call
  34. // a method call
  35. if (typeof options === 'string') {
  36. if (calendar && $.isFunction(calendar[options])) {
  37. singleRes = calendar[options].apply(calendar, args);
  38. if (!i) {
  39. res = singleRes; // record the first method call result
  40. }
  41. if (options === 'destroy') { // for the destroy method, must remove Calendar object data
  42. element.removeData('fullCalendar');
  43. }
  44. }
  45. }
  46. // a new calendar initialization
  47. else if (!calendar) { // don't initialize twice
  48. calendar = new Calendar(element, options);
  49. element.data('fullCalendar', calendar);
  50. calendar.render();
  51. }
  52. });
  53. return res;
  54. };
  55. var complexOptions = [ // names of options that are objects whose properties should be combined
  56. 'header',
  57. 'footer',
  58. 'buttonText',
  59. 'buttonIcons',
  60. 'themeButtonIcons'
  61. ];
  62. // Merges an array of option objects into a single object
  63. function mergeOptions(optionObjs) {
  64. return mergeProps(optionObjs, complexOptions);
  65. }
  66. ;;
  67. // exports
  68. FC.intersectRanges = intersectRanges;
  69. FC.applyAll = applyAll;
  70. FC.debounce = debounce;
  71. FC.isInt = isInt;
  72. FC.htmlEscape = htmlEscape;
  73. FC.cssToStr = cssToStr;
  74. FC.proxy = proxy;
  75. FC.capitaliseFirstLetter = capitaliseFirstLetter;
  76. /* FullCalendar-specific DOM Utilities
  77. ----------------------------------------------------------------------------------------------------------------------*/
  78. // Given the scrollbar widths of some other container, create borders/margins on rowEls in order to match the left
  79. // and right space that was offset by the scrollbars. A 1-pixel border first, then margin beyond that.
  80. function compensateScroll(rowEls, scrollbarWidths) {
  81. if (scrollbarWidths.left) {
  82. rowEls.css({
  83. 'border-left-width': 1,
  84. 'margin-left': scrollbarWidths.left - 1
  85. });
  86. }
  87. if (scrollbarWidths.right) {
  88. rowEls.css({
  89. 'border-right-width': 1,
  90. 'margin-right': scrollbarWidths.right - 1
  91. });
  92. }
  93. }
  94. // Undoes compensateScroll and restores all borders/margins
  95. function uncompensateScroll(rowEls) {
  96. rowEls.css({
  97. 'margin-left': '',
  98. 'margin-right': '',
  99. 'border-left-width': '',
  100. 'border-right-width': ''
  101. });
  102. }
  103. // Make the mouse cursor express that an event is not allowed in the current area
  104. function disableCursor() {
  105. $('body').addClass('fc-not-allowed');
  106. }
  107. // Returns the mouse cursor to its original look
  108. function enableCursor() {
  109. $('body').removeClass('fc-not-allowed');
  110. }
  111. // Given a total available height to fill, have `els` (essentially child rows) expand to accomodate.
  112. // By default, all elements that are shorter than the recommended height are expanded uniformly, not considering
  113. // any other els that are already too tall. if `shouldRedistribute` is on, it considers these tall rows and
  114. // reduces the available height.
  115. function distributeHeight(els, availableHeight, shouldRedistribute) {
  116. // *FLOORING NOTE*: we floor in certain places because zoom can give inaccurate floating-point dimensions,
  117. // and it is better to be shorter than taller, to avoid creating unnecessary scrollbars.
  118. var minOffset1 = Math.floor(availableHeight / els.length); // for non-last element
  119. var minOffset2 = Math.floor(availableHeight - minOffset1 * (els.length - 1)); // for last element *FLOORING NOTE*
  120. var flexEls = []; // elements that are allowed to expand. array of DOM nodes
  121. var flexOffsets = []; // amount of vertical space it takes up
  122. var flexHeights = []; // actual css height
  123. var usedHeight = 0;
  124. undistributeHeight(els); // give all elements their natural height
  125. // find elements that are below the recommended height (expandable).
  126. // important to query for heights in a single first pass (to avoid reflow oscillation).
  127. els.each(function(i, el) {
  128. var minOffset = i === els.length - 1 ? minOffset2 : minOffset1;
  129. var naturalOffset = $(el).outerHeight(true);
  130. if (naturalOffset < minOffset) {
  131. flexEls.push(el);
  132. flexOffsets.push(naturalOffset);
  133. flexHeights.push($(el).height());
  134. }
  135. else {
  136. // this element stretches past recommended height (non-expandable). mark the space as occupied.
  137. usedHeight += naturalOffset;
  138. }
  139. });
  140. // readjust the recommended height to only consider the height available to non-maxed-out rows.
  141. if (shouldRedistribute) {
  142. availableHeight -= usedHeight;
  143. minOffset1 = Math.floor(availableHeight / flexEls.length);
  144. minOffset2 = Math.floor(availableHeight - minOffset1 * (flexEls.length - 1)); // *FLOORING NOTE*
  145. }
  146. // assign heights to all expandable elements
  147. $(flexEls).each(function(i, el) {
  148. var minOffset = i === flexEls.length - 1 ? minOffset2 : minOffset1;
  149. var naturalOffset = flexOffsets[i];
  150. var naturalHeight = flexHeights[i];
  151. var newHeight = minOffset - (naturalOffset - naturalHeight); // subtract the margin/padding
  152. if (naturalOffset < minOffset) { // we check this again because redistribution might have changed things
  153. $(el).height(newHeight);
  154. }
  155. });
  156. }
  157. // Undoes distrubuteHeight, restoring all els to their natural height
  158. function undistributeHeight(els) {
  159. els.height('');
  160. }
  161. // Given `els`, a jQuery set of <td> cells, find the cell with the largest natural width and set the widths of all the
  162. // cells to be that width.
  163. // PREREQUISITE: if you want a cell to take up width, it needs to have a single inner element w/ display:inline
  164. function matchCellWidths(els) {
  165. var maxInnerWidth = 0;
  166. els.find('> *').each(function(i, innerEl) {
  167. var innerWidth = $(innerEl).outerWidth();
  168. if (innerWidth > maxInnerWidth) {
  169. maxInnerWidth = innerWidth;
  170. }
  171. });
  172. maxInnerWidth++; // sometimes not accurate of width the text needs to stay on one line. insurance
  173. els.width(maxInnerWidth);
  174. return maxInnerWidth;
  175. }
  176. // Given one element that resides inside another,
  177. // Subtracts the height of the inner element from the outer element.
  178. function subtractInnerElHeight(outerEl, innerEl) {
  179. var both = outerEl.add(innerEl);
  180. var diff;
  181. // effin' IE8/9/10/11 sometimes returns 0 for dimensions. this weird hack was the only thing that worked
  182. both.css({
  183. position: 'relative', // cause a reflow, which will force fresh dimension recalculation
  184. left: -1 // ensure reflow in case the el was already relative. negative is less likely to cause new scroll
  185. });
  186. diff = outerEl.outerHeight() - innerEl.outerHeight(); // grab the dimensions
  187. both.css({ position: '', left: '' }); // undo hack
  188. return diff;
  189. }
  190. /* Element Geom Utilities
  191. ----------------------------------------------------------------------------------------------------------------------*/
  192. FC.getOuterRect = getOuterRect;
  193. FC.getClientRect = getClientRect;
  194. FC.getContentRect = getContentRect;
  195. FC.getScrollbarWidths = getScrollbarWidths;
  196. // borrowed from https://github.com/jquery/jquery-ui/blob/1.11.0/ui/core.js#L51
  197. function getScrollParent(el) {
  198. var position = el.css('position'),
  199. scrollParent = el.parents().filter(function() {
  200. var parent = $(this);
  201. return (/(auto|scroll)/).test(
  202. parent.css('overflow') + parent.css('overflow-y') + parent.css('overflow-x')
  203. );
  204. }).eq(0);
  205. return position === 'fixed' || !scrollParent.length ? $(el[0].ownerDocument || document) : scrollParent;
  206. }
  207. // Queries the outer bounding area of a jQuery element.
  208. // Returns a rectangle with absolute coordinates: left, right (exclusive), top, bottom (exclusive).
  209. // Origin is optional.
  210. function getOuterRect(el, origin) {
  211. var offset = el.offset();
  212. var left = offset.left - (origin ? origin.left : 0);
  213. var top = offset.top - (origin ? origin.top : 0);
  214. return {
  215. left: left,
  216. right: left + el.outerWidth(),
  217. top: top,
  218. bottom: top + el.outerHeight()
  219. };
  220. }
  221. // Queries the area within the margin/border/scrollbars of a jQuery element. Does not go within the padding.
  222. // Returns a rectangle with absolute coordinates: left, right (exclusive), top, bottom (exclusive).
  223. // Origin is optional.
  224. // NOTE: should use clientLeft/clientTop, but very unreliable cross-browser.
  225. function getClientRect(el, origin) {
  226. var offset = el.offset();
  227. var scrollbarWidths = getScrollbarWidths(el);
  228. var left = offset.left + getCssFloat(el, 'border-left-width') + scrollbarWidths.left - (origin ? origin.left : 0);
  229. var top = offset.top + getCssFloat(el, 'border-top-width') + scrollbarWidths.top - (origin ? origin.top : 0);
  230. return {
  231. left: left,
  232. right: left + el[0].clientWidth, // clientWidth includes padding but NOT scrollbars
  233. top: top,
  234. bottom: top + el[0].clientHeight // clientHeight includes padding but NOT scrollbars
  235. };
  236. }
  237. // Queries the area within the margin/border/padding of a jQuery element. Assumed not to have scrollbars.
  238. // Returns a rectangle with absolute coordinates: left, right (exclusive), top, bottom (exclusive).
  239. // Origin is optional.
  240. function getContentRect(el, origin) {
  241. var offset = el.offset(); // just outside of border, margin not included
  242. var left = offset.left + getCssFloat(el, 'border-left-width') + getCssFloat(el, 'padding-left') -
  243. (origin ? origin.left : 0);
  244. var top = offset.top + getCssFloat(el, 'border-top-width') + getCssFloat(el, 'padding-top') -
  245. (origin ? origin.top : 0);
  246. return {
  247. left: left,
  248. right: left + el.width(),
  249. top: top,
  250. bottom: top + el.height()
  251. };
  252. }
  253. // Returns the computed left/right/top/bottom scrollbar widths for the given jQuery element.
  254. // NOTE: should use clientLeft/clientTop, but very unreliable cross-browser.
  255. function getScrollbarWidths(el) {
  256. var leftRightWidth = el.innerWidth() - el[0].clientWidth; // the paddings cancel out, leaving the scrollbars
  257. var bottomWidth = el.innerHeight() - el[0].clientHeight; // "
  258. var widths;
  259. leftRightWidth = sanitizeScrollbarWidth(leftRightWidth);
  260. bottomWidth = sanitizeScrollbarWidth(bottomWidth);
  261. widths = { left: 0, right: 0, top: 0, bottom: bottomWidth };
  262. if (getIsLeftRtlScrollbars() && el.css('direction') == 'rtl') { // is the scrollbar on the left side?
  263. widths.left = leftRightWidth;
  264. }
  265. else {
  266. widths.right = leftRightWidth;
  267. }
  268. return widths;
  269. }
  270. // The scrollbar width computations in getScrollbarWidths are sometimes flawed when it comes to
  271. // retina displays, rounding, and IE11. Massage them into a usable value.
  272. function sanitizeScrollbarWidth(width) {
  273. width = Math.max(0, width); // no negatives
  274. width = Math.round(width);
  275. return width;
  276. }
  277. // Logic for determining if, when the element is right-to-left, the scrollbar appears on the left side
  278. var _isLeftRtlScrollbars = null;
  279. function getIsLeftRtlScrollbars() { // responsible for caching the computation
  280. if (_isLeftRtlScrollbars === null) {
  281. _isLeftRtlScrollbars = computeIsLeftRtlScrollbars();
  282. }
  283. return _isLeftRtlScrollbars;
  284. }
  285. function computeIsLeftRtlScrollbars() { // creates an offscreen test element, then removes it
  286. var el = $('<div><div/></div>')
  287. .css({
  288. position: 'absolute',
  289. top: -1000,
  290. left: 0,
  291. border: 0,
  292. padding: 0,
  293. overflow: 'scroll',
  294. direction: 'rtl'
  295. })
  296. .appendTo('body');
  297. var innerEl = el.children();
  298. var res = innerEl.offset().left > el.offset().left; // is the inner div shifted to accommodate a left scrollbar?
  299. el.remove();
  300. return res;
  301. }
  302. // Retrieves a jQuery element's computed CSS value as a floating-point number.
  303. // If the queried value is non-numeric (ex: IE can return "medium" for border width), will just return zero.
  304. function getCssFloat(el, prop) {
  305. return parseFloat(el.css(prop)) || 0;
  306. }
  307. /* Mouse / Touch Utilities
  308. ----------------------------------------------------------------------------------------------------------------------*/
  309. FC.preventDefault = preventDefault;
  310. // Returns a boolean whether this was a left mouse click and no ctrl key (which means right click on Mac)
  311. function isPrimaryMouseButton(ev) {
  312. return ev.which == 1 && !ev.ctrlKey;
  313. }
  314. function getEvX(ev) {
  315. var touches = ev.originalEvent.touches;
  316. // on mobile FF, pageX for touch events is present, but incorrect,
  317. // so, look at touch coordinates first.
  318. if (touches && touches.length) {
  319. return touches[0].pageX;
  320. }
  321. return ev.pageX;
  322. }
  323. function getEvY(ev) {
  324. var touches = ev.originalEvent.touches;
  325. // on mobile FF, pageX for touch events is present, but incorrect,
  326. // so, look at touch coordinates first.
  327. if (touches && touches.length) {
  328. return touches[0].pageY;
  329. }
  330. return ev.pageY;
  331. }
  332. function getEvIsTouch(ev) {
  333. return /^touch/.test(ev.type);
  334. }
  335. function preventSelection(el) {
  336. el.addClass('fc-unselectable')
  337. .on('selectstart', preventDefault);
  338. }
  339. function allowSelection(el) {
  340. el.removeClass('fc-unselectable')
  341. .off('selectstart', preventDefault);
  342. }
  343. // Stops a mouse/touch event from doing it's native browser action
  344. function preventDefault(ev) {
  345. ev.preventDefault();
  346. }
  347. /* General Geometry Utils
  348. ----------------------------------------------------------------------------------------------------------------------*/
  349. FC.intersectRects = intersectRects;
  350. // Returns a new rectangle that is the intersection of the two rectangles. If they don't intersect, returns false
  351. function intersectRects(rect1, rect2) {
  352. var res = {
  353. left: Math.max(rect1.left, rect2.left),
  354. right: Math.min(rect1.right, rect2.right),
  355. top: Math.max(rect1.top, rect2.top),
  356. bottom: Math.min(rect1.bottom, rect2.bottom)
  357. };
  358. if (res.left < res.right && res.top < res.bottom) {
  359. return res;
  360. }
  361. return false;
  362. }
  363. // Returns a new point that will have been moved to reside within the given rectangle
  364. function constrainPoint(point, rect) {
  365. return {
  366. left: Math.min(Math.max(point.left, rect.left), rect.right),
  367. top: Math.min(Math.max(point.top, rect.top), rect.bottom)
  368. };
  369. }
  370. // Returns a point that is the center of the given rectangle
  371. function getRectCenter(rect) {
  372. return {
  373. left: (rect.left + rect.right) / 2,
  374. top: (rect.top + rect.bottom) / 2
  375. };
  376. }
  377. // Subtracts point2's coordinates from point1's coordinates, returning a delta
  378. function diffPoints(point1, point2) {
  379. return {
  380. left: point1.left - point2.left,
  381. top: point1.top - point2.top
  382. };
  383. }
  384. /* Object Ordering by Field
  385. ----------------------------------------------------------------------------------------------------------------------*/
  386. FC.parseFieldSpecs = parseFieldSpecs;
  387. FC.compareByFieldSpecs = compareByFieldSpecs;
  388. FC.compareByFieldSpec = compareByFieldSpec;
  389. FC.flexibleCompare = flexibleCompare;
  390. function parseFieldSpecs(input) {
  391. var specs = [];
  392. var tokens = [];
  393. var i, token;
  394. if (typeof input === 'string') {
  395. tokens = input.split(/\s*,\s*/);
  396. }
  397. else if (typeof input === 'function') {
  398. tokens = [ input ];
  399. }
  400. else if ($.isArray(input)) {
  401. tokens = input;
  402. }
  403. for (i = 0; i < tokens.length; i++) {
  404. token = tokens[i];
  405. if (typeof token === 'string') {
  406. specs.push(
  407. token.charAt(0) == '-' ?
  408. { field: token.substring(1), order: -1 } :
  409. { field: token, order: 1 }
  410. );
  411. }
  412. else if (typeof token === 'function') {
  413. specs.push({ func: token });
  414. }
  415. }
  416. return specs;
  417. }
  418. function compareByFieldSpecs(obj1, obj2, fieldSpecs) {
  419. var i;
  420. var cmp;
  421. for (i = 0; i < fieldSpecs.length; i++) {
  422. cmp = compareByFieldSpec(obj1, obj2, fieldSpecs[i]);
  423. if (cmp) {
  424. return cmp;
  425. }
  426. }
  427. return 0;
  428. }
  429. function compareByFieldSpec(obj1, obj2, fieldSpec) {
  430. if (fieldSpec.func) {
  431. return fieldSpec.func(obj1, obj2);
  432. }
  433. return flexibleCompare(obj1[fieldSpec.field], obj2[fieldSpec.field]) *
  434. (fieldSpec.order || 1);
  435. }
  436. function flexibleCompare(a, b) {
  437. if (!a && !b) {
  438. return 0;
  439. }
  440. if (b == null) {
  441. return -1;
  442. }
  443. if (a == null) {
  444. return 1;
  445. }
  446. if ($.type(a) === 'string' || $.type(b) === 'string') {
  447. return String(a).localeCompare(String(b));
  448. }
  449. return a - b;
  450. }
  451. /* FullCalendar-specific Misc Utilities
  452. ----------------------------------------------------------------------------------------------------------------------*/
  453. // Computes the intersection of the two ranges. Will return fresh date clones in a range.
  454. // Returns undefined if no intersection.
  455. // Expects all dates to be normalized to the same timezone beforehand.
  456. // TODO: move to date section?
  457. function intersectRanges(subjectRange, constraintRange) {
  458. var subjectStart = subjectRange.start;
  459. var subjectEnd = subjectRange.end;
  460. var constraintStart = constraintRange.start;
  461. var constraintEnd = constraintRange.end;
  462. var segStart, segEnd;
  463. var isStart, isEnd;
  464. if (subjectEnd > constraintStart && subjectStart < constraintEnd) { // in bounds at all?
  465. if (subjectStart >= constraintStart) {
  466. segStart = subjectStart.clone();
  467. isStart = true;
  468. }
  469. else {
  470. segStart = constraintStart.clone();
  471. isStart = false;
  472. }
  473. if (subjectEnd <= constraintEnd) {
  474. segEnd = subjectEnd.clone();
  475. isEnd = true;
  476. }
  477. else {
  478. segEnd = constraintEnd.clone();
  479. isEnd = false;
  480. }
  481. return {
  482. start: segStart,
  483. end: segEnd,
  484. isStart: isStart,
  485. isEnd: isEnd
  486. };
  487. }
  488. }
  489. /* Date Utilities
  490. ----------------------------------------------------------------------------------------------------------------------*/
  491. FC.computeIntervalUnit = computeIntervalUnit;
  492. FC.divideRangeByDuration = divideRangeByDuration;
  493. FC.divideDurationByDuration = divideDurationByDuration;
  494. FC.multiplyDuration = multiplyDuration;
  495. FC.durationHasTime = durationHasTime;
  496. var dayIDs = [ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ];
  497. var intervalUnits = [ 'year', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond' ];
  498. // Diffs the two moments into a Duration where full-days are recorded first, then the remaining time.
  499. // Moments will have their timezones normalized.
  500. function diffDayTime(a, b) {
  501. return moment.duration({
  502. days: a.clone().stripTime().diff(b.clone().stripTime(), 'days'),
  503. ms: a.time() - b.time() // time-of-day from day start. disregards timezone
  504. });
  505. }
  506. // Diffs the two moments via their start-of-day (regardless of timezone). Produces whole-day durations.
  507. function diffDay(a, b) {
  508. return moment.duration({
  509. days: a.clone().stripTime().diff(b.clone().stripTime(), 'days')
  510. });
  511. }
  512. // Diffs two moments, producing a duration, made of a whole-unit-increment of the given unit. Uses rounding.
  513. function diffByUnit(a, b, unit) {
  514. return moment.duration(
  515. Math.round(a.diff(b, unit, true)), // returnFloat=true
  516. unit
  517. );
  518. }
  519. // Computes the unit name of the largest whole-unit period of time.
  520. // For example, 48 hours will be "days" whereas 49 hours will be "hours".
  521. // Accepts start/end, a range object, or an original duration object.
  522. function computeIntervalUnit(start, end) {
  523. var i, unit;
  524. var val;
  525. for (i = 0; i < intervalUnits.length; i++) {
  526. unit = intervalUnits[i];
  527. val = computeRangeAs(unit, start, end);
  528. if (val >= 1 && isInt(val)) {
  529. break;
  530. }
  531. }
  532. return unit; // will be "milliseconds" if nothing else matches
  533. }
  534. // Computes the number of units (like "hours") in the given range.
  535. // Range can be a {start,end} object, separate start/end args, or a Duration.
  536. // Results are based on Moment's .as() and .diff() methods, so results can depend on internal handling
  537. // of month-diffing logic (which tends to vary from version to version).
  538. function computeRangeAs(unit, start, end) {
  539. if (end != null) { // given start, end
  540. return end.diff(start, unit, true);
  541. }
  542. else if (moment.isDuration(start)) { // given duration
  543. return start.as(unit);
  544. }
  545. else { // given { start, end } range object
  546. return start.end.diff(start.start, unit, true);
  547. }
  548. }
  549. // Intelligently divides a range (specified by a start/end params) by a duration
  550. function divideRangeByDuration(start, end, dur) {
  551. var months;
  552. if (durationHasTime(dur)) {
  553. return (end - start) / dur;
  554. }
  555. months = dur.asMonths();
  556. if (Math.abs(months) >= 1 && isInt(months)) {
  557. return end.diff(start, 'months', true) / months;
  558. }
  559. return end.diff(start, 'days', true) / dur.asDays();
  560. }
  561. // Intelligently divides one duration by another
  562. function divideDurationByDuration(dur1, dur2) {
  563. var months1, months2;
  564. if (durationHasTime(dur1) || durationHasTime(dur2)) {
  565. return dur1 / dur2;
  566. }
  567. months1 = dur1.asMonths();
  568. months2 = dur2.asMonths();
  569. if (
  570. Math.abs(months1) >= 1 && isInt(months1) &&
  571. Math.abs(months2) >= 1 && isInt(months2)
  572. ) {
  573. return months1 / months2;
  574. }
  575. return dur1.asDays() / dur2.asDays();
  576. }
  577. // Intelligently multiplies a duration by a number
  578. function multiplyDuration(dur, n) {
  579. var months;
  580. if (durationHasTime(dur)) {
  581. return moment.duration(dur * n);
  582. }
  583. months = dur.asMonths();
  584. if (Math.abs(months) >= 1 && isInt(months)) {
  585. return moment.duration({ months: months * n });
  586. }
  587. return moment.duration({ days: dur.asDays() * n });
  588. }
  589. // Returns a boolean about whether the given duration has any time parts (hours/minutes/seconds/ms)
  590. function durationHasTime(dur) {
  591. return Boolean(dur.hours() || dur.minutes() || dur.seconds() || dur.milliseconds());
  592. }
  593. function isNativeDate(input) {
  594. return Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date;
  595. }
  596. // Returns a boolean about whether the given input is a time string, like "06:40:00" or "06:00"
  597. function isTimeString(str) {
  598. return /^\d+\:\d+(?:\:\d+\.?(?:\d{3})?)?$/.test(str);
  599. }
  600. /* Logging and Debug
  601. ----------------------------------------------------------------------------------------------------------------------*/
  602. FC.log = function() {
  603. var console = window.console;
  604. if (console && console.log) {
  605. return console.log.apply(console, arguments);
  606. }
  607. };
  608. FC.warn = function() {
  609. var console = window.console;
  610. if (console && console.warn) {
  611. return console.warn.apply(console, arguments);
  612. }
  613. else {
  614. return FC.log.apply(FC, arguments);
  615. }
  616. };
  617. /* General Utilities
  618. ----------------------------------------------------------------------------------------------------------------------*/
  619. var hasOwnPropMethod = {}.hasOwnProperty;
  620. // Merges an array of objects into a single object.
  621. // The second argument allows for an array of property names who's object values will be merged together.
  622. function mergeProps(propObjs, complexProps) {
  623. var dest = {};
  624. var i, name;
  625. var complexObjs;
  626. var j, val;
  627. var props;
  628. if (complexProps) {
  629. for (i = 0; i < complexProps.length; i++) {
  630. name = complexProps[i];
  631. complexObjs = [];
  632. // collect the trailing object values, stopping when a non-object is discovered
  633. for (j = propObjs.length - 1; j >= 0; j--) {
  634. val = propObjs[j][name];
  635. if (typeof val === 'object') {
  636. complexObjs.unshift(val);
  637. }
  638. else if (val !== undefined) {
  639. dest[name] = val; // if there were no objects, this value will be used
  640. break;
  641. }
  642. }
  643. // if the trailing values were objects, use the merged value
  644. if (complexObjs.length) {
  645. dest[name] = mergeProps(complexObjs);
  646. }
  647. }
  648. }
  649. // copy values into the destination, going from last to first
  650. for (i = propObjs.length - 1; i >= 0; i--) {
  651. props = propObjs[i];
  652. for (name in props) {
  653. if (!(name in dest)) { // if already assigned by previous props or complex props, don't reassign
  654. dest[name] = props[name];
  655. }
  656. }
  657. }
  658. return dest;
  659. }
  660. // Create an object that has the given prototype. Just like Object.create
  661. function createObject(proto) {
  662. var f = function() {};
  663. f.prototype = proto;
  664. return new f();
  665. }
  666. FC.createObject = createObject;
  667. function copyOwnProps(src, dest) {
  668. for (var name in src) {
  669. if (hasOwnProp(src, name)) {
  670. dest[name] = src[name];
  671. }
  672. }
  673. }
  674. function hasOwnProp(obj, name) {
  675. return hasOwnPropMethod.call(obj, name);
  676. }
  677. // Is the given value a non-object non-function value?
  678. function isAtomic(val) {
  679. return /undefined|null|boolean|number|string/.test($.type(val));
  680. }
  681. function applyAll(functions, thisObj, args) {
  682. if ($.isFunction(functions)) {
  683. functions = [ functions ];
  684. }
  685. if (functions) {
  686. var i;
  687. var ret;
  688. for (i=0; i<functions.length; i++) {
  689. ret = functions[i].apply(thisObj, args) || ret;
  690. }
  691. return ret;
  692. }
  693. }
  694. function firstDefined() {
  695. for (var i=0; i<arguments.length; i++) {
  696. if (arguments[i] !== undefined) {
  697. return arguments[i];
  698. }
  699. }
  700. }
  701. function htmlEscape(s) {
  702. return (s + '').replace(/&/g, '&amp;')
  703. .replace(/</g, '&lt;')
  704. .replace(/>/g, '&gt;')
  705. .replace(/'/g, '&#039;')
  706. .replace(/"/g, '&quot;')
  707. .replace(/\n/g, '<br />');
  708. }
  709. function stripHtmlEntities(text) {
  710. return text.replace(/&.*?;/g, '');
  711. }
  712. // Given a hash of CSS properties, returns a string of CSS.
  713. // Uses property names as-is (no camel-case conversion). Will not make statements for null/undefined values.
  714. function cssToStr(cssProps) {
  715. var statements = [];
  716. $.each(cssProps, function(name, val) {
  717. if (val != null) {
  718. statements.push(name + ':' + val);
  719. }
  720. });
  721. return statements.join(';');
  722. }
  723. // Given an object hash of HTML attribute names to values,
  724. // generates a string that can be injected between < > in HTML
  725. function attrsToStr(attrs) {
  726. var parts = [];
  727. $.each(attrs, function(name, val) {
  728. if (val != null) {
  729. parts.push(name + '="' + htmlEscape(val) + '"');
  730. }
  731. });
  732. return parts.join(' ');
  733. }
  734. function capitaliseFirstLetter(str) {
  735. return str.charAt(0).toUpperCase() + str.slice(1);
  736. }
  737. function compareNumbers(a, b) { // for .sort()
  738. return a - b;
  739. }
  740. function isInt(n) {
  741. return n % 1 === 0;
  742. }
  743. // Returns a method bound to the given object context.
  744. // Just like one of the jQuery.proxy signatures, but without the undesired behavior of treating the same method with
  745. // different contexts as identical when binding/unbinding events.
  746. function proxy(obj, methodName) {
  747. var method = obj[methodName];
  748. return function() {
  749. return method.apply(obj, arguments);
  750. };
  751. }
  752. // Returns a function, that, as long as it continues to be invoked, will not
  753. // be triggered. The function will be called after it stops being called for
  754. // N milliseconds. If `immediate` is passed, trigger the function on the
  755. // leading edge, instead of the trailing.
  756. // https://github.com/jashkenas/underscore/blob/1.6.0/underscore.js#L714
  757. function debounce(func, wait, immediate) {
  758. var timeout, args, context, timestamp, result;
  759. var later = function() {
  760. var last = +new Date() - timestamp;
  761. if (last < wait) {
  762. timeout = setTimeout(later, wait - last);
  763. }
  764. else {
  765. timeout = null;
  766. if (!immediate) {
  767. result = func.apply(context, args);
  768. context = args = null;
  769. }
  770. }
  771. };
  772. return function() {
  773. context = this;
  774. args = arguments;
  775. timestamp = +new Date();
  776. var callNow = immediate && !timeout;
  777. if (!timeout) {
  778. timeout = setTimeout(later, wait);
  779. }
  780. if (callNow) {
  781. result = func.apply(context, args);
  782. context = args = null;
  783. }
  784. return result;
  785. };
  786. }
  787. ;;
  788. /*
  789. GENERAL NOTE on moments throughout the *entire rest* of the codebase:
  790. All moments are assumed to be ambiguously-zoned unless otherwise noted,
  791. with the NOTABLE EXCEOPTION of start/end dates that live on *Event Objects*.
  792. Ambiguously-TIMED moments are assumed to be ambiguously-zoned by nature.
  793. */
  794. var ambigDateOfMonthRegex = /^\s*\d{4}-\d\d$/;
  795. var ambigTimeOrZoneRegex =
  796. /^\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+)?)?)?)?)?$/;
  797. var newMomentProto = moment.fn; // where we will attach our new methods
  798. var oldMomentProto = $.extend({}, newMomentProto); // copy of original moment methods
  799. // tell momentjs to transfer these properties upon clone
  800. var momentProperties = moment.momentProperties;
  801. momentProperties.push('_fullCalendar');
  802. momentProperties.push('_ambigTime');
  803. momentProperties.push('_ambigZone');
  804. // Creating
  805. // -------------------------------------------------------------------------------------------------
  806. // Creates a new moment, similar to the vanilla moment(...) constructor, but with
  807. // extra features (ambiguous time, enhanced formatting). When given an existing moment,
  808. // it will function as a clone (and retain the zone of the moment). Anything else will
  809. // result in a moment in the local zone.
  810. FC.moment = function() {
  811. return makeMoment(arguments);
  812. };
  813. // Sames as FC.moment, but forces the resulting moment to be in the UTC timezone.
  814. FC.moment.utc = function() {
  815. var mom = makeMoment(arguments, true);
  816. // Force it into UTC because makeMoment doesn't guarantee it
  817. // (if given a pre-existing moment for example)
  818. if (mom.hasTime()) { // don't give ambiguously-timed moments a UTC zone
  819. mom.utc();
  820. }
  821. return mom;
  822. };
  823. // Same as FC.moment, but when given an ISO8601 string, the timezone offset is preserved.
  824. // ISO8601 strings with no timezone offset will become ambiguously zoned.
  825. FC.moment.parseZone = function() {
  826. return makeMoment(arguments, true, true);
  827. };
  828. // Builds an enhanced moment from args. When given an existing moment, it clones. When given a
  829. // native Date, or called with no arguments (the current time), the resulting moment will be local.
  830. // Anything else needs to be "parsed" (a string or an array), and will be affected by:
  831. // parseAsUTC - if there is no zone information, should we parse the input in UTC?
  832. // parseZone - if there is zone information, should we force the zone of the moment?
  833. function makeMoment(args, parseAsUTC, parseZone) {
  834. var input = args[0];
  835. var isSingleString = args.length == 1 && typeof input === 'string';
  836. var isAmbigTime;
  837. var isAmbigZone;
  838. var ambigMatch;
  839. var mom;
  840. if (moment.isMoment(input) || isNativeDate(input) || input === undefined) {
  841. mom = moment.apply(null, args);
  842. }
  843. else { // "parsing" is required
  844. isAmbigTime = false;
  845. isAmbigZone = false;
  846. if (isSingleString) {
  847. if (ambigDateOfMonthRegex.test(input)) {
  848. // accept strings like '2014-05', but convert to the first of the month
  849. input += '-01';
  850. args = [ input ]; // for when we pass it on to moment's constructor
  851. isAmbigTime = true;
  852. isAmbigZone = true;
  853. }
  854. else if ((ambigMatch = ambigTimeOrZoneRegex.exec(input))) {
  855. isAmbigTime = !ambigMatch[5]; // no time part?
  856. isAmbigZone = true;
  857. }
  858. }
  859. else if ($.isArray(input)) {
  860. // arrays have no timezone information, so assume ambiguous zone
  861. isAmbigZone = true;
  862. }
  863. // otherwise, probably a string with a format
  864. if (parseAsUTC || isAmbigTime) {
  865. mom = moment.utc.apply(moment, args);
  866. }
  867. else {
  868. mom = moment.apply(null, args);
  869. }
  870. if (isAmbigTime) {
  871. mom._ambigTime = true;
  872. mom._ambigZone = true; // ambiguous time always means ambiguous zone
  873. }
  874. else if (parseZone) { // let's record the inputted zone somehow
  875. if (isAmbigZone) {
  876. mom._ambigZone = true;
  877. }
  878. else if (isSingleString) {
  879. mom.utcOffset(input); // if not a valid zone, will assign UTC
  880. }
  881. }
  882. }
  883. mom._fullCalendar = true; // flag for extended functionality
  884. return mom;
  885. }
  886. // Week Number
  887. // -------------------------------------------------------------------------------------------------
  888. // Returns the week number, considering the locale's custom week number calcuation
  889. // `weeks` is an alias for `week`
  890. newMomentProto.week = newMomentProto.weeks = function(input) {
  891. var weekCalc = this._locale._fullCalendar_weekCalc;
  892. if (input == null && typeof weekCalc === 'function') { // custom function only works for getter
  893. return weekCalc(this);
  894. }
  895. else if (weekCalc === 'ISO') {
  896. return oldMomentProto.isoWeek.apply(this, arguments); // ISO getter/setter
  897. }
  898. return oldMomentProto.week.apply(this, arguments); // local getter/setter
  899. };
  900. // Time-of-day
  901. // -------------------------------------------------------------------------------------------------
  902. // GETTER
  903. // Returns a Duration with the hours/minutes/seconds/ms values of the moment.
  904. // If the moment has an ambiguous time, a duration of 00:00 will be returned.
  905. //
  906. // SETTER
  907. // You can supply a Duration, a Moment, or a Duration-like argument.
  908. // When setting the time, and the moment has an ambiguous time, it then becomes unambiguous.
  909. newMomentProto.time = function(time) {
  910. // Fallback to the original method (if there is one) if this moment wasn't created via FullCalendar.
  911. // `time` is a generic enough method name where this precaution is necessary to avoid collisions w/ other plugins.
  912. if (!this._fullCalendar) {
  913. return oldMomentProto.time.apply(this, arguments);
  914. }
  915. if (time == null) { // getter
  916. return moment.duration({
  917. hours: this.hours(),
  918. minutes: this.minutes(),
  919. seconds: this.seconds(),
  920. milliseconds: this.milliseconds()
  921. });
  922. }
  923. else { // setter
  924. this._ambigTime = false; // mark that the moment now has a time
  925. if (!moment.isDuration(time) && !moment.isMoment(time)) {
  926. time = moment.duration(time);
  927. }
  928. // The day value should cause overflow (so 24 hours becomes 00:00:00 of next day).
  929. // Only for Duration times, not Moment times.
  930. var dayHours = 0;
  931. if (moment.isDuration(time)) {
  932. dayHours = Math.floor(time.asDays()) * 24;
  933. }
  934. // We need to set the individual fields.
  935. // Can't use startOf('day') then add duration. In case of DST at start of day.
  936. return this.hours(dayHours + time.hours())
  937. .minutes(time.minutes())
  938. .seconds(time.seconds())
  939. .milliseconds(time.milliseconds());
  940. }
  941. };
  942. // Converts the moment to UTC, stripping out its time-of-day and timezone offset,
  943. // but preserving its YMD. A moment with a stripped time will display no time
  944. // nor timezone offset when .format() is called.
  945. newMomentProto.stripTime = function() {
  946. if (!this._ambigTime) {
  947. this.utc(true); // keepLocalTime=true (for keeping *date* value)
  948. // set time to zero
  949. this.set({
  950. hours: 0,
  951. minutes: 0,
  952. seconds: 0,
  953. ms: 0
  954. });
  955. // Mark the time as ambiguous. This needs to happen after the .utc() call, which might call .utcOffset(),
  956. // which clears all ambig flags.
  957. this._ambigTime = true;
  958. this._ambigZone = true; // if ambiguous time, also ambiguous timezone offset
  959. }
  960. return this; // for chaining
  961. };
  962. // Returns if the moment has a non-ambiguous time (boolean)
  963. newMomentProto.hasTime = function() {
  964. return !this._ambigTime;
  965. };
  966. // Timezone
  967. // -------------------------------------------------------------------------------------------------
  968. // Converts the moment to UTC, stripping out its timezone offset, but preserving its
  969. // YMD and time-of-day. A moment with a stripped timezone offset will display no
  970. // timezone offset when .format() is called.
  971. newMomentProto.stripZone = function() {
  972. var wasAmbigTime;
  973. if (!this._ambigZone) {
  974. wasAmbigTime = this._ambigTime;
  975. this.utc(true); // keepLocalTime=true (for keeping date and time values)
  976. // the above call to .utc()/.utcOffset() unfortunately might clear the ambig flags, so restore
  977. this._ambigTime = wasAmbigTime || false;
  978. // Mark the zone as ambiguous. This needs to happen after the .utc() call, which might call .utcOffset(),
  979. // which clears the ambig flags.
  980. this._ambigZone = true;
  981. }
  982. return this; // for chaining
  983. };
  984. // Returns of the moment has a non-ambiguous timezone offset (boolean)
  985. newMomentProto.hasZone = function() {
  986. return !this._ambigZone;
  987. };
  988. // implicitly marks a zone
  989. newMomentProto.local = function(keepLocalTime) {
  990. // for when converting from ambiguously-zoned to local,
  991. // keep the time values when converting from UTC -> local
  992. oldMomentProto.local.call(this, this._ambigZone || keepLocalTime);
  993. // ensure non-ambiguous
  994. // this probably already happened via local() -> utcOffset(), but don't rely on Moment's internals
  995. this._ambigTime = false;
  996. this._ambigZone = false;
  997. return this; // for chaining
  998. };
  999. // implicitly marks a zone
  1000. newMomentProto.utc = function(keepLocalTime) {
  1001. oldMomentProto.utc.call(this, keepLocalTime);
  1002. // ensure non-ambiguous
  1003. // this probably already happened via utc() -> utcOffset(), but don't rely on Moment's internals
  1004. this._ambigTime = false;
  1005. this._ambigZone = false;
  1006. return this;
  1007. };
  1008. // implicitly marks a zone (will probably get called upon .utc() and .local())
  1009. newMomentProto.utcOffset = function(tzo) {
  1010. if (tzo != null) { // setter
  1011. // these assignments needs to happen before the original zone method is called.
  1012. // I forget why, something to do with a browser crash.
  1013. this._ambigTime = false;
  1014. this._ambigZone = false;
  1015. }
  1016. return oldMomentProto.utcOffset.apply(this, arguments);
  1017. };
  1018. // Formatting
  1019. // -------------------------------------------------------------------------------------------------
  1020. newMomentProto.format = function() {
  1021. if (this._fullCalendar && arguments[0]) { // an enhanced moment? and a format string provided?
  1022. return formatDate(this, arguments[0]); // our extended formatting
  1023. }
  1024. if (this._ambigTime) {
  1025. return oldMomentFormat(this, 'YYYY-MM-DD');
  1026. }
  1027. if (this._ambigZone) {
  1028. return oldMomentFormat(this, 'YYYY-MM-DD[T]HH:mm:ss');
  1029. }
  1030. return oldMomentProto.format.apply(this, arguments);
  1031. };
  1032. newMomentProto.toISOString = function() {
  1033. if (this._ambigTime) {
  1034. return oldMomentFormat(this, 'YYYY-MM-DD');
  1035. }
  1036. if (this._ambigZone) {
  1037. return oldMomentFormat(this, 'YYYY-MM-DD[T]HH:mm:ss');
  1038. }
  1039. return oldMomentProto.toISOString.apply(this, arguments);
  1040. };
  1041. ;;
  1042. (function() {
  1043. // exports
  1044. FC.formatDate = formatDate;
  1045. FC.formatRange = formatRange;
  1046. FC.oldMomentFormat = oldMomentFormat;
  1047. FC.queryMostGranularFormatUnit = queryMostGranularFormatUnit;
  1048. // Config
  1049. // ---------------------------------------------------------------------------------------------------------------------
  1050. /*
  1051. Inserted between chunks in the fake ("intermediate") formatting string.
  1052. Important that it passes as whitespace (\s) because moment often identifies non-standalone months
  1053. via a regexp with an \s.
  1054. */
  1055. var PART_SEPARATOR = '\u000b'; // vertical tab
  1056. /*
  1057. Inserted as the first character of a literal-text chunk to indicate that the literal text is not actually literal text,
  1058. but rather, a "special" token that has custom rendering (see specialTokens map).
  1059. */
  1060. var SPECIAL_TOKEN_MARKER = '\u001f'; // information separator 1
  1061. /*
  1062. Inserted at the beginning and end of a span of text that must have non-zero numeric characters.
  1063. Handling of these markers is done in a post-processing step at the very end of text rendering.
  1064. */
  1065. var MAYBE_MARKER = '\u001e'; // information separator 2
  1066. var MAYBE_REGEXP = new RegExp(MAYBE_MARKER + '([^' + MAYBE_MARKER + ']*)' + MAYBE_MARKER, 'g'); // must be global
  1067. /*
  1068. Addition formatting tokens we want recognized
  1069. */
  1070. var specialTokens = {
  1071. t: function(date) { // "a" or "p"
  1072. return oldMomentFormat(date, 'a').charAt(0);
  1073. },
  1074. T: function(date) { // "A" or "P"
  1075. return oldMomentFormat(date, 'A').charAt(0);
  1076. }
  1077. };
  1078. /*
  1079. The first characters of formatting tokens for units that are 1 day or larger.
  1080. `value` is for ranking relative size (lower means bigger).
  1081. `unit` is a normalized unit, used for comparing moments.
  1082. */
  1083. var largeTokenMap = {
  1084. Y: { value: 1, unit: 'year' },
  1085. M: { value: 2, unit: 'month' },
  1086. W: { value: 3, unit: 'week' }, // ISO week
  1087. w: { value: 3, unit: 'week' }, // local week
  1088. D: { value: 4, unit: 'day' }, // day of month
  1089. d: { value: 4, unit: 'day' } // day of week
  1090. };
  1091. // Single Date Formatting
  1092. // ---------------------------------------------------------------------------------------------------------------------
  1093. /*
  1094. Formats `date` with a Moment formatting string, but allow our non-zero areas and special token
  1095. */
  1096. function formatDate(date, formatStr) {
  1097. return renderFakeFormatString(
  1098. getParsedFormatString(formatStr).fakeFormatString,
  1099. date
  1100. );
  1101. }
  1102. /*
  1103. Call this if you want Moment's original format method to be used
  1104. */
  1105. function oldMomentFormat(mom, formatStr) {
  1106. return oldMomentProto.format.call(mom, formatStr); // oldMomentProto defined in moment-ext.js
  1107. }
  1108. // Date Range Formatting
  1109. // -------------------------------------------------------------------------------------------------
  1110. // TODO: make it work with timezone offset
  1111. /*
  1112. Using a formatting string meant for a single date, generate a range string, like
  1113. "Sep 2 - 9 2013", that intelligently inserts a separator where the dates differ.
  1114. If the dates are the same as far as the format string is concerned, just return a single
  1115. rendering of one date, without any separator.
  1116. */
  1117. function formatRange(date1, date2, formatStr, separator, isRTL) {
  1118. var localeData;
  1119. date1 = FC.moment.parseZone(date1);
  1120. date2 = FC.moment.parseZone(date2);
  1121. localeData = date1.localeData();
  1122. // Expand localized format strings, like "LL" -> "MMMM D YYYY".
  1123. // BTW, this is not important for `formatDate` because it is impossible to put custom tokens
  1124. // or non-zero areas in Moment's localized format strings.
  1125. formatStr = localeData.longDateFormat(formatStr) || formatStr;
  1126. return renderParsedFormat(
  1127. getParsedFormatString(formatStr),
  1128. date1,
  1129. date2,
  1130. separator || ' - ',
  1131. isRTL
  1132. );
  1133. }
  1134. /*
  1135. Renders a range with an already-parsed format string.
  1136. */
  1137. function renderParsedFormat(parsedFormat, date1, date2, separator, isRTL) {
  1138. var sameUnits = parsedFormat.sameUnits;
  1139. var unzonedDate1 = date1.clone().stripZone(); // for same-unit comparisons
  1140. var unzonedDate2 = date2.clone().stripZone(); // "
  1141. var renderedParts1 = renderFakeFormatStringParts(parsedFormat.fakeFormatString, date1);
  1142. var renderedParts2 = renderFakeFormatStringParts(parsedFormat.fakeFormatString, date2);
  1143. var leftI;
  1144. var leftStr = '';
  1145. var rightI;
  1146. var rightStr = '';
  1147. var middleI;
  1148. var middleStr1 = '';
  1149. var middleStr2 = '';
  1150. var middleStr = '';
  1151. // Start at the leftmost side of the formatting string and continue until you hit a token
  1152. // that is not the same between dates.
  1153. for (
  1154. leftI = 0;
  1155. leftI < sameUnits.length && (!sameUnits[leftI] || unzonedDate1.isSame(unzonedDate2, sameUnits[leftI]));
  1156. leftI++
  1157. ) {
  1158. leftStr += renderedParts1[leftI];
  1159. }
  1160. // Similarly, start at the rightmost side of the formatting string and move left
  1161. for (
  1162. rightI = sameUnits.length - 1;
  1163. rightI > leftI && (!sameUnits[rightI] || unzonedDate1.isSame(unzonedDate2, sameUnits[rightI]));
  1164. rightI--
  1165. ) {
  1166. // If current chunk is on the boundary of unique date-content, and is a special-case
  1167. // date-formatting postfix character, then don't consume it. Consider it unique date-content.
  1168. // TODO: make configurable
  1169. if (rightI - 1 === leftI && renderedParts1[rightI] === '.') {
  1170. break;
  1171. }
  1172. rightStr = renderedParts1[rightI] + rightStr;
  1173. }
  1174. // The area in the middle is different for both of the dates.
  1175. // Collect them distinctly so we can jam them together later.
  1176. for (middleI = leftI; middleI <= rightI; middleI++) {
  1177. middleStr1 += renderedParts1[middleI];
  1178. middleStr2 += renderedParts2[middleI];
  1179. }
  1180. if (middleStr1 || middleStr2) {
  1181. if (isRTL) {
  1182. middleStr = middleStr2 + separator + middleStr1;
  1183. }
  1184. else {
  1185. middleStr = middleStr1 + separator + middleStr2;
  1186. }
  1187. }
  1188. return processMaybeMarkers(
  1189. leftStr + middleStr + rightStr
  1190. );
  1191. }
  1192. // Format String Parsing
  1193. // ---------------------------------------------------------------------------------------------------------------------
  1194. var parsedFormatStrCache = {};
  1195. /*
  1196. Returns a parsed format string, leveraging a cache.
  1197. */
  1198. function getParsedFormatString(formatStr) {
  1199. return parsedFormatStrCache[formatStr] ||
  1200. (parsedFormatStrCache[formatStr] = parseFormatString(formatStr));
  1201. }
  1202. /*
  1203. Parses a format string into the following:
  1204. - fakeFormatString: a momentJS formatting string, littered with special control characters that get post-processed.
  1205. - sameUnits: for every part in fakeFormatString, if the part is a token, the value will be a unit string (like "day"),
  1206. that indicates how similar a range's start & end must be in order to share the same formatted text.
  1207. If not a token, then the value is null.
  1208. Always a flat array (not nested liked "chunks").
  1209. */
  1210. function parseFormatString(formatStr) {
  1211. var chunks = chunkFormatString(formatStr);
  1212. return {
  1213. fakeFormatString: buildFakeFormatString(chunks),
  1214. sameUnits: buildSameUnits(chunks)
  1215. };
  1216. }
  1217. /*
  1218. Break the formatting string into an array of chunks.
  1219. A 'maybe' chunk will have nested chunks.
  1220. */
  1221. function chunkFormatString(formatStr) {
  1222. var chunks = [];
  1223. var match;
  1224. // TODO: more descrimination
  1225. // \4 is a backreference to the first character of a multi-character set.
  1226. var chunker = /\[([^\]]*)\]|\(([^\)]*)\)|(LTS|LT|(\w)\4*o?)|([^\w\[\(]+)/g;
  1227. while ((match = chunker.exec(formatStr))) {
  1228. if (match[1]) { // a literal string inside [ ... ]
  1229. chunks.push.apply(chunks, // append
  1230. splitStringLiteral(match[1])
  1231. );
  1232. }
  1233. else if (match[2]) { // non-zero formatting inside ( ... )
  1234. chunks.push({ maybe: chunkFormatString(match[2]) });
  1235. }
  1236. else if (match[3]) { // a formatting token
  1237. chunks.push({ token: match[3] });
  1238. }
  1239. else if (match[5]) { // an unenclosed literal string
  1240. chunks.push.apply(chunks, // append
  1241. splitStringLiteral(match[5])
  1242. );
  1243. }
  1244. }
  1245. return chunks;
  1246. }
  1247. /*
  1248. Potentially splits a literal-text string into multiple parts. For special cases.
  1249. */
  1250. function splitStringLiteral(s) {
  1251. if (s === '. ') {
  1252. return [ '.', ' ' ]; // for locales with periods bound to the end of each year/month/date
  1253. }
  1254. else {
  1255. return [ s ];
  1256. }
  1257. }
  1258. /*
  1259. Given chunks parsed from a real format string, generate a fake (aka "intermediate") format string with special control
  1260. characters that will eventually be given to moment for formatting, and then post-processed.
  1261. */
  1262. function buildFakeFormatString(chunks) {
  1263. var parts = [];
  1264. var i, chunk;
  1265. for (i = 0; i < chunks.length; i++) {
  1266. chunk = chunks[i];
  1267. if (typeof chunk === 'string') {
  1268. parts.push('[' + chunk + ']');
  1269. }
  1270. else if (chunk.token) {
  1271. if (chunk.token in specialTokens) {
  1272. parts.push(
  1273. SPECIAL_TOKEN_MARKER + // useful during post-processing
  1274. '[' + chunk.token + ']' // preserve as literal text
  1275. );
  1276. }
  1277. else {
  1278. parts.push(chunk.token); // unprotected text implies a format string
  1279. }
  1280. }
  1281. else if (chunk.maybe) {
  1282. parts.push(
  1283. MAYBE_MARKER + // useful during post-processing
  1284. buildFakeFormatString(chunk.maybe) +
  1285. MAYBE_MARKER
  1286. );
  1287. }
  1288. }
  1289. return parts.join(PART_SEPARATOR);
  1290. }
  1291. /*
  1292. Given parsed chunks from a real formatting string, generates an array of unit strings (like "day") that indicate
  1293. in which regard two dates must be similar in order to share range formatting text.
  1294. The `chunks` can be nested (because of "maybe" chunks), however, the returned array will be flat.
  1295. */
  1296. function buildSameUnits(chunks) {
  1297. var units = [];
  1298. var i, chunk;
  1299. var tokenInfo;
  1300. for (i = 0; i < chunks.length; i++) {
  1301. chunk = chunks[i];
  1302. if (chunk.token) {
  1303. tokenInfo = largeTokenMap[chunk.token.charAt(0)];
  1304. units.push(tokenInfo ? tokenInfo.unit : 'second'); // default to a very strict same-second
  1305. }
  1306. else if (chunk.maybe) {
  1307. units.push.apply(units, // append
  1308. buildSameUnits(chunk.maybe)
  1309. );
  1310. }
  1311. else {
  1312. units.push(null);
  1313. }
  1314. }
  1315. return units;
  1316. }
  1317. // Rendering to text
  1318. // ---------------------------------------------------------------------------------------------------------------------
  1319. /*
  1320. Formats a date with a fake format string, post-processes the control characters, then returns.
  1321. */
  1322. function renderFakeFormatString(fakeFormatString, date) {
  1323. return processMaybeMarkers(
  1324. renderFakeFormatStringParts(fakeFormatString, date).join('')
  1325. );
  1326. }
  1327. /*
  1328. Formats a date into parts that will have been post-processed, EXCEPT for the "maybe" markers.
  1329. */
  1330. function renderFakeFormatStringParts(fakeFormatString, date) {
  1331. var parts = [];
  1332. var fakeRender = oldMomentFormat(date, fakeFormatString);
  1333. var fakeParts = fakeRender.split(PART_SEPARATOR);
  1334. var i, fakePart;
  1335. for (i = 0; i < fakeParts.length; i++) {
  1336. fakePart = fakeParts[i];
  1337. if (fakePart.charAt(0) === SPECIAL_TOKEN_MARKER) {
  1338. parts.push(
  1339. // the literal string IS the token's name.
  1340. // call special token's registered function.
  1341. specialTokens[fakePart.substring(1)](date)
  1342. );
  1343. }
  1344. else {
  1345. parts.push(fakePart);
  1346. }
  1347. }
  1348. return parts;
  1349. }
  1350. /*
  1351. Accepts an almost-finally-formatted string and processes the "maybe" control characters, returning a new string.
  1352. */
  1353. function processMaybeMarkers(s) {
  1354. return s.replace(MAYBE_REGEXP, function(m0, m1) { // regex assumed to have 'g' flag
  1355. if (m1.match(/[1-9]/)) { // any non-zero numeric characters?
  1356. return m1;
  1357. }
  1358. else {
  1359. return '';
  1360. }
  1361. });
  1362. }
  1363. // Misc Utils
  1364. // -------------------------------------------------------------------------------------------------
  1365. /*
  1366. Returns a unit string, either 'year', 'month', 'day', or null for the most granular formatting token in the string.
  1367. */
  1368. function queryMostGranularFormatUnit(formatStr) {
  1369. var chunks = chunkFormatString(formatStr);
  1370. var i, chunk;
  1371. var candidate;
  1372. var best;
  1373. for (i = 0; i < chunks.length; i++) {
  1374. chunk = chunks[i];
  1375. if (chunk.token) {
  1376. candidate = largeTokenMap[chunk.token.charAt(0)];
  1377. if (candidate) {
  1378. if (!best || candidate.value > best.value) {
  1379. best = candidate;
  1380. }
  1381. }
  1382. }
  1383. }
  1384. if (best) {
  1385. return best.unit;
  1386. }
  1387. return null;
  1388. };
  1389. })();
  1390. // quick local references
  1391. var formatDate = FC.formatDate;
  1392. var formatRange = FC.formatRange;
  1393. var oldMomentFormat = FC.oldMomentFormat;
  1394. ;;
  1395. FC.Class = Class; // export
  1396. // Class that all other classes will inherit from
  1397. function Class() { }
  1398. // Called on a class to create a subclass.
  1399. // Last argument contains instance methods. Any argument before the last are considered mixins.
  1400. Class.extend = function() {
  1401. var len = arguments.length;
  1402. var i;
  1403. var members;
  1404. for (i = 0; i < len; i++) {
  1405. members = arguments[i];
  1406. if (i < len - 1) { // not the last argument?
  1407. mixIntoClass(this, members);
  1408. }
  1409. }
  1410. return extendClass(this, members || {}); // members will be undefined if no arguments
  1411. };
  1412. // Adds new member variables/methods to the class's prototype.
  1413. // Can be called with another class, or a plain object hash containing new members.
  1414. Class.mixin = function(members) {
  1415. mixIntoClass(this, members);
  1416. };
  1417. function extendClass(superClass, members) {
  1418. var subClass;
  1419. // ensure a constructor for the subclass, forwarding all arguments to the super-constructor if it doesn't exist
  1420. if (hasOwnProp(members, 'constructor')) {
  1421. subClass = members.constructor;
  1422. }
  1423. if (typeof subClass !== 'function') {
  1424. subClass = members.constructor = function() {
  1425. superClass.apply(this, arguments);
  1426. };
  1427. }
  1428. // build the base prototype for the subclass, which is an new object chained to the superclass's prototype
  1429. subClass.prototype = createObject(superClass.prototype);
  1430. // copy each member variable/method onto the the subclass's prototype
  1431. copyOwnProps(members, subClass.prototype);
  1432. // copy over all class variables/methods to the subclass, such as `extend` and `mixin`
  1433. copyOwnProps(superClass, subClass);
  1434. return subClass;
  1435. }
  1436. function mixIntoClass(theClass, members) {
  1437. copyOwnProps(members, theClass.prototype);
  1438. }
  1439. ;;
  1440. /*
  1441. Wrap jQuery's Deferred Promise object to be slightly more Promise/A+ compliant.
  1442. With the added non-standard feature of synchronously executing handlers on resolved promises,
  1443. which doesn't always happen otherwise (esp with nested .then handlers!?),
  1444. so, this makes things a lot easier, esp because jQuery 3 changed the synchronicity for Deferred objects.
  1445. TODO: write tests and more comments
  1446. */
  1447. function Promise(executor) {
  1448. var deferred = $.Deferred();
  1449. var promise = deferred.promise();
  1450. if (typeof executor === 'function') {
  1451. executor(
  1452. function(value) { // resolve
  1453. if (Promise.immediate) {
  1454. promise._value = value;
  1455. }
  1456. deferred.resolve(value);
  1457. },
  1458. function() { // reject
  1459. deferred.reject();
  1460. }
  1461. );
  1462. }
  1463. if (Promise.immediate) {
  1464. var origThen = promise.then;
  1465. promise.then = function(onFulfilled, onRejected) {
  1466. var state = promise.state();
  1467. if (state === 'resolved') {
  1468. if (typeof onFulfilled === 'function') {
  1469. return Promise.resolve(onFulfilled(promise._value));
  1470. }
  1471. }
  1472. else if (state === 'rejected') {
  1473. if (typeof onRejected === 'function') {
  1474. onRejected();
  1475. return promise; // already rejected
  1476. }
  1477. }
  1478. return origThen.call(promise, onFulfilled, onRejected);
  1479. };
  1480. }
  1481. return promise; // instanceof Promise will break :( TODO: make Promise a real class
  1482. }
  1483. FC.Promise = Promise;
  1484. Promise.immediate = true;
  1485. Promise.resolve = function(value) {
  1486. if (value && typeof value.resolve === 'function') {
  1487. return value.promise();
  1488. }
  1489. if (value && typeof value.then === 'function') {
  1490. return value;
  1491. }
  1492. else {
  1493. var deferred = $.Deferred().resolve(value);
  1494. var promise = deferred.promise();
  1495. if (Promise.immediate) {
  1496. var origThen = promise.then;
  1497. promise._value = value;
  1498. promise.then = function(onFulfilled, onRejected) {
  1499. if (typeof onFulfilled === 'function') {
  1500. return Promise.resolve(onFulfilled(value));
  1501. }
  1502. return origThen.call(promise, onFulfilled, onRejected);
  1503. };
  1504. }
  1505. return promise;
  1506. }
  1507. };
  1508. Promise.reject = function() {
  1509. return $.Deferred().reject().promise();
  1510. };
  1511. Promise.all = function(inputs) {
  1512. var hasAllValues = false;
  1513. var values;
  1514. var i, input;
  1515. if (Promise.immediate) {
  1516. hasAllValues = true;
  1517. values = [];
  1518. for (i = 0; i < inputs.length; i++) {
  1519. input = inputs[i];
  1520. if (input && typeof input.state === 'function' && input.state() === 'resolved' && ('_value' in input)) {
  1521. values.push(input._value);
  1522. }
  1523. else if (input && typeof input.then === 'function') {
  1524. hasAllValues = false;
  1525. break;
  1526. }
  1527. else {
  1528. values.push(input);
  1529. }
  1530. }
  1531. }
  1532. if (hasAllValues) {
  1533. return Promise.resolve(values);
  1534. }
  1535. else {
  1536. return $.when.apply($.when, inputs).then(function() {
  1537. return $.when($.makeArray(arguments));
  1538. });
  1539. }
  1540. };
  1541. ;;
  1542. // TODO: write tests and clean up code
  1543. function TaskQueue(debounceWait) {
  1544. var q = []; // array of runFuncs
  1545. function addTask(taskFunc) {
  1546. return new Promise(function(resolve) {
  1547. // should run this function when it's taskFunc's turn to run.
  1548. // responsible for popping itself off the queue.
  1549. var runFunc = function() {
  1550. Promise.resolve(taskFunc()) // result might be async, coerce to promise
  1551. .then(resolve) // resolve TaskQueue::push's promise, for the caller. will receive result of taskFunc.
  1552. .then(function() {
  1553. q.shift(); // pop itself off
  1554. // run the next task, if any
  1555. if (q.length) {
  1556. q[0]();
  1557. }
  1558. });
  1559. };
  1560. // always put the task at the end of the queue, BEFORE running the task
  1561. q.push(runFunc);
  1562. // if it's the only task in the queue, run immediately
  1563. if (q.length === 1) {
  1564. runFunc();
  1565. }
  1566. });
  1567. }
  1568. this.add = // potentially debounce, for the public method
  1569. typeof debounceWait === 'number' ?
  1570. debounce(addTask, debounceWait) :
  1571. addTask; // if not a number (null/undefined/false), no debounce at all
  1572. this.addQuickly = addTask; // guaranteed no debounce
  1573. }
  1574. FC.TaskQueue = TaskQueue;
  1575. /*
  1576. q = new TaskQueue();
  1577. function work(i) {
  1578. return q.push(function() {
  1579. trigger();
  1580. console.log('work' + i);
  1581. });
  1582. }
  1583. var cnt = 0;
  1584. function trigger() {
  1585. if (cnt < 5) {
  1586. cnt++;
  1587. work(cnt);
  1588. }
  1589. }
  1590. work(9);
  1591. */
  1592. ;;
  1593. var EmitterMixin = FC.EmitterMixin = {
  1594. // jQuery-ification via $(this) allows a non-DOM object to have
  1595. // the same event handling capabilities (including namespaces).
  1596. on: function(types, handler) {
  1597. $(this).on(types, this._prepareIntercept(handler));
  1598. return this; // for chaining
  1599. },
  1600. one: function(types, handler) {
  1601. $(this).one(types, this._prepareIntercept(handler));
  1602. return this; // for chaining
  1603. },
  1604. _prepareIntercept: function(handler) {
  1605. // handlers are always called with an "event" object as their first param.
  1606. // sneak the `this` context and arguments into the extra parameter object
  1607. // and forward them on to the original handler.
  1608. var intercept = function(ev, extra) {
  1609. return handler.apply(
  1610. extra.context || this,
  1611. extra.args || []
  1612. );
  1613. };
  1614. // mimick jQuery's internal "proxy" system (risky, I know)
  1615. // causing all functions with the same .guid to appear to be the same.
  1616. // https://github.com/jquery/jquery/blob/2.2.4/src/core.js#L448
  1617. // this is needed for calling .off with the original non-intercept handler.
  1618. if (!handler.guid) {
  1619. handler.guid = $.guid++;
  1620. }
  1621. intercept.guid = handler.guid;
  1622. return intercept;
  1623. },
  1624. off: function(types, handler) {
  1625. $(this).off(types, handler);
  1626. return this; // for chaining
  1627. },
  1628. trigger: function(types) {
  1629. var args = Array.prototype.slice.call(arguments, 1); // arguments after the first
  1630. // pass in "extra" info to the intercept
  1631. $(this).triggerHandler(types, { args: args });
  1632. return this; // for chaining
  1633. },
  1634. triggerWith: function(types, context, args) {
  1635. // `triggerHandler` is less reliant on the DOM compared to `trigger`.
  1636. // pass in "extra" info to the intercept.
  1637. $(this).triggerHandler(types, { context: context, args: args });
  1638. return this; // for chaining
  1639. }
  1640. };
  1641. ;;
  1642. /*
  1643. Utility methods for easily listening to events on another object,
  1644. and more importantly, easily unlistening from them.
  1645. */
  1646. var ListenerMixin = FC.ListenerMixin = (function() {
  1647. var guid = 0;
  1648. var ListenerMixin = {
  1649. listenerId: null,
  1650. /*
  1651. Given an `other` object that has on/off methods, bind the given `callback` to an event by the given name.
  1652. The `callback` will be called with the `this` context of the object that .listenTo is being called on.
  1653. Can be called:
  1654. .listenTo(other, eventName, callback)
  1655. OR
  1656. .listenTo(other, {
  1657. eventName1: callback1,
  1658. eventName2: callback2
  1659. })
  1660. */
  1661. listenTo: function(other, arg, callback) {
  1662. if (typeof arg === 'object') { // given dictionary of callbacks
  1663. for (var eventName in arg) {
  1664. if (arg.hasOwnProperty(eventName)) {
  1665. this.listenTo(other, eventName, arg[eventName]);
  1666. }
  1667. }
  1668. }
  1669. else if (typeof arg === 'string') {
  1670. other.on(
  1671. arg + '.' + this.getListenerNamespace(), // use event namespacing to identify this object
  1672. $.proxy(callback, this) // always use `this` context
  1673. // the usually-undesired jQuery guid behavior doesn't matter,
  1674. // because we always unbind via namespace
  1675. );
  1676. }
  1677. },
  1678. /*
  1679. Causes the current object to stop listening to events on the `other` object.
  1680. `eventName` is optional. If omitted, will stop listening to ALL events on `other`.
  1681. */
  1682. stopListeningTo: function(other, eventName) {
  1683. other.off((eventName || '') + '.' + this.getListenerNamespace());
  1684. },
  1685. /*
  1686. Returns a string, unique to this object, to be used for event namespacing
  1687. */
  1688. getListenerNamespace: function() {
  1689. if (this.listenerId == null) {
  1690. this.listenerId = guid++;
  1691. }
  1692. return '_listener' + this.listenerId;
  1693. }
  1694. };
  1695. return ListenerMixin;
  1696. })();
  1697. ;;
  1698. /* A rectangular panel that is absolutely positioned over other content
  1699. ------------------------------------------------------------------------------------------------------------------------
  1700. Options:
  1701. - className (string)
  1702. - content (HTML string or jQuery element set)
  1703. - parentEl
  1704. - top
  1705. - left
  1706. - right (the x coord of where the right edge should be. not a "CSS" right)
  1707. - autoHide (boolean)
  1708. - show (callback)
  1709. - hide (callback)
  1710. */
  1711. var Popover = Class.extend(ListenerMixin, {
  1712. isHidden: true,
  1713. options: null,
  1714. el: null, // the container element for the popover. generated by this object
  1715. margin: 10, // the space required between the popover and the edges of the scroll container
  1716. constructor: function(options) {
  1717. this.options = options || {};
  1718. },
  1719. // Shows the popover on the specified position. Renders it if not already
  1720. show: function() {
  1721. if (this.isHidden) {
  1722. if (!this.el) {
  1723. this.render();
  1724. }
  1725. this.el.show();
  1726. this.position();
  1727. this.isHidden = false;
  1728. this.trigger('show');
  1729. }
  1730. },
  1731. // Hides the popover, through CSS, but does not remove it from the DOM
  1732. hide: function() {
  1733. if (!this.isHidden) {
  1734. this.el.hide();
  1735. this.isHidden = true;
  1736. this.trigger('hide');
  1737. }
  1738. },
  1739. // Creates `this.el` and renders content inside of it
  1740. render: function() {
  1741. var _this = this;
  1742. var options = this.options;
  1743. this.el = $('<div class="fc-popover"/>')
  1744. .addClass(options.className || '')
  1745. .css({
  1746. // position initially to the top left to avoid creating scrollbars
  1747. top: 0,
  1748. left: 0
  1749. })
  1750. .append(options.content)
  1751. .appendTo(options.parentEl);
  1752. // when a click happens on anything inside with a 'fc-close' className, hide the popover
  1753. this.el.on('click', '.fc-close', function() {
  1754. _this.hide();
  1755. });
  1756. if (options.autoHide) {
  1757. this.listenTo($(document), 'mousedown', this.documentMousedown);
  1758. }
  1759. },
  1760. // Triggered when the user clicks *anywhere* in the document, for the autoHide feature
  1761. documentMousedown: function(ev) {
  1762. // only hide the popover if the click happened outside the popover
  1763. if (this.el && !$(ev.target).closest(this.el).length) {
  1764. this.hide();
  1765. }
  1766. },
  1767. // Hides and unregisters any handlers
  1768. removeElement: function() {
  1769. this.hide();
  1770. if (this.el) {
  1771. this.el.remove();
  1772. this.el = null;
  1773. }
  1774. this.stopListeningTo($(document), 'mousedown');
  1775. },
  1776. // Positions the popover optimally, using the top/left/right options
  1777. position: function() {
  1778. var options = this.options;
  1779. var origin = this.el.offsetParent().offset();
  1780. var width = this.el.outerWidth();
  1781. var height = this.el.outerHeight();
  1782. var windowEl = $(window);
  1783. var viewportEl = getScrollParent(this.el);
  1784. var viewportTop;
  1785. var viewportLeft;
  1786. var viewportOffset;
  1787. var top; // the "position" (not "offset") values for the popover
  1788. var left; //
  1789. // compute top and left
  1790. top = options.top || 0;
  1791. if (options.left !== undefined) {
  1792. left = options.left;
  1793. }
  1794. else if (options.right !== undefined) {
  1795. left = options.right - width; // derive the left value from the right value
  1796. }
  1797. else {
  1798. left = 0;
  1799. }
  1800. if (viewportEl.is(window) || viewportEl.is(document)) { // normalize getScrollParent's result
  1801. viewportEl = windowEl;
  1802. viewportTop = 0; // the window is always at the top left
  1803. viewportLeft = 0; // (and .offset() won't work if called here)
  1804. }
  1805. else {
  1806. viewportOffset = viewportEl.offset();
  1807. viewportTop = viewportOffset.top;
  1808. viewportLeft = viewportOffset.left;
  1809. }
  1810. // if the window is scrolled, it causes the visible area to be further down
  1811. viewportTop += windowEl.scrollTop();
  1812. viewportLeft += windowEl.scrollLeft();
  1813. // constrain to the view port. if constrained by two edges, give precedence to top/left
  1814. if (options.viewportConstrain !== false) {
  1815. top = Math.min(top, viewportTop + viewportEl.outerHeight() - height - this.margin);
  1816. top = Math.max(top, viewportTop + this.margin);
  1817. left = Math.min(left, viewportLeft + viewportEl.outerWidth() - width - this.margin);
  1818. left = Math.max(left, viewportLeft + this.margin);
  1819. }
  1820. this.el.css({
  1821. top: top - origin.top,
  1822. left: left - origin.left
  1823. });
  1824. },
  1825. // Triggers a callback. Calls a function in the option hash of the same name.
  1826. // Arguments beyond the first `name` are forwarded on.
  1827. // TODO: better code reuse for this. Repeat code
  1828. trigger: function(name) {
  1829. if (this.options[name]) {
  1830. this.options[name].apply(this, Array.prototype.slice.call(arguments, 1));
  1831. }
  1832. }
  1833. });
  1834. ;;
  1835. /*
  1836. A cache for the left/right/top/bottom/width/height values for one or more elements.
  1837. Works with both offset (from topleft document) and position (from offsetParent).
  1838. options:
  1839. - els
  1840. - isHorizontal
  1841. - isVertical
  1842. */
  1843. var CoordCache = FC.CoordCache = Class.extend({
  1844. els: null, // jQuery set (assumed to be siblings)
  1845. forcedOffsetParentEl: null, // options can override the natural offsetParent
  1846. origin: null, // {left,top} position of offsetParent of els
  1847. boundingRect: null, // constrain cordinates to this rectangle. {left,right,top,bottom} or null
  1848. isHorizontal: false, // whether to query for left/right/width
  1849. isVertical: false, // whether to query for top/bottom/height
  1850. // arrays of coordinates (offsets from topleft of document)
  1851. lefts: null,
  1852. rights: null,
  1853. tops: null,
  1854. bottoms: null,
  1855. constructor: function(options) {
  1856. this.els = $(options.els);
  1857. this.isHorizontal = options.isHorizontal;
  1858. this.isVertical = options.isVertical;
  1859. this.forcedOffsetParentEl = options.offsetParent ? $(options.offsetParent) : null;
  1860. },
  1861. // Queries the els for coordinates and stores them.
  1862. // Call this method before using and of the get* methods below.
  1863. build: function() {
  1864. var offsetParentEl = this.forcedOffsetParentEl;
  1865. if (!offsetParentEl && this.els.length > 0) {
  1866. offsetParentEl = this.els.eq(0).offsetParent();
  1867. }
  1868. this.origin = offsetParentEl ?
  1869. offsetParentEl.offset() :
  1870. null;
  1871. this.boundingRect = this.queryBoundingRect();
  1872. if (this.isHorizontal) {
  1873. this.buildElHorizontals();
  1874. }
  1875. if (this.isVertical) {
  1876. this.buildElVerticals();
  1877. }
  1878. },
  1879. // Destroys all internal data about coordinates, freeing memory
  1880. clear: function() {
  1881. this.origin = null;
  1882. this.boundingRect = null;
  1883. this.lefts = null;
  1884. this.rights = null;
  1885. this.tops = null;
  1886. this.bottoms = null;
  1887. },
  1888. // When called, if coord caches aren't built, builds them
  1889. ensureBuilt: function() {
  1890. if (!this.origin) {
  1891. this.build();
  1892. }
  1893. },
  1894. // Populates the left/right internal coordinate arrays
  1895. buildElHorizontals: function() {
  1896. var lefts = [];
  1897. var rights = [];
  1898. this.els.each(function(i, node) {
  1899. var el = $(node);
  1900. var left = el.offset().left;
  1901. var width = el.outerWidth();
  1902. lefts.push(left);
  1903. rights.push(left + width);
  1904. });
  1905. this.lefts = lefts;
  1906. this.rights = rights;
  1907. },
  1908. // Populates the top/bottom internal coordinate arrays
  1909. buildElVerticals: function() {
  1910. var tops = [];
  1911. var bottoms = [];
  1912. this.els.each(function(i, node) {
  1913. var el = $(node);
  1914. var top = el.offset().top;
  1915. var height = el.outerHeight();
  1916. tops.push(top);
  1917. bottoms.push(top + height);
  1918. });
  1919. this.tops = tops;
  1920. this.bottoms = bottoms;
  1921. },
  1922. // Given a left offset (from document left), returns the index of the el that it horizontally intersects.
  1923. // If no intersection is made, returns undefined.
  1924. getHorizontalIndex: function(leftOffset) {
  1925. this.ensureBuilt();
  1926. var lefts = this.lefts;
  1927. var rights = this.rights;
  1928. var len = lefts.length;
  1929. var i;
  1930. for (i = 0; i < len; i++) {
  1931. if (leftOffset >= lefts[i] && leftOffset < rights[i]) {
  1932. return i;
  1933. }
  1934. }
  1935. },
  1936. // Given a top offset (from document top), returns the index of the el that it vertically intersects.
  1937. // If no intersection is made, returns undefined.
  1938. getVerticalIndex: function(topOffset) {
  1939. this.ensureBuilt();
  1940. var tops = this.tops;
  1941. var bottoms = this.bottoms;
  1942. var len = tops.length;
  1943. var i;
  1944. for (i = 0; i < len; i++) {
  1945. if (topOffset >= tops[i] && topOffset < bottoms[i]) {
  1946. return i;
  1947. }
  1948. }
  1949. },
  1950. // Gets the left offset (from document left) of the element at the given index
  1951. getLeftOffset: function(leftIndex) {
  1952. this.ensureBuilt();
  1953. return this.lefts[leftIndex];
  1954. },
  1955. // Gets the left position (from offsetParent left) of the element at the given index
  1956. getLeftPosition: function(leftIndex) {
  1957. this.ensureBuilt();
  1958. return this.lefts[leftIndex] - this.origin.left;
  1959. },
  1960. // Gets the right offset (from document left) of the element at the given index.
  1961. // This value is NOT relative to the document's right edge, like the CSS concept of "right" would be.
  1962. getRightOffset: function(leftIndex) {
  1963. this.ensureBuilt();
  1964. return this.rights[leftIndex];
  1965. },
  1966. // Gets the right position (from offsetParent left) of the element at the given index.
  1967. // This value is NOT relative to the offsetParent's right edge, like the CSS concept of "right" would be.
  1968. getRightPosition: function(leftIndex) {
  1969. this.ensureBuilt();
  1970. return this.rights[leftIndex] - this.origin.left;
  1971. },
  1972. // Gets the width of the element at the given index
  1973. getWidth: function(leftIndex) {
  1974. this.ensureBuilt();
  1975. return this.rights[leftIndex] - this.lefts[leftIndex];
  1976. },
  1977. // Gets the top offset (from document top) of the element at the given index
  1978. getTopOffset: function(topIndex) {
  1979. this.ensureBuilt();
  1980. return this.tops[topIndex];
  1981. },
  1982. // Gets the top position (from offsetParent top) of the element at the given position
  1983. getTopPosition: function(topIndex) {
  1984. this.ensureBuilt();
  1985. return this.tops[topIndex] - this.origin.top;
  1986. },
  1987. // Gets the bottom offset (from the document top) of the element at the given index.
  1988. // This value is NOT relative to the offsetParent's bottom edge, like the CSS concept of "bottom" would be.
  1989. getBottomOffset: function(topIndex) {
  1990. this.ensureBuilt();
  1991. return this.bottoms[topIndex];
  1992. },
  1993. // Gets the bottom position (from the offsetParent top) of the element at the given index.
  1994. // This value is NOT relative to the offsetParent's bottom edge, like the CSS concept of "bottom" would be.
  1995. getBottomPosition: function(topIndex) {
  1996. this.ensureBuilt();
  1997. return this.bottoms[topIndex] - this.origin.top;
  1998. },
  1999. // Gets the height of the element at the given index
  2000. getHeight: function(topIndex) {
  2001. this.ensureBuilt();
  2002. return this.bottoms[topIndex] - this.tops[topIndex];
  2003. },
  2004. // Bounding Rect
  2005. // TODO: decouple this from CoordCache
  2006. // Compute and return what the elements' bounding rectangle is, from the user's perspective.
  2007. // Right now, only returns a rectangle if constrained by an overflow:scroll element.
  2008. // Returns null if there are no elements
  2009. queryBoundingRect: function() {
  2010. var scrollParentEl;
  2011. if (this.els.length > 0) {
  2012. scrollParentEl = getScrollParent(this.els.eq(0));
  2013. if (!scrollParentEl.is(document)) {
  2014. return getClientRect(scrollParentEl);
  2015. }
  2016. }
  2017. return null;
  2018. },
  2019. isPointInBounds: function(leftOffset, topOffset) {
  2020. return this.isLeftInBounds(leftOffset) && this.isTopInBounds(topOffset);
  2021. },
  2022. isLeftInBounds: function(leftOffset) {
  2023. return !this.boundingRect || (leftOffset >= this.boundingRect.left && leftOffset < this.boundingRect.right);
  2024. },
  2025. isTopInBounds: function(topOffset) {
  2026. return !this.boundingRect || (topOffset >= this.boundingRect.top && topOffset < this.boundingRect.bottom);
  2027. }
  2028. });
  2029. ;;
  2030. /* Tracks a drag's mouse movement, firing various handlers
  2031. ----------------------------------------------------------------------------------------------------------------------*/
  2032. // TODO: use Emitter
  2033. var DragListener = FC.DragListener = Class.extend(ListenerMixin, {
  2034. options: null,
  2035. subjectEl: null,
  2036. // coordinates of the initial mousedown
  2037. originX: null,
  2038. originY: null,
  2039. // the wrapping element that scrolls, or MIGHT scroll if there's overflow.
  2040. // TODO: do this for wrappers that have overflow:hidden as well.
  2041. scrollEl: null,
  2042. isInteracting: false,
  2043. isDistanceSurpassed: false,
  2044. isDelayEnded: false,
  2045. isDragging: false,
  2046. isTouch: false,
  2047. delay: null,
  2048. delayTimeoutId: null,
  2049. minDistance: null,
  2050. shouldCancelTouchScroll: true,
  2051. scrollAlwaysKills: false,
  2052. constructor: function(options) {
  2053. this.options = options || {};
  2054. },
  2055. // Interaction (high-level)
  2056. // -----------------------------------------------------------------------------------------------------------------
  2057. startInteraction: function(ev, extraOptions) {
  2058. var isTouch = getEvIsTouch(ev);
  2059. if (ev.type === 'mousedown') {
  2060. if (GlobalEmitter.get().shouldIgnoreMouse()) {
  2061. return;
  2062. }
  2063. else if (!isPrimaryMouseButton(ev)) {
  2064. return;
  2065. }
  2066. else {
  2067. ev.preventDefault(); // prevents native selection in most browsers
  2068. }
  2069. }
  2070. if (!this.isInteracting) {
  2071. // process options
  2072. extraOptions = extraOptions || {};
  2073. this.delay = firstDefined(extraOptions.delay, this.options.delay, 0);
  2074. this.minDistance = firstDefined(extraOptions.distance, this.options.distance, 0);
  2075. this.subjectEl = this.options.subjectEl;
  2076. preventSelection($('body'));
  2077. this.isInteracting = true;
  2078. this.isTouch = isTouch;
  2079. this.isDelayEnded = false;
  2080. this.isDistanceSurpassed = false;
  2081. this.originX = getEvX(ev);
  2082. this.originY = getEvY(ev);
  2083. this.scrollEl = getScrollParent($(ev.target));
  2084. this.bindHandlers();
  2085. this.initAutoScroll();
  2086. this.handleInteractionStart(ev);
  2087. this.startDelay(ev);
  2088. if (!this.minDistance) {
  2089. this.handleDistanceSurpassed(ev);
  2090. }
  2091. }
  2092. },
  2093. handleInteractionStart: function(ev) {
  2094. this.trigger('interactionStart', ev);
  2095. },
  2096. endInteraction: function(ev, isCancelled) {
  2097. if (this.isInteracting) {
  2098. this.endDrag(ev);
  2099. if (this.delayTimeoutId) {
  2100. clearTimeout(this.delayTimeoutId);
  2101. this.delayTimeoutId = null;
  2102. }
  2103. this.destroyAutoScroll();
  2104. this.unbindHandlers();
  2105. this.isInteracting = false;
  2106. this.handleInteractionEnd(ev, isCancelled);
  2107. allowSelection($('body'));
  2108. }
  2109. },
  2110. handleInteractionEnd: function(ev, isCancelled) {
  2111. this.trigger('interactionEnd', ev, isCancelled || false);
  2112. },
  2113. // Binding To DOM
  2114. // -----------------------------------------------------------------------------------------------------------------
  2115. bindHandlers: function() {
  2116. // some browsers (Safari in iOS 10) don't allow preventDefault on touch events that are bound after touchstart,
  2117. // so listen to the GlobalEmitter singleton, which is always bound, instead of the document directly.
  2118. var globalEmitter = GlobalEmitter.get();
  2119. if (this.isTouch) {
  2120. this.listenTo(globalEmitter, {
  2121. touchmove: this.handleTouchMove,
  2122. touchend: this.endInteraction,
  2123. scroll: this.handleTouchScroll
  2124. });
  2125. }
  2126. else {
  2127. this.listenTo(globalEmitter, {
  2128. mousemove: this.handleMouseMove,
  2129. mouseup: this.endInteraction
  2130. });
  2131. }
  2132. this.listenTo(globalEmitter, {
  2133. selectstart: preventDefault, // don't allow selection while dragging
  2134. contextmenu: preventDefault // long taps would open menu on Chrome dev tools
  2135. });
  2136. },
  2137. unbindHandlers: function() {
  2138. this.stopListeningTo(GlobalEmitter.get());
  2139. },
  2140. // Drag (high-level)
  2141. // -----------------------------------------------------------------------------------------------------------------
  2142. // extraOptions ignored if drag already started
  2143. startDrag: function(ev, extraOptions) {
  2144. this.startInteraction(ev, extraOptions); // ensure interaction began
  2145. if (!this.isDragging) {
  2146. this.isDragging = true;
  2147. this.handleDragStart(ev);
  2148. }
  2149. },
  2150. handleDragStart: function(ev) {
  2151. this.trigger('dragStart', ev);
  2152. },
  2153. handleMove: function(ev) {
  2154. var dx = getEvX(ev) - this.originX;
  2155. var dy = getEvY(ev) - this.originY;
  2156. var minDistance = this.minDistance;
  2157. var distanceSq; // current distance from the origin, squared
  2158. if (!this.isDistanceSurpassed) {
  2159. distanceSq = dx * dx + dy * dy;
  2160. if (distanceSq >= minDistance * minDistance) { // use pythagorean theorem
  2161. this.handleDistanceSurpassed(ev);
  2162. }
  2163. }
  2164. if (this.isDragging) {
  2165. this.handleDrag(dx, dy, ev);
  2166. }
  2167. },
  2168. // Called while the mouse is being moved and when we know a legitimate drag is taking place
  2169. handleDrag: function(dx, dy, ev) {
  2170. this.trigger('drag', dx, dy, ev);
  2171. this.updateAutoScroll(ev); // will possibly cause scrolling
  2172. },
  2173. endDrag: function(ev) {
  2174. if (this.isDragging) {
  2175. this.isDragging = false;
  2176. this.handleDragEnd(ev);
  2177. }
  2178. },
  2179. handleDragEnd: function(ev) {
  2180. this.trigger('dragEnd', ev);
  2181. },
  2182. // Delay
  2183. // -----------------------------------------------------------------------------------------------------------------
  2184. startDelay: function(initialEv) {
  2185. var _this = this;
  2186. if (this.delay) {
  2187. this.delayTimeoutId = setTimeout(function() {
  2188. _this.handleDelayEnd(initialEv);
  2189. }, this.delay);
  2190. }
  2191. else {
  2192. this.handleDelayEnd(initialEv);
  2193. }
  2194. },
  2195. handleDelayEnd: function(initialEv) {
  2196. this.isDelayEnded = true;
  2197. if (this.isDistanceSurpassed) {
  2198. this.startDrag(initialEv);
  2199. }
  2200. },
  2201. // Distance
  2202. // -----------------------------------------------------------------------------------------------------------------
  2203. handleDistanceSurpassed: function(ev) {
  2204. this.isDistanceSurpassed = true;
  2205. if (this.isDelayEnded) {
  2206. this.startDrag(ev);
  2207. }
  2208. },
  2209. // Mouse / Touch
  2210. // -----------------------------------------------------------------------------------------------------------------
  2211. handleTouchMove: function(ev) {
  2212. // prevent inertia and touchmove-scrolling while dragging
  2213. if (this.isDragging && this.shouldCancelTouchScroll) {
  2214. ev.preventDefault();
  2215. }
  2216. this.handleMove(ev);
  2217. },
  2218. handleMouseMove: function(ev) {
  2219. this.handleMove(ev);
  2220. },
  2221. // Scrolling (unrelated to auto-scroll)
  2222. // -----------------------------------------------------------------------------------------------------------------
  2223. handleTouchScroll: function(ev) {
  2224. // if the drag is being initiated by touch, but a scroll happens before
  2225. // the drag-initiating delay is over, cancel the drag
  2226. if (!this.isDragging || this.scrollAlwaysKills) {
  2227. this.endInteraction(ev, true); // isCancelled=true
  2228. }
  2229. },
  2230. // Utils
  2231. // -----------------------------------------------------------------------------------------------------------------
  2232. // Triggers a callback. Calls a function in the option hash of the same name.
  2233. // Arguments beyond the first `name` are forwarded on.
  2234. trigger: function(name) {
  2235. if (this.options[name]) {
  2236. this.options[name].apply(this, Array.prototype.slice.call(arguments, 1));
  2237. }
  2238. // makes _methods callable by event name. TODO: kill this
  2239. if (this['_' + name]) {
  2240. this['_' + name].apply(this, Array.prototype.slice.call(arguments, 1));
  2241. }
  2242. }
  2243. });
  2244. ;;
  2245. /*
  2246. this.scrollEl is set in DragListener
  2247. */
  2248. DragListener.mixin({
  2249. isAutoScroll: false,
  2250. scrollBounds: null, // { top, bottom, left, right }
  2251. scrollTopVel: null, // pixels per second
  2252. scrollLeftVel: null, // pixels per second
  2253. scrollIntervalId: null, // ID of setTimeout for scrolling animation loop
  2254. // defaults
  2255. scrollSensitivity: 30, // pixels from edge for scrolling to start
  2256. scrollSpeed: 200, // pixels per second, at maximum speed
  2257. scrollIntervalMs: 50, // millisecond wait between scroll increment
  2258. initAutoScroll: function() {
  2259. var scrollEl = this.scrollEl;
  2260. this.isAutoScroll =
  2261. this.options.scroll &&
  2262. scrollEl &&
  2263. !scrollEl.is(window) &&
  2264. !scrollEl.is(document);
  2265. if (this.isAutoScroll) {
  2266. // debounce makes sure rapid calls don't happen
  2267. this.listenTo(scrollEl, 'scroll', debounce(this.handleDebouncedScroll, 100));
  2268. }
  2269. },
  2270. destroyAutoScroll: function() {
  2271. this.endAutoScroll(); // kill any animation loop
  2272. // remove the scroll handler if there is a scrollEl
  2273. if (this.isAutoScroll) {
  2274. this.stopListeningTo(this.scrollEl, 'scroll'); // will probably get removed by unbindHandlers too :(
  2275. }
  2276. },
  2277. // Computes and stores the bounding rectangle of scrollEl
  2278. computeScrollBounds: function() {
  2279. if (this.isAutoScroll) {
  2280. this.scrollBounds = getOuterRect(this.scrollEl);
  2281. // TODO: use getClientRect in future. but prevents auto scrolling when on top of scrollbars
  2282. }
  2283. },
  2284. // Called when the dragging is in progress and scrolling should be updated
  2285. updateAutoScroll: function(ev) {
  2286. var sensitivity = this.scrollSensitivity;
  2287. var bounds = this.scrollBounds;
  2288. var topCloseness, bottomCloseness;
  2289. var leftCloseness, rightCloseness;
  2290. var topVel = 0;
  2291. var leftVel = 0;
  2292. if (bounds) { // only scroll if scrollEl exists
  2293. // compute closeness to edges. valid range is from 0.0 - 1.0
  2294. topCloseness = (sensitivity - (getEvY(ev) - bounds.top)) / sensitivity;
  2295. bottomCloseness = (sensitivity - (bounds.bottom - getEvY(ev))) / sensitivity;
  2296. leftCloseness = (sensitivity - (getEvX(ev) - bounds.left)) / sensitivity;
  2297. rightCloseness = (sensitivity - (bounds.right - getEvX(ev))) / sensitivity;
  2298. // translate vertical closeness into velocity.
  2299. // mouse must be completely in bounds for velocity to happen.
  2300. if (topCloseness >= 0 && topCloseness <= 1) {
  2301. topVel = topCloseness * this.scrollSpeed * -1; // negative. for scrolling up
  2302. }
  2303. else if (bottomCloseness >= 0 && bottomCloseness <= 1) {
  2304. topVel = bottomCloseness * this.scrollSpeed;
  2305. }
  2306. // translate horizontal closeness into velocity
  2307. if (leftCloseness >= 0 && leftCloseness <= 1) {
  2308. leftVel = leftCloseness * this.scrollSpeed * -1; // negative. for scrolling left
  2309. }
  2310. else if (rightCloseness >= 0 && rightCloseness <= 1) {
  2311. leftVel = rightCloseness * this.scrollSpeed;
  2312. }
  2313. }
  2314. this.setScrollVel(topVel, leftVel);
  2315. },
  2316. // Sets the speed-of-scrolling for the scrollEl
  2317. setScrollVel: function(topVel, leftVel) {
  2318. this.scrollTopVel = topVel;
  2319. this.scrollLeftVel = leftVel;
  2320. this.constrainScrollVel(); // massages into realistic values
  2321. // if there is non-zero velocity, and an animation loop hasn't already started, then START
  2322. if ((this.scrollTopVel || this.scrollLeftVel) && !this.scrollIntervalId) {
  2323. this.scrollIntervalId = setInterval(
  2324. proxy(this, 'scrollIntervalFunc'), // scope to `this`
  2325. this.scrollIntervalMs
  2326. );
  2327. }
  2328. },
  2329. // Forces scrollTopVel and scrollLeftVel to be zero if scrolling has already gone all the way
  2330. constrainScrollVel: function() {
  2331. var el = this.scrollEl;
  2332. if (this.scrollTopVel < 0) { // scrolling up?
  2333. if (el.scrollTop() <= 0) { // already scrolled all the way up?
  2334. this.scrollTopVel = 0;
  2335. }
  2336. }
  2337. else if (this.scrollTopVel > 0) { // scrolling down?
  2338. if (el.scrollTop() + el[0].clientHeight >= el[0].scrollHeight) { // already scrolled all the way down?
  2339. this.scrollTopVel = 0;
  2340. }
  2341. }
  2342. if (this.scrollLeftVel < 0) { // scrolling left?
  2343. if (el.scrollLeft() <= 0) { // already scrolled all the left?
  2344. this.scrollLeftVel = 0;
  2345. }
  2346. }
  2347. else if (this.scrollLeftVel > 0) { // scrolling right?
  2348. if (el.scrollLeft() + el[0].clientWidth >= el[0].scrollWidth) { // already scrolled all the way right?
  2349. this.scrollLeftVel = 0;
  2350. }
  2351. }
  2352. },
  2353. // This function gets called during every iteration of the scrolling animation loop
  2354. scrollIntervalFunc: function() {
  2355. var el = this.scrollEl;
  2356. var frac = this.scrollIntervalMs / 1000; // considering animation frequency, what the vel should be mult'd by
  2357. // change the value of scrollEl's scroll
  2358. if (this.scrollTopVel) {
  2359. el.scrollTop(el.scrollTop() + this.scrollTopVel * frac);
  2360. }
  2361. if (this.scrollLeftVel) {
  2362. el.scrollLeft(el.scrollLeft() + this.scrollLeftVel * frac);
  2363. }
  2364. this.constrainScrollVel(); // since the scroll values changed, recompute the velocities
  2365. // if scrolled all the way, which causes the vels to be zero, stop the animation loop
  2366. if (!this.scrollTopVel && !this.scrollLeftVel) {
  2367. this.endAutoScroll();
  2368. }
  2369. },
  2370. // Kills any existing scrolling animation loop
  2371. endAutoScroll: function() {
  2372. if (this.scrollIntervalId) {
  2373. clearInterval(this.scrollIntervalId);
  2374. this.scrollIntervalId = null;
  2375. this.handleScrollEnd();
  2376. }
  2377. },
  2378. // Get called when the scrollEl is scrolled (NOTE: this is delayed via debounce)
  2379. handleDebouncedScroll: function() {
  2380. // recompute all coordinates, but *only* if this is *not* part of our scrolling animation
  2381. if (!this.scrollIntervalId) {
  2382. this.handleScrollEnd();
  2383. }
  2384. },
  2385. // Called when scrolling has stopped, whether through auto scroll, or the user scrolling
  2386. handleScrollEnd: function() {
  2387. }
  2388. });
  2389. ;;
  2390. /* Tracks mouse movements over a component and raises events about which hit the mouse is over.
  2391. ------------------------------------------------------------------------------------------------------------------------
  2392. options:
  2393. - subjectEl
  2394. - subjectCenter
  2395. */
  2396. var HitDragListener = DragListener.extend({
  2397. component: null, // converts coordinates to hits
  2398. // methods: hitsNeeded, hitsNotNeeded, queryHit
  2399. origHit: null, // the hit the mouse was over when listening started
  2400. hit: null, // the hit the mouse is over
  2401. coordAdjust: null, // delta that will be added to the mouse coordinates when computing collisions
  2402. constructor: function(component, options) {
  2403. DragListener.call(this, options); // call the super-constructor
  2404. this.component = component;
  2405. },
  2406. // Called when drag listening starts (but a real drag has not necessarily began).
  2407. // ev might be undefined if dragging was started manually.
  2408. handleInteractionStart: function(ev) {
  2409. var subjectEl = this.subjectEl;
  2410. var subjectRect;
  2411. var origPoint;
  2412. var point;
  2413. this.component.hitsNeeded();
  2414. this.computeScrollBounds(); // for autoscroll
  2415. if (ev) {
  2416. origPoint = { left: getEvX(ev), top: getEvY(ev) };
  2417. point = origPoint;
  2418. // constrain the point to bounds of the element being dragged
  2419. if (subjectEl) {
  2420. subjectRect = getOuterRect(subjectEl); // used for centering as well
  2421. point = constrainPoint(point, subjectRect);
  2422. }
  2423. this.origHit = this.queryHit(point.left, point.top);
  2424. // treat the center of the subject as the collision point?
  2425. if (subjectEl && this.options.subjectCenter) {
  2426. // only consider the area the subject overlaps the hit. best for large subjects.
  2427. // TODO: skip this if hit didn't supply left/right/top/bottom
  2428. if (this.origHit) {
  2429. subjectRect = intersectRects(this.origHit, subjectRect) ||
  2430. subjectRect; // in case there is no intersection
  2431. }
  2432. point = getRectCenter(subjectRect);
  2433. }
  2434. this.coordAdjust = diffPoints(point, origPoint); // point - origPoint
  2435. }
  2436. else {
  2437. this.origHit = null;
  2438. this.coordAdjust = null;
  2439. }
  2440. // call the super-method. do it after origHit has been computed
  2441. DragListener.prototype.handleInteractionStart.apply(this, arguments);
  2442. },
  2443. // Called when the actual drag has started
  2444. handleDragStart: function(ev) {
  2445. var hit;
  2446. DragListener.prototype.handleDragStart.apply(this, arguments); // call the super-method
  2447. // might be different from this.origHit if the min-distance is large
  2448. hit = this.queryHit(getEvX(ev), getEvY(ev));
  2449. // report the initial hit the mouse is over
  2450. // especially important if no min-distance and drag starts immediately
  2451. if (hit) {
  2452. this.handleHitOver(hit);
  2453. }
  2454. },
  2455. // Called when the drag moves
  2456. handleDrag: function(dx, dy, ev) {
  2457. var hit;
  2458. DragListener.prototype.handleDrag.apply(this, arguments); // call the super-method
  2459. hit = this.queryHit(getEvX(ev), getEvY(ev));
  2460. if (!isHitsEqual(hit, this.hit)) { // a different hit than before?
  2461. if (this.hit) {
  2462. this.handleHitOut();
  2463. }
  2464. if (hit) {
  2465. this.handleHitOver(hit);
  2466. }
  2467. }
  2468. },
  2469. // Called when dragging has been stopped
  2470. handleDragEnd: function() {
  2471. this.handleHitDone();
  2472. DragListener.prototype.handleDragEnd.apply(this, arguments); // call the super-method
  2473. },
  2474. // Called when a the mouse has just moved over a new hit
  2475. handleHitOver: function(hit) {
  2476. var isOrig = isHitsEqual(hit, this.origHit);
  2477. this.hit = hit;
  2478. this.trigger('hitOver', this.hit, isOrig, this.origHit);
  2479. },
  2480. // Called when the mouse has just moved out of a hit
  2481. handleHitOut: function() {
  2482. if (this.hit) {
  2483. this.trigger('hitOut', this.hit);
  2484. this.handleHitDone();
  2485. this.hit = null;
  2486. }
  2487. },
  2488. // Called after a hitOut. Also called before a dragStop
  2489. handleHitDone: function() {
  2490. if (this.hit) {
  2491. this.trigger('hitDone', this.hit);
  2492. }
  2493. },
  2494. // Called when the interaction ends, whether there was a real drag or not
  2495. handleInteractionEnd: function() {
  2496. DragListener.prototype.handleInteractionEnd.apply(this, arguments); // call the super-method
  2497. this.origHit = null;
  2498. this.hit = null;
  2499. this.component.hitsNotNeeded();
  2500. },
  2501. // Called when scrolling has stopped, whether through auto scroll, or the user scrolling
  2502. handleScrollEnd: function() {
  2503. DragListener.prototype.handleScrollEnd.apply(this, arguments); // call the super-method
  2504. // hits' absolute positions will be in new places after a user's scroll.
  2505. // HACK for recomputing.
  2506. if (this.isDragging) {
  2507. this.component.releaseHits();
  2508. this.component.prepareHits();
  2509. }
  2510. },
  2511. // Gets the hit underneath the coordinates for the given mouse event
  2512. queryHit: function(left, top) {
  2513. if (this.coordAdjust) {
  2514. left += this.coordAdjust.left;
  2515. top += this.coordAdjust.top;
  2516. }
  2517. return this.component.queryHit(left, top);
  2518. }
  2519. });
  2520. // Returns `true` if the hits are identically equal. `false` otherwise. Must be from the same component.
  2521. // Two null values will be considered equal, as two "out of the component" states are the same.
  2522. function isHitsEqual(hit0, hit1) {
  2523. if (!hit0 && !hit1) {
  2524. return true;
  2525. }
  2526. if (hit0 && hit1) {
  2527. return hit0.component === hit1.component &&
  2528. isHitPropsWithin(hit0, hit1) &&
  2529. isHitPropsWithin(hit1, hit0); // ensures all props are identical
  2530. }
  2531. return false;
  2532. }
  2533. // Returns true if all of subHit's non-standard properties are within superHit
  2534. function isHitPropsWithin(subHit, superHit) {
  2535. for (var propName in subHit) {
  2536. if (!/^(component|left|right|top|bottom)$/.test(propName)) {
  2537. if (subHit[propName] !== superHit[propName]) {
  2538. return false;
  2539. }
  2540. }
  2541. }
  2542. return true;
  2543. }
  2544. ;;
  2545. /*
  2546. Listens to document and window-level user-interaction events, like touch events and mouse events,
  2547. and fires these events as-is to whoever is observing a GlobalEmitter.
  2548. Best when used as a singleton via GlobalEmitter.get()
  2549. Normalizes mouse/touch events. For examples:
  2550. - ignores the the simulated mouse events that happen after a quick tap: mousemove+mousedown+mouseup+click
  2551. - compensates for various buggy scenarios where a touchend does not fire
  2552. */
  2553. FC.touchMouseIgnoreWait = 500;
  2554. var GlobalEmitter = Class.extend(ListenerMixin, EmitterMixin, {
  2555. isTouching: false,
  2556. mouseIgnoreDepth: 0,
  2557. handleScrollProxy: null,
  2558. bind: function() {
  2559. var _this = this;
  2560. this.listenTo($(document), {
  2561. touchstart: this.handleTouchStart,
  2562. touchcancel: this.handleTouchCancel,
  2563. touchend: this.handleTouchEnd,
  2564. mousedown: this.handleMouseDown,
  2565. mousemove: this.handleMouseMove,
  2566. mouseup: this.handleMouseUp,
  2567. click: this.handleClick,
  2568. selectstart: this.handleSelectStart,
  2569. contextmenu: this.handleContextMenu
  2570. });
  2571. // because we need to call preventDefault
  2572. // because https://www.chromestatus.com/features/5093566007214080
  2573. // TODO: investigate performance because this is a global handler
  2574. window.addEventListener(
  2575. 'touchmove',
  2576. this.handleTouchMoveProxy = function(ev) {
  2577. _this.handleTouchMove($.Event(ev));
  2578. },
  2579. { passive: false } // allows preventDefault()
  2580. );
  2581. // attach a handler to get called when ANY scroll action happens on the page.
  2582. // this was impossible to do with normal on/off because 'scroll' doesn't bubble.
  2583. // http://stackoverflow.com/a/32954565/96342
  2584. window.addEventListener(
  2585. 'scroll',
  2586. this.handleScrollProxy = function(ev) {
  2587. _this.handleScroll($.Event(ev));
  2588. },
  2589. true // useCapture
  2590. );
  2591. },
  2592. unbind: function() {
  2593. this.stopListeningTo($(document));
  2594. window.removeEventListener(
  2595. 'touchmove',
  2596. this.handleTouchMoveProxy
  2597. );
  2598. window.removeEventListener(
  2599. 'scroll',
  2600. this.handleScrollProxy,
  2601. true // useCapture
  2602. );
  2603. },
  2604. // Touch Handlers
  2605. // -----------------------------------------------------------------------------------------------------------------
  2606. handleTouchStart: function(ev) {
  2607. // if a previous touch interaction never ended with a touchend, then implicitly end it,
  2608. // but since a new touch interaction is about to begin, don't start the mouse ignore period.
  2609. this.stopTouch(ev, true); // skipMouseIgnore=true
  2610. this.isTouching = true;
  2611. this.trigger('touchstart', ev);
  2612. },
  2613. handleTouchMove: function(ev) {
  2614. if (this.isTouching) {
  2615. this.trigger('touchmove', ev);
  2616. }
  2617. },
  2618. handleTouchCancel: function(ev) {
  2619. if (this.isTouching) {
  2620. this.trigger('touchcancel', ev);
  2621. // Have touchcancel fire an artificial touchend. That way, handlers won't need to listen to both.
  2622. // If touchend fires later, it won't have any effect b/c isTouching will be false.
  2623. this.stopTouch(ev);
  2624. }
  2625. },
  2626. handleTouchEnd: function(ev) {
  2627. this.stopTouch(ev);
  2628. },
  2629. // Mouse Handlers
  2630. // -----------------------------------------------------------------------------------------------------------------
  2631. handleMouseDown: function(ev) {
  2632. if (!this.shouldIgnoreMouse()) {
  2633. this.trigger('mousedown', ev);
  2634. }
  2635. },
  2636. handleMouseMove: function(ev) {
  2637. if (!this.shouldIgnoreMouse()) {
  2638. this.trigger('mousemove', ev);
  2639. }
  2640. },
  2641. handleMouseUp: function(ev) {
  2642. if (!this.shouldIgnoreMouse()) {
  2643. this.trigger('mouseup', ev);
  2644. }
  2645. },
  2646. handleClick: function(ev) {
  2647. if (!this.shouldIgnoreMouse()) {
  2648. this.trigger('click', ev);
  2649. }
  2650. },
  2651. // Misc Handlers
  2652. // -----------------------------------------------------------------------------------------------------------------
  2653. handleSelectStart: function(ev) {
  2654. this.trigger('selectstart', ev);
  2655. },
  2656. handleContextMenu: function(ev) {
  2657. this.trigger('contextmenu', ev);
  2658. },
  2659. handleScroll: function(ev) {
  2660. this.trigger('scroll', ev);
  2661. },
  2662. // Utils
  2663. // -----------------------------------------------------------------------------------------------------------------
  2664. stopTouch: function(ev, skipMouseIgnore) {
  2665. if (this.isTouching) {
  2666. this.isTouching = false;
  2667. this.trigger('touchend', ev);
  2668. if (!skipMouseIgnore) {
  2669. this.startTouchMouseIgnore();
  2670. }
  2671. }
  2672. },
  2673. startTouchMouseIgnore: function() {
  2674. var _this = this;
  2675. var wait = FC.touchMouseIgnoreWait;
  2676. if (wait) {
  2677. this.mouseIgnoreDepth++;
  2678. setTimeout(function() {
  2679. _this.mouseIgnoreDepth--;
  2680. }, wait);
  2681. }
  2682. },
  2683. shouldIgnoreMouse: function() {
  2684. return this.isTouching || Boolean(this.mouseIgnoreDepth);
  2685. }
  2686. });
  2687. // Singleton
  2688. // ---------------------------------------------------------------------------------------------------------------------
  2689. (function() {
  2690. var globalEmitter = null;
  2691. var neededCount = 0;
  2692. // gets the singleton
  2693. GlobalEmitter.get = function() {
  2694. if (!globalEmitter) {
  2695. globalEmitter = new GlobalEmitter();
  2696. globalEmitter.bind();
  2697. }
  2698. return globalEmitter;
  2699. };
  2700. // called when an object knows it will need a GlobalEmitter in the near future.
  2701. GlobalEmitter.needed = function() {
  2702. GlobalEmitter.get(); // ensures globalEmitter
  2703. neededCount++;
  2704. };
  2705. // called when the object that originally called needed() doesn't need a GlobalEmitter anymore.
  2706. GlobalEmitter.unneeded = function() {
  2707. neededCount--;
  2708. if (!neededCount) { // nobody else needs it
  2709. globalEmitter.unbind();
  2710. globalEmitter = null;
  2711. }
  2712. };
  2713. })();
  2714. ;;
  2715. /* Creates a clone of an element and lets it track the mouse as it moves
  2716. ----------------------------------------------------------------------------------------------------------------------*/
  2717. var MouseFollower = Class.extend(ListenerMixin, {
  2718. options: null,
  2719. sourceEl: null, // the element that will be cloned and made to look like it is dragging
  2720. el: null, // the clone of `sourceEl` that will track the mouse
  2721. parentEl: null, // the element that `el` (the clone) will be attached to
  2722. // the initial position of el, relative to the offset parent. made to match the initial offset of sourceEl
  2723. top0: null,
  2724. left0: null,
  2725. // the absolute coordinates of the initiating touch/mouse action
  2726. y0: null,
  2727. x0: null,
  2728. // the number of pixels the mouse has moved from its initial position
  2729. topDelta: null,
  2730. leftDelta: null,
  2731. isFollowing: false,
  2732. isHidden: false,
  2733. isAnimating: false, // doing the revert animation?
  2734. constructor: function(sourceEl, options) {
  2735. this.options = options = options || {};
  2736. this.sourceEl = sourceEl;
  2737. this.parentEl = options.parentEl ? $(options.parentEl) : sourceEl.parent(); // default to sourceEl's parent
  2738. },
  2739. // Causes the element to start following the mouse
  2740. start: function(ev) {
  2741. if (!this.isFollowing) {
  2742. this.isFollowing = true;
  2743. this.y0 = getEvY(ev);
  2744. this.x0 = getEvX(ev);
  2745. this.topDelta = 0;
  2746. this.leftDelta = 0;
  2747. if (!this.isHidden) {
  2748. this.updatePosition();
  2749. }
  2750. if (getEvIsTouch(ev)) {
  2751. this.listenTo($(document), 'touchmove', this.handleMove);
  2752. }
  2753. else {
  2754. this.listenTo($(document), 'mousemove', this.handleMove);
  2755. }
  2756. }
  2757. },
  2758. // Causes the element to stop following the mouse. If shouldRevert is true, will animate back to original position.
  2759. // `callback` gets invoked when the animation is complete. If no animation, it is invoked immediately.
  2760. stop: function(shouldRevert, callback) {
  2761. var _this = this;
  2762. var revertDuration = this.options.revertDuration;
  2763. function complete() { // might be called by .animate(), which might change `this` context
  2764. _this.isAnimating = false;
  2765. _this.removeElement();
  2766. _this.top0 = _this.left0 = null; // reset state for future updatePosition calls
  2767. if (callback) {
  2768. callback();
  2769. }
  2770. }
  2771. if (this.isFollowing && !this.isAnimating) { // disallow more than one stop animation at a time
  2772. this.isFollowing = false;
  2773. this.stopListeningTo($(document));
  2774. if (shouldRevert && revertDuration && !this.isHidden) { // do a revert animation?
  2775. this.isAnimating = true;
  2776. this.el.animate({
  2777. top: this.top0,
  2778. left: this.left0
  2779. }, {
  2780. duration: revertDuration,
  2781. complete: complete
  2782. });
  2783. }
  2784. else {
  2785. complete();
  2786. }
  2787. }
  2788. },
  2789. // Gets the tracking element. Create it if necessary
  2790. getEl: function() {
  2791. var el = this.el;
  2792. if (!el) {
  2793. el = this.el = this.sourceEl.clone()
  2794. .addClass(this.options.additionalClass || '')
  2795. .css({
  2796. position: 'absolute',
  2797. visibility: '', // in case original element was hidden (commonly through hideEvents())
  2798. display: this.isHidden ? 'none' : '', // for when initially hidden
  2799. margin: 0,
  2800. right: 'auto', // erase and set width instead
  2801. bottom: 'auto', // erase and set height instead
  2802. width: this.sourceEl.width(), // explicit height in case there was a 'right' value
  2803. height: this.sourceEl.height(), // explicit width in case there was a 'bottom' value
  2804. opacity: this.options.opacity || '',
  2805. zIndex: this.options.zIndex
  2806. });
  2807. // we don't want long taps or any mouse interaction causing selection/menus.
  2808. // would use preventSelection(), but that prevents selectstart, causing problems.
  2809. el.addClass('fc-unselectable');
  2810. el.appendTo(this.parentEl);
  2811. }
  2812. return el;
  2813. },
  2814. // Removes the tracking element if it has already been created
  2815. removeElement: function() {
  2816. if (this.el) {
  2817. this.el.remove();
  2818. this.el = null;
  2819. }
  2820. },
  2821. // Update the CSS position of the tracking element
  2822. updatePosition: function() {
  2823. var sourceOffset;
  2824. var origin;
  2825. this.getEl(); // ensure this.el
  2826. // make sure origin info was computed
  2827. if (this.top0 === null) {
  2828. sourceOffset = this.sourceEl.offset();
  2829. origin = this.el.offsetParent().offset();
  2830. this.top0 = sourceOffset.top - origin.top;
  2831. this.left0 = sourceOffset.left - origin.left;
  2832. }
  2833. this.el.css({
  2834. top: this.top0 + this.topDelta,
  2835. left: this.left0 + this.leftDelta
  2836. });
  2837. },
  2838. // Gets called when the user moves the mouse
  2839. handleMove: function(ev) {
  2840. this.topDelta = getEvY(ev) - this.y0;
  2841. this.leftDelta = getEvX(ev) - this.x0;
  2842. if (!this.isHidden) {
  2843. this.updatePosition();
  2844. }
  2845. },
  2846. // Temporarily makes the tracking element invisible. Can be called before following starts
  2847. hide: function() {
  2848. if (!this.isHidden) {
  2849. this.isHidden = true;
  2850. if (this.el) {
  2851. this.el.hide();
  2852. }
  2853. }
  2854. },
  2855. // Show the tracking element after it has been temporarily hidden
  2856. show: function() {
  2857. if (this.isHidden) {
  2858. this.isHidden = false;
  2859. this.updatePosition();
  2860. this.getEl().show();
  2861. }
  2862. }
  2863. });
  2864. ;;
  2865. /* An abstract class comprised of a "grid" of areas that each represent a specific datetime
  2866. ----------------------------------------------------------------------------------------------------------------------*/
  2867. var Grid = FC.Grid = Class.extend(ListenerMixin, {
  2868. // self-config, overridable by subclasses
  2869. hasDayInteractions: true, // can user click/select ranges of time?
  2870. view: null, // a View object
  2871. isRTL: null, // shortcut to the view's isRTL option
  2872. start: null,
  2873. end: null,
  2874. el: null, // the containing element
  2875. elsByFill: null, // a hash of jQuery element sets used for rendering each fill. Keyed by fill name.
  2876. // derived from options
  2877. eventTimeFormat: null,
  2878. displayEventTime: null,
  2879. displayEventEnd: null,
  2880. minResizeDuration: null, // TODO: hack. set by subclasses. minumum event resize duration
  2881. // if defined, holds the unit identified (ex: "year" or "month") that determines the level of granularity
  2882. // of the date areas. if not defined, assumes to be day and time granularity.
  2883. // TODO: port isTimeScale into same system?
  2884. largeUnit: null,
  2885. dayClickListener: null,
  2886. daySelectListener: null,
  2887. segDragListener: null,
  2888. segResizeListener: null,
  2889. externalDragListener: null,
  2890. constructor: function(view) {
  2891. this.view = view;
  2892. this.isRTL = view.opt('isRTL');
  2893. this.elsByFill = {};
  2894. this.dayClickListener = this.buildDayClickListener();
  2895. this.daySelectListener = this.buildDaySelectListener();
  2896. },
  2897. /* Options
  2898. ------------------------------------------------------------------------------------------------------------------*/
  2899. // Generates the format string used for event time text, if not explicitly defined by 'timeFormat'
  2900. computeEventTimeFormat: function() {
  2901. return this.view.opt('smallTimeFormat');
  2902. },
  2903. // Determines whether events should have their end times displayed, if not explicitly defined by 'displayEventTime'.
  2904. // Only applies to non-all-day events.
  2905. computeDisplayEventTime: function() {
  2906. return true;
  2907. },
  2908. // Determines whether events should have their end times displayed, if not explicitly defined by 'displayEventEnd'
  2909. computeDisplayEventEnd: function() {
  2910. return true;
  2911. },
  2912. /* Dates
  2913. ------------------------------------------------------------------------------------------------------------------*/
  2914. // Tells the grid about what period of time to display.
  2915. // Any date-related internal data should be generated.
  2916. setRange: function(range) {
  2917. this.start = range.start.clone();
  2918. this.end = range.end.clone();
  2919. this.rangeUpdated();
  2920. this.processRangeOptions();
  2921. },
  2922. // Called when internal variables that rely on the range should be updated
  2923. rangeUpdated: function() {
  2924. },
  2925. // Updates values that rely on options and also relate to range
  2926. processRangeOptions: function() {
  2927. var view = this.view;
  2928. var displayEventTime;
  2929. var displayEventEnd;
  2930. this.eventTimeFormat =
  2931. view.opt('eventTimeFormat') ||
  2932. view.opt('timeFormat') || // deprecated
  2933. this.computeEventTimeFormat();
  2934. displayEventTime = view.opt('displayEventTime');
  2935. if (displayEventTime == null) {
  2936. displayEventTime = this.computeDisplayEventTime(); // might be based off of range
  2937. }
  2938. displayEventEnd = view.opt('displayEventEnd');
  2939. if (displayEventEnd == null) {
  2940. displayEventEnd = this.computeDisplayEventEnd(); // might be based off of range
  2941. }
  2942. this.displayEventTime = displayEventTime;
  2943. this.displayEventEnd = displayEventEnd;
  2944. },
  2945. // Converts a span (has unzoned start/end and any other grid-specific location information)
  2946. // into an array of segments (pieces of events whose format is decided by the grid).
  2947. spanToSegs: function(span) {
  2948. // subclasses must implement
  2949. },
  2950. // Diffs the two dates, returning a duration, based on granularity of the grid
  2951. // TODO: port isTimeScale into this system?
  2952. diffDates: function(a, b) {
  2953. if (this.largeUnit) {
  2954. return diffByUnit(a, b, this.largeUnit);
  2955. }
  2956. else {
  2957. return diffDayTime(a, b);
  2958. }
  2959. },
  2960. /* Hit Area
  2961. ------------------------------------------------------------------------------------------------------------------*/
  2962. hitsNeededDepth: 0, // necessary because multiple callers might need the same hits
  2963. hitsNeeded: function() {
  2964. if (!(this.hitsNeededDepth++)) {
  2965. this.prepareHits();
  2966. }
  2967. },
  2968. hitsNotNeeded: function() {
  2969. if (this.hitsNeededDepth && !(--this.hitsNeededDepth)) {
  2970. this.releaseHits();
  2971. }
  2972. },
  2973. // Called before one or more queryHit calls might happen. Should prepare any cached coordinates for queryHit
  2974. prepareHits: function() {
  2975. },
  2976. // Called when queryHit calls have subsided. Good place to clear any coordinate caches.
  2977. releaseHits: function() {
  2978. },
  2979. // Given coordinates from the topleft of the document, return data about the date-related area underneath.
  2980. // Can return an object with arbitrary properties (although top/right/left/bottom are encouraged).
  2981. // Must have a `grid` property, a reference to this current grid. TODO: avoid this
  2982. // The returned object will be processed by getHitSpan and getHitEl.
  2983. queryHit: function(leftOffset, topOffset) {
  2984. },
  2985. // Given position-level information about a date-related area within the grid,
  2986. // should return an object with at least a start/end date. Can provide other information as well.
  2987. getHitSpan: function(hit) {
  2988. },
  2989. // Given position-level information about a date-related area within the grid,
  2990. // should return a jQuery element that best represents it. passed to dayClick callback.
  2991. getHitEl: function(hit) {
  2992. },
  2993. /* Rendering
  2994. ------------------------------------------------------------------------------------------------------------------*/
  2995. // Sets the container element that the grid should render inside of.
  2996. // Does other DOM-related initializations.
  2997. setElement: function(el) {
  2998. this.el = el;
  2999. if (this.hasDayInteractions) {
  3000. preventSelection(el);
  3001. this.bindDayHandler('touchstart', this.dayTouchStart);
  3002. this.bindDayHandler('mousedown', this.dayMousedown);
  3003. }
  3004. // attach event-element-related handlers. in Grid.events
  3005. // same garbage collection note as above.
  3006. this.bindSegHandlers();
  3007. this.bindGlobalHandlers();
  3008. },
  3009. bindDayHandler: function(name, handler) {
  3010. var _this = this;
  3011. // attach a handler to the grid's root element.
  3012. // jQuery will take care of unregistering them when removeElement gets called.
  3013. this.el.on(name, function(ev) {
  3014. if (
  3015. !$(ev.target).is(
  3016. _this.segSelector + ',' + // directly on an event element
  3017. _this.segSelector + ' *,' + // within an event element
  3018. '.fc-more,' + // a "more.." link
  3019. 'a[data-goto]' // a clickable nav link
  3020. )
  3021. ) {
  3022. return handler.call(_this, ev);
  3023. }
  3024. });
  3025. },
  3026. // Removes the grid's container element from the DOM. Undoes any other DOM-related attachments.
  3027. // DOES NOT remove any content beforehand (doesn't clear events or call unrenderDates), unlike View
  3028. removeElement: function() {
  3029. this.unbindGlobalHandlers();
  3030. this.clearDragListeners();
  3031. this.el.remove();
  3032. // NOTE: we don't null-out this.el for the same reasons we don't do it within View::removeElement
  3033. },
  3034. // Renders the basic structure of grid view before any content is rendered
  3035. renderSkeleton: function() {
  3036. // subclasses should implement
  3037. },
  3038. // Renders the grid's date-related content (like areas that represent days/times).
  3039. // Assumes setRange has already been called and the skeleton has already been rendered.
  3040. renderDates: function() {
  3041. // subclasses should implement
  3042. },
  3043. // Unrenders the grid's date-related content
  3044. unrenderDates: function() {
  3045. // subclasses should implement
  3046. },
  3047. /* Handlers
  3048. ------------------------------------------------------------------------------------------------------------------*/
  3049. // Binds DOM handlers to elements that reside outside the grid, such as the document
  3050. bindGlobalHandlers: function() {
  3051. this.listenTo($(document), {
  3052. dragstart: this.externalDragStart, // jqui
  3053. sortstart: this.externalDragStart // jqui
  3054. });
  3055. },
  3056. // Unbinds DOM handlers from elements that reside outside the grid
  3057. unbindGlobalHandlers: function() {
  3058. this.stopListeningTo($(document));
  3059. },
  3060. // Process a mousedown on an element that represents a day. For day clicking and selecting.
  3061. dayMousedown: function(ev) {
  3062. var view = this.view;
  3063. // prevent a user's clickaway for unselecting a range or an event from
  3064. // causing a dayClick or starting an immediate new selection.
  3065. if (view.isSelected || view.selectedEvent) {
  3066. return;
  3067. }
  3068. this.dayClickListener.startInteraction(ev);
  3069. if (view.opt('selectable')) {
  3070. this.daySelectListener.startInteraction(ev, {
  3071. distance: view.opt('selectMinDistance')
  3072. });
  3073. }
  3074. },
  3075. dayTouchStart: function(ev) {
  3076. var view = this.view;
  3077. var selectLongPressDelay;
  3078. // prevent a user's clickaway for unselecting a range or an event from
  3079. // causing a dayClick or starting an immediate new selection.
  3080. if (view.isSelected || view.selectedEvent) {
  3081. return;
  3082. }
  3083. selectLongPressDelay = view.opt('selectLongPressDelay');
  3084. if (selectLongPressDelay == null) {
  3085. selectLongPressDelay = view.opt('longPressDelay'); // fallback
  3086. }
  3087. this.dayClickListener.startInteraction(ev);
  3088. if (view.opt('selectable')) {
  3089. this.daySelectListener.startInteraction(ev, {
  3090. delay: selectLongPressDelay
  3091. });
  3092. }
  3093. },
  3094. // Creates a listener that tracks the user's drag across day elements, for day clicking.
  3095. buildDayClickListener: function() {
  3096. var _this = this;
  3097. var view = this.view;
  3098. var dayClickHit; // null if invalid dayClick
  3099. var dragListener = new HitDragListener(this, {
  3100. scroll: view.opt('dragScroll'),
  3101. interactionStart: function() {
  3102. dayClickHit = dragListener.origHit;
  3103. },
  3104. hitOver: function(hit, isOrig, origHit) {
  3105. // if user dragged to another cell at any point, it can no longer be a dayClick
  3106. if (!isOrig) {
  3107. dayClickHit = null;
  3108. }
  3109. },
  3110. hitOut: function() { // called before mouse moves to a different hit OR moved out of all hits
  3111. dayClickHit = null;
  3112. },
  3113. interactionEnd: function(ev, isCancelled) {
  3114. if (!isCancelled && dayClickHit) {
  3115. view.triggerDayClick(
  3116. _this.getHitSpan(dayClickHit),
  3117. _this.getHitEl(dayClickHit),
  3118. ev
  3119. );
  3120. }
  3121. }
  3122. });
  3123. // because dayClickListener won't be called with any time delay, "dragging" will begin immediately,
  3124. // which will kill any touchmoving/scrolling. Prevent this.
  3125. dragListener.shouldCancelTouchScroll = false;
  3126. dragListener.scrollAlwaysKills = true;
  3127. return dragListener;
  3128. },
  3129. // Creates a listener that tracks the user's drag across day elements, for day selecting.
  3130. buildDaySelectListener: function() {
  3131. var _this = this;
  3132. var view = this.view;
  3133. var selectionSpan; // null if invalid selection
  3134. var dragListener = new HitDragListener(this, {
  3135. scroll: view.opt('dragScroll'),
  3136. interactionStart: function() {
  3137. selectionSpan = null;
  3138. },
  3139. dragStart: function() {
  3140. view.unselect(); // since we could be rendering a new selection, we want to clear any old one
  3141. },
  3142. hitOver: function(hit, isOrig, origHit) {
  3143. if (origHit) { // click needs to have started on a hit
  3144. selectionSpan = _this.computeSelection(
  3145. _this.getHitSpan(origHit),
  3146. _this.getHitSpan(hit)
  3147. );
  3148. if (selectionSpan) {
  3149. _this.renderSelection(selectionSpan);
  3150. }
  3151. else if (selectionSpan === false) {
  3152. disableCursor();
  3153. }
  3154. }
  3155. },
  3156. hitOut: function() { // called before mouse moves to a different hit OR moved out of all hits
  3157. selectionSpan = null;
  3158. _this.unrenderSelection();
  3159. },
  3160. hitDone: function() { // called after a hitOut OR before a dragEnd
  3161. enableCursor();
  3162. },
  3163. interactionEnd: function(ev, isCancelled) {
  3164. if (!isCancelled && selectionSpan) {
  3165. // the selection will already have been rendered. just report it
  3166. view.reportSelection(selectionSpan, ev);
  3167. }
  3168. }
  3169. });
  3170. return dragListener;
  3171. },
  3172. // Kills all in-progress dragging.
  3173. // Useful for when public API methods that result in re-rendering are invoked during a drag.
  3174. // Also useful for when touch devices misbehave and don't fire their touchend.
  3175. clearDragListeners: function() {
  3176. this.dayClickListener.endInteraction();
  3177. this.daySelectListener.endInteraction();
  3178. if (this.segDragListener) {
  3179. this.segDragListener.endInteraction(); // will clear this.segDragListener
  3180. }
  3181. if (this.segResizeListener) {
  3182. this.segResizeListener.endInteraction(); // will clear this.segResizeListener
  3183. }
  3184. if (this.externalDragListener) {
  3185. this.externalDragListener.endInteraction(); // will clear this.externalDragListener
  3186. }
  3187. },
  3188. /* Event Helper
  3189. ------------------------------------------------------------------------------------------------------------------*/
  3190. // TODO: should probably move this to Grid.events, like we did event dragging / resizing
  3191. // Renders a mock event at the given event location, which contains zoned start/end properties.
  3192. // Returns all mock event elements.
  3193. renderEventLocationHelper: function(eventLocation, sourceSeg) {
  3194. var fakeEvent = this.fabricateHelperEvent(eventLocation, sourceSeg);
  3195. return this.renderHelper(fakeEvent, sourceSeg); // do the actual rendering
  3196. },
  3197. // Builds a fake event given zoned event date properties and a segment is should be inspired from.
  3198. // The range's end can be null, in which case the mock event that is rendered will have a null end time.
  3199. // `sourceSeg` is the internal segment object involved in the drag. If null, something external is dragging.
  3200. fabricateHelperEvent: function(eventLocation, sourceSeg) {
  3201. var fakeEvent = sourceSeg ? createObject(sourceSeg.event) : {}; // mask the original event object if possible
  3202. fakeEvent.start = eventLocation.start.clone();
  3203. fakeEvent.end = eventLocation.end ? eventLocation.end.clone() : null;
  3204. fakeEvent.allDay = null; // force it to be freshly computed by normalizeEventDates
  3205. this.view.calendar.normalizeEventDates(fakeEvent);
  3206. // this extra className will be useful for differentiating real events from mock events in CSS
  3207. fakeEvent.className = (fakeEvent.className || []).concat('fc-helper');
  3208. // if something external is being dragged in, don't render a resizer
  3209. if (!sourceSeg) {
  3210. fakeEvent.editable = false;
  3211. }
  3212. return fakeEvent;
  3213. },
  3214. // Renders a mock event. Given zoned event date properties.
  3215. // Must return all mock event elements.
  3216. renderHelper: function(eventLocation, sourceSeg) {
  3217. // subclasses must implement
  3218. },
  3219. // Unrenders a mock event
  3220. unrenderHelper: function() {
  3221. // subclasses must implement
  3222. },
  3223. /* Selection
  3224. ------------------------------------------------------------------------------------------------------------------*/
  3225. // Renders a visual indication of a selection. Will highlight by default but can be overridden by subclasses.
  3226. // Given a span (unzoned start/end and other misc data)
  3227. renderSelection: function(span) {
  3228. this.renderHighlight(span);
  3229. },
  3230. // Unrenders any visual indications of a selection. Will unrender a highlight by default.
  3231. unrenderSelection: function() {
  3232. this.unrenderHighlight();
  3233. },
  3234. // Given the first and last date-spans of a selection, returns another date-span object.
  3235. // Subclasses can override and provide additional data in the span object. Will be passed to renderSelection().
  3236. // Will return false if the selection is invalid and this should be indicated to the user.
  3237. // Will return null/undefined if a selection invalid but no error should be reported.
  3238. computeSelection: function(span0, span1) {
  3239. var span = this.computeSelectionSpan(span0, span1);
  3240. if (span && !this.view.calendar.isSelectionSpanAllowed(span)) {
  3241. return false;
  3242. }
  3243. return span;
  3244. },
  3245. // Given two spans, must return the combination of the two.
  3246. // TODO: do this separation of concerns (combining VS validation) for event dnd/resize too.
  3247. computeSelectionSpan: function(span0, span1) {
  3248. var dates = [ span0.start, span0.end, span1.start, span1.end ];
  3249. dates.sort(compareNumbers); // sorts chronologically. works with Moments
  3250. return { start: dates[0].clone(), end: dates[3].clone() };
  3251. },
  3252. /* Highlight
  3253. ------------------------------------------------------------------------------------------------------------------*/
  3254. // Renders an emphasis on the given date range. Given a span (unzoned start/end and other misc data)
  3255. renderHighlight: function(span) {
  3256. this.renderFill('highlight', this.spanToSegs(span));
  3257. },
  3258. // Unrenders the emphasis on a date range
  3259. unrenderHighlight: function() {
  3260. this.unrenderFill('highlight');
  3261. },
  3262. // Generates an array of classNames for rendering the highlight. Used by the fill system.
  3263. highlightSegClasses: function() {
  3264. return [ 'fc-highlight' ];
  3265. },
  3266. /* Business Hours
  3267. ------------------------------------------------------------------------------------------------------------------*/
  3268. renderBusinessHours: function() {
  3269. },
  3270. unrenderBusinessHours: function() {
  3271. },
  3272. /* Now Indicator
  3273. ------------------------------------------------------------------------------------------------------------------*/
  3274. getNowIndicatorUnit: function() {
  3275. },
  3276. renderNowIndicator: function(date) {
  3277. },
  3278. unrenderNowIndicator: function() {
  3279. },
  3280. /* Fill System (highlight, background events, business hours)
  3281. --------------------------------------------------------------------------------------------------------------------
  3282. TODO: remove this system. like we did in TimeGrid
  3283. */
  3284. // Renders a set of rectangles over the given segments of time.
  3285. // MUST RETURN a subset of segs, the segs that were actually rendered.
  3286. // Responsible for populating this.elsByFill. TODO: better API for expressing this requirement
  3287. renderFill: function(type, segs) {
  3288. // subclasses must implement
  3289. },
  3290. // Unrenders a specific type of fill that is currently rendered on the grid
  3291. unrenderFill: function(type) {
  3292. var el = this.elsByFill[type];
  3293. if (el) {
  3294. el.remove();
  3295. delete this.elsByFill[type];
  3296. }
  3297. },
  3298. // Renders and assigns an `el` property for each fill segment. Generic enough to work with different types.
  3299. // Only returns segments that successfully rendered.
  3300. // To be harnessed by renderFill (implemented by subclasses).
  3301. // Analagous to renderFgSegEls.
  3302. renderFillSegEls: function(type, segs) {
  3303. var _this = this;
  3304. var segElMethod = this[type + 'SegEl'];
  3305. var html = '';
  3306. var renderedSegs = [];
  3307. var i;
  3308. if (segs.length) {
  3309. // build a large concatenation of segment HTML
  3310. for (i = 0; i < segs.length; i++) {
  3311. html += this.fillSegHtml(type, segs[i]);
  3312. }
  3313. // Grab individual elements from the combined HTML string. Use each as the default rendering.
  3314. // Then, compute the 'el' for each segment.
  3315. $(html).each(function(i, node) {
  3316. var seg = segs[i];
  3317. var el = $(node);
  3318. // allow custom filter methods per-type
  3319. if (segElMethod) {
  3320. el = segElMethod.call(_this, seg, el);
  3321. }
  3322. if (el) { // custom filters did not cancel the render
  3323. el = $(el); // allow custom filter to return raw DOM node
  3324. // correct element type? (would be bad if a non-TD were inserted into a table for example)
  3325. if (el.is(_this.fillSegTag)) {
  3326. seg.el = el;
  3327. renderedSegs.push(seg);
  3328. }
  3329. }
  3330. });
  3331. }
  3332. return renderedSegs;
  3333. },
  3334. fillSegTag: 'div', // subclasses can override
  3335. // Builds the HTML needed for one fill segment. Generic enough to work with different types.
  3336. fillSegHtml: function(type, seg) {
  3337. // custom hooks per-type
  3338. var classesMethod = this[type + 'SegClasses'];
  3339. var cssMethod = this[type + 'SegCss'];
  3340. var classes = classesMethod ? classesMethod.call(this, seg) : [];
  3341. var css = cssToStr(cssMethod ? cssMethod.call(this, seg) : {});
  3342. return '<' + this.fillSegTag +
  3343. (classes.length ? ' class="' + classes.join(' ') + '"' : '') +
  3344. (css ? ' style="' + css + '"' : '') +
  3345. ' />';
  3346. },
  3347. /* Generic rendering utilities for subclasses
  3348. ------------------------------------------------------------------------------------------------------------------*/
  3349. // Computes HTML classNames for a single-day element
  3350. getDayClasses: function(date, noThemeHighlight) {
  3351. var view = this.view;
  3352. var today = view.calendar.getNow();
  3353. var classes = [ 'fc-' + dayIDs[date.day()] ];
  3354. if (
  3355. view.intervalDuration.as('months') == 1 &&
  3356. date.month() != view.intervalStart.month()
  3357. ) {
  3358. classes.push('fc-other-month');
  3359. }
  3360. if (date.isSame(today, 'day')) {
  3361. classes.push('fc-today');
  3362. if (noThemeHighlight !== true) {
  3363. classes.push(view.highlightStateClass);
  3364. }
  3365. }
  3366. else if (date < today) {
  3367. classes.push('fc-past');
  3368. }
  3369. else {
  3370. classes.push('fc-future');
  3371. }
  3372. return classes;
  3373. }
  3374. });
  3375. ;;
  3376. /* Event-rendering and event-interaction methods for the abstract Grid class
  3377. ----------------------------------------------------------------------------------------------------------------------*/
  3378. Grid.mixin({
  3379. // self-config, overridable by subclasses
  3380. segSelector: '.fc-event-container > *', // what constitutes an event element?
  3381. mousedOverSeg: null, // the segment object the user's mouse is over. null if over nothing
  3382. isDraggingSeg: false, // is a segment being dragged? boolean
  3383. isResizingSeg: false, // is a segment being resized? boolean
  3384. isDraggingExternal: false, // jqui-dragging an external element? boolean
  3385. segs: null, // the *event* segments currently rendered in the grid. TODO: rename to `eventSegs`
  3386. // Renders the given events onto the grid
  3387. renderEvents: function(events) {
  3388. var bgEvents = [];
  3389. var fgEvents = [];
  3390. var i;
  3391. for (i = 0; i < events.length; i++) {
  3392. (isBgEvent(events[i]) ? bgEvents : fgEvents).push(events[i]);
  3393. }
  3394. this.segs = [].concat( // record all segs
  3395. this.renderBgEvents(bgEvents),
  3396. this.renderFgEvents(fgEvents)
  3397. );
  3398. },
  3399. renderBgEvents: function(events) {
  3400. var segs = this.eventsToSegs(events);
  3401. // renderBgSegs might return a subset of segs, segs that were actually rendered
  3402. return this.renderBgSegs(segs) || segs;
  3403. },
  3404. renderFgEvents: function(events) {
  3405. var segs = this.eventsToSegs(events);
  3406. // renderFgSegs might return a subset of segs, segs that were actually rendered
  3407. return this.renderFgSegs(segs) || segs;
  3408. },
  3409. // Unrenders all events currently rendered on the grid
  3410. unrenderEvents: function() {
  3411. this.handleSegMouseout(); // trigger an eventMouseout if user's mouse is over an event
  3412. this.clearDragListeners();
  3413. this.unrenderFgSegs();
  3414. this.unrenderBgSegs();
  3415. this.segs = null;
  3416. },
  3417. // Retrieves all rendered segment objects currently rendered on the grid
  3418. getEventSegs: function() {
  3419. return this.segs || [];
  3420. },
  3421. /* Foreground Segment Rendering
  3422. ------------------------------------------------------------------------------------------------------------------*/
  3423. // Renders foreground event segments onto the grid. May return a subset of segs that were rendered.
  3424. renderFgSegs: function(segs) {
  3425. // subclasses must implement
  3426. },
  3427. // Unrenders all currently rendered foreground segments
  3428. unrenderFgSegs: function() {
  3429. // subclasses must implement
  3430. },
  3431. // Renders and assigns an `el` property for each foreground event segment.
  3432. // Only returns segments that successfully rendered.
  3433. // A utility that subclasses may use.
  3434. renderFgSegEls: function(segs, disableResizing) {
  3435. var view = this.view;
  3436. var html = '';
  3437. var renderedSegs = [];
  3438. var i;
  3439. if (segs.length) { // don't build an empty html string
  3440. // build a large concatenation of event segment HTML
  3441. for (i = 0; i < segs.length; i++) {
  3442. html += this.fgSegHtml(segs[i], disableResizing);
  3443. }
  3444. // Grab individual elements from the combined HTML string. Use each as the default rendering.
  3445. // Then, compute the 'el' for each segment. An el might be null if the eventRender callback returned false.
  3446. $(html).each(function(i, node) {
  3447. var seg = segs[i];
  3448. var el = view.resolveEventEl(seg.event, $(node));
  3449. if (el) {
  3450. el.data('fc-seg', seg); // used by handlers
  3451. seg.el = el;
  3452. renderedSegs.push(seg);
  3453. }
  3454. });
  3455. }
  3456. return renderedSegs;
  3457. },
  3458. // Generates the HTML for the default rendering of a foreground event segment. Used by renderFgSegEls()
  3459. fgSegHtml: function(seg, disableResizing) {
  3460. // subclasses should implement
  3461. },
  3462. /* Background Segment Rendering
  3463. ------------------------------------------------------------------------------------------------------------------*/
  3464. // Renders the given background event segments onto the grid.
  3465. // Returns a subset of the segs that were actually rendered.
  3466. renderBgSegs: function(segs) {
  3467. return this.renderFill('bgEvent', segs);
  3468. },
  3469. // Unrenders all the currently rendered background event segments
  3470. unrenderBgSegs: function() {
  3471. this.unrenderFill('bgEvent');
  3472. },
  3473. // Renders a background event element, given the default rendering. Called by the fill system.
  3474. bgEventSegEl: function(seg, el) {
  3475. return this.view.resolveEventEl(seg.event, el); // will filter through eventRender
  3476. },
  3477. // Generates an array of classNames to be used for the default rendering of a background event.
  3478. // Called by fillSegHtml.
  3479. bgEventSegClasses: function(seg) {
  3480. var event = seg.event;
  3481. var source = event.source || {};
  3482. return [ 'fc-bgevent' ].concat(
  3483. event.className,
  3484. source.className || []
  3485. );
  3486. },
  3487. // Generates a semicolon-separated CSS string to be used for the default rendering of a background event.
  3488. // Called by fillSegHtml.
  3489. bgEventSegCss: function(seg) {
  3490. return {
  3491. 'background-color': this.getSegSkinCss(seg)['background-color']
  3492. };
  3493. },
  3494. // Generates an array of classNames to be used for the rendering business hours overlay. Called by the fill system.
  3495. // Called by fillSegHtml.
  3496. businessHoursSegClasses: function(seg) {
  3497. return [ 'fc-nonbusiness', 'fc-bgevent' ];
  3498. },
  3499. /* Business Hours
  3500. ------------------------------------------------------------------------------------------------------------------*/
  3501. // Compute business hour segs for the grid's current date range.
  3502. // Caller must ask if whole-day business hours are needed.
  3503. // If no `businessHours` configuration value is specified, assumes the calendar default.
  3504. buildBusinessHourSegs: function(wholeDay, businessHours) {
  3505. return this.eventsToSegs(
  3506. this.buildBusinessHourEvents(wholeDay, businessHours)
  3507. );
  3508. },
  3509. // Compute business hour *events* for the grid's current date range.
  3510. // Caller must ask if whole-day business hours are needed.
  3511. // If no `businessHours` configuration value is specified, assumes the calendar default.
  3512. buildBusinessHourEvents: function(wholeDay, businessHours) {
  3513. var calendar = this.view.calendar;
  3514. var events;
  3515. if (businessHours == null) {
  3516. // fallback
  3517. // access from calendawr. don't access from view. doesn't update with dynamic options.
  3518. businessHours = calendar.options.businessHours;
  3519. }
  3520. events = calendar.computeBusinessHourEvents(wholeDay, businessHours);
  3521. // HACK. Eventually refactor business hours "events" system.
  3522. // If no events are given, but businessHours is activated, this means the entire visible range should be
  3523. // marked as *not* business-hours, via inverse-background rendering.
  3524. if (!events.length && businessHours) {
  3525. events = [
  3526. $.extend({}, BUSINESS_HOUR_EVENT_DEFAULTS, {
  3527. start: this.view.end, // guaranteed out-of-range
  3528. end: this.view.end, // "
  3529. dow: null
  3530. })
  3531. ];
  3532. }
  3533. return events;
  3534. },
  3535. /* Handlers
  3536. ------------------------------------------------------------------------------------------------------------------*/
  3537. // Attaches event-element-related handlers for *all* rendered event segments of the view.
  3538. bindSegHandlers: function() {
  3539. this.bindSegHandlersToEl(this.el);
  3540. },
  3541. // Attaches event-element-related handlers to an arbitrary container element. leverages bubbling.
  3542. bindSegHandlersToEl: function(el) {
  3543. this.bindSegHandlerToEl(el, 'touchstart', this.handleSegTouchStart);
  3544. this.bindSegHandlerToEl(el, 'mouseenter', this.handleSegMouseover);
  3545. this.bindSegHandlerToEl(el, 'mouseleave', this.handleSegMouseout);
  3546. this.bindSegHandlerToEl(el, 'mousedown', this.handleSegMousedown);
  3547. this.bindSegHandlerToEl(el, 'click', this.handleSegClick);
  3548. },
  3549. // Executes a handler for any a user-interaction on a segment.
  3550. // Handler gets called with (seg, ev), and with the `this` context of the Grid
  3551. bindSegHandlerToEl: function(el, name, handler) {
  3552. var _this = this;
  3553. el.on(name, this.segSelector, function(ev) {
  3554. var seg = $(this).data('fc-seg'); // grab segment data. put there by View::renderEvents
  3555. // only call the handlers if there is not a drag/resize in progress
  3556. if (seg && !_this.isDraggingSeg && !_this.isResizingSeg) {
  3557. return handler.call(_this, seg, ev); // context will be the Grid
  3558. }
  3559. });
  3560. },
  3561. handleSegClick: function(seg, ev) {
  3562. var res = this.view.publiclyTrigger('eventClick', seg.el[0], seg.event, ev); // can return `false` to cancel
  3563. if (res === false) {
  3564. ev.preventDefault();
  3565. }
  3566. },
  3567. // Updates internal state and triggers handlers for when an event element is moused over
  3568. handleSegMouseover: function(seg, ev) {
  3569. if (
  3570. !GlobalEmitter.get().shouldIgnoreMouse() &&
  3571. !this.mousedOverSeg
  3572. ) {
  3573. this.mousedOverSeg = seg;
  3574. if (this.view.isEventResizable(seg.event)) {
  3575. seg.el.addClass('fc-allow-mouse-resize');
  3576. }
  3577. this.view.publiclyTrigger('eventMouseover', seg.el[0], seg.event, ev);
  3578. }
  3579. },
  3580. // Updates internal state and triggers handlers for when an event element is moused out.
  3581. // Can be given no arguments, in which case it will mouseout the segment that was previously moused over.
  3582. handleSegMouseout: function(seg, ev) {
  3583. ev = ev || {}; // if given no args, make a mock mouse event
  3584. if (this.mousedOverSeg) {
  3585. seg = seg || this.mousedOverSeg; // if given no args, use the currently moused-over segment
  3586. this.mousedOverSeg = null;
  3587. if (this.view.isEventResizable(seg.event)) {
  3588. seg.el.removeClass('fc-allow-mouse-resize');
  3589. }
  3590. this.view.publiclyTrigger('eventMouseout', seg.el[0], seg.event, ev);
  3591. }
  3592. },
  3593. handleSegMousedown: function(seg, ev) {
  3594. var isResizing = this.startSegResize(seg, ev, { distance: 5 });
  3595. if (!isResizing && this.view.isEventDraggable(seg.event)) {
  3596. this.buildSegDragListener(seg)
  3597. .startInteraction(ev, {
  3598. distance: 5
  3599. });
  3600. }
  3601. },
  3602. handleSegTouchStart: function(seg, ev) {
  3603. var view = this.view;
  3604. var event = seg.event;
  3605. var isSelected = view.isEventSelected(event);
  3606. var isDraggable = view.isEventDraggable(event);
  3607. var isResizable = view.isEventResizable(event);
  3608. var isResizing = false;
  3609. var dragListener;
  3610. var eventLongPressDelay;
  3611. if (isSelected && isResizable) {
  3612. // only allow resizing of the event is selected
  3613. isResizing = this.startSegResize(seg, ev);
  3614. }
  3615. if (!isResizing && (isDraggable || isResizable)) { // allowed to be selected?
  3616. eventLongPressDelay = view.opt('eventLongPressDelay');
  3617. if (eventLongPressDelay == null) {
  3618. eventLongPressDelay = view.opt('longPressDelay'); // fallback
  3619. }
  3620. dragListener = isDraggable ?
  3621. this.buildSegDragListener(seg) :
  3622. this.buildSegSelectListener(seg); // seg isn't draggable, but still needs to be selected
  3623. dragListener.startInteraction(ev, { // won't start if already started
  3624. delay: isSelected ? 0 : eventLongPressDelay // do delay if not already selected
  3625. });
  3626. }
  3627. },
  3628. // returns boolean whether resizing actually started or not.
  3629. // assumes the seg allows resizing.
  3630. // `dragOptions` are optional.
  3631. startSegResize: function(seg, ev, dragOptions) {
  3632. if ($(ev.target).is('.fc-resizer')) {
  3633. this.buildSegResizeListener(seg, $(ev.target).is('.fc-start-resizer'))
  3634. .startInteraction(ev, dragOptions);
  3635. return true;
  3636. }
  3637. return false;
  3638. },
  3639. /* Event Dragging
  3640. ------------------------------------------------------------------------------------------------------------------*/
  3641. // Builds a listener that will track user-dragging on an event segment.
  3642. // Generic enough to work with any type of Grid.
  3643. // Has side effect of setting/unsetting `segDragListener`
  3644. buildSegDragListener: function(seg) {
  3645. var _this = this;
  3646. var view = this.view;
  3647. var calendar = view.calendar;
  3648. var el = seg.el;
  3649. var event = seg.event;
  3650. var isDragging;
  3651. var mouseFollower; // A clone of the original element that will move with the mouse
  3652. var dropLocation; // zoned event date properties
  3653. if (this.segDragListener) {
  3654. return this.segDragListener;
  3655. }
  3656. // Tracks mouse movement over the *view's* coordinate map. Allows dragging and dropping between subcomponents
  3657. // of the view.
  3658. var dragListener = this.segDragListener = new HitDragListener(view, {
  3659. scroll: view.opt('dragScroll'),
  3660. subjectEl: el,
  3661. subjectCenter: true,
  3662. interactionStart: function(ev) {
  3663. seg.component = _this; // for renderDrag
  3664. isDragging = false;
  3665. mouseFollower = new MouseFollower(seg.el, {
  3666. additionalClass: 'fc-dragging',
  3667. parentEl: view.el,
  3668. opacity: dragListener.isTouch ? null : view.opt('dragOpacity'),
  3669. revertDuration: view.opt('dragRevertDuration'),
  3670. zIndex: 2 // one above the .fc-view
  3671. });
  3672. mouseFollower.hide(); // don't show until we know this is a real drag
  3673. mouseFollower.start(ev);
  3674. },
  3675. dragStart: function(ev) {
  3676. if (dragListener.isTouch && !view.isEventSelected(event)) {
  3677. // if not previously selected, will fire after a delay. then, select the event
  3678. view.selectEvent(event);
  3679. }
  3680. isDragging = true;
  3681. _this.handleSegMouseout(seg, ev); // ensure a mouseout on the manipulated event has been reported
  3682. _this.segDragStart(seg, ev);
  3683. view.hideEvent(event); // hide all event segments. our mouseFollower will take over
  3684. },
  3685. hitOver: function(hit, isOrig, origHit) {
  3686. var dragHelperEls;
  3687. // starting hit could be forced (DayGrid.limit)
  3688. if (seg.hit) {
  3689. origHit = seg.hit;
  3690. }
  3691. // since we are querying the parent view, might not belong to this grid
  3692. dropLocation = _this.computeEventDrop(
  3693. origHit.component.getHitSpan(origHit),
  3694. hit.component.getHitSpan(hit),
  3695. event
  3696. );
  3697. if (dropLocation && !calendar.isEventSpanAllowed(_this.eventToSpan(dropLocation), event)) {
  3698. disableCursor();
  3699. dropLocation = null;
  3700. }
  3701. // if a valid drop location, have the subclass render a visual indication
  3702. if (dropLocation && (dragHelperEls = view.renderDrag(dropLocation, seg))) {
  3703. dragHelperEls.addClass('fc-dragging');
  3704. if (!dragListener.isTouch) {
  3705. _this.applyDragOpacity(dragHelperEls);
  3706. }
  3707. mouseFollower.hide(); // if the subclass is already using a mock event "helper", hide our own
  3708. }
  3709. else {
  3710. mouseFollower.show(); // otherwise, have the helper follow the mouse (no snapping)
  3711. }
  3712. if (isOrig) {
  3713. dropLocation = null; // needs to have moved hits to be a valid drop
  3714. }
  3715. },
  3716. hitOut: function() { // called before mouse moves to a different hit OR moved out of all hits
  3717. view.unrenderDrag(); // unrender whatever was done in renderDrag
  3718. mouseFollower.show(); // show in case we are moving out of all hits
  3719. dropLocation = null;
  3720. },
  3721. hitDone: function() { // Called after a hitOut OR before a dragEnd
  3722. enableCursor();
  3723. },
  3724. interactionEnd: function(ev) {
  3725. delete seg.component; // prevent side effects
  3726. // do revert animation if hasn't changed. calls a callback when finished (whether animation or not)
  3727. mouseFollower.stop(!dropLocation, function() {
  3728. if (isDragging) {
  3729. view.unrenderDrag();
  3730. _this.segDragStop(seg, ev);
  3731. }
  3732. if (dropLocation) {
  3733. // no need to re-show original, will rerender all anyways. esp important if eventRenderWait
  3734. view.reportSegDrop(seg, dropLocation, _this.largeUnit, el, ev);
  3735. }
  3736. else {
  3737. view.showEvent(event);
  3738. }
  3739. });
  3740. _this.segDragListener = null;
  3741. }
  3742. });
  3743. return dragListener;
  3744. },
  3745. // seg isn't draggable, but let's use a generic DragListener
  3746. // simply for the delay, so it can be selected.
  3747. // Has side effect of setting/unsetting `segDragListener`
  3748. buildSegSelectListener: function(seg) {
  3749. var _this = this;
  3750. var view = this.view;
  3751. var event = seg.event;
  3752. if (this.segDragListener) {
  3753. return this.segDragListener;
  3754. }
  3755. var dragListener = this.segDragListener = new DragListener({
  3756. dragStart: function(ev) {
  3757. if (dragListener.isTouch && !view.isEventSelected(event)) {
  3758. // if not previously selected, will fire after a delay. then, select the event
  3759. view.selectEvent(event);
  3760. }
  3761. },
  3762. interactionEnd: function(ev) {
  3763. _this.segDragListener = null;
  3764. }
  3765. });
  3766. return dragListener;
  3767. },
  3768. // Called before event segment dragging starts
  3769. segDragStart: function(seg, ev) {
  3770. this.isDraggingSeg = true;
  3771. this.view.publiclyTrigger('eventDragStart', seg.el[0], seg.event, ev, {}); // last argument is jqui dummy
  3772. },
  3773. // Called after event segment dragging stops
  3774. segDragStop: function(seg, ev) {
  3775. this.isDraggingSeg = false;
  3776. this.view.publiclyTrigger('eventDragStop', seg.el[0], seg.event, ev, {}); // last argument is jqui dummy
  3777. },
  3778. // Given the spans an event drag began, and the span event was dropped, calculates the new zoned start/end/allDay
  3779. // values for the event. Subclasses may override and set additional properties to be used by renderDrag.
  3780. // A falsy returned value indicates an invalid drop.
  3781. // DOES NOT consider overlap/constraint.
  3782. computeEventDrop: function(startSpan, endSpan, event) {
  3783. var calendar = this.view.calendar;
  3784. var dragStart = startSpan.start;
  3785. var dragEnd = endSpan.start;
  3786. var delta;
  3787. var dropLocation; // zoned event date properties
  3788. if (dragStart.hasTime() === dragEnd.hasTime()) {
  3789. delta = this.diffDates(dragEnd, dragStart);
  3790. // if an all-day event was in a timed area and it was dragged to a different time,
  3791. // guarantee an end and adjust start/end to have times
  3792. if (event.allDay && durationHasTime(delta)) {
  3793. dropLocation = {
  3794. start: event.start.clone(),
  3795. end: calendar.getEventEnd(event), // will be an ambig day
  3796. allDay: false // for normalizeEventTimes
  3797. };
  3798. calendar.normalizeEventTimes(dropLocation);
  3799. }
  3800. // othewise, work off existing values
  3801. else {
  3802. dropLocation = pluckEventDateProps(event);
  3803. }
  3804. dropLocation.start.add(delta);
  3805. if (dropLocation.end) {
  3806. dropLocation.end.add(delta);
  3807. }
  3808. }
  3809. else {
  3810. // if switching from day <-> timed, start should be reset to the dropped date, and the end cleared
  3811. dropLocation = {
  3812. start: dragEnd.clone(),
  3813. end: null, // end should be cleared
  3814. allDay: !dragEnd.hasTime()
  3815. };
  3816. }
  3817. return dropLocation;
  3818. },
  3819. // Utility for apply dragOpacity to a jQuery set
  3820. applyDragOpacity: function(els) {
  3821. var opacity = this.view.opt('dragOpacity');
  3822. if (opacity != null) {
  3823. els.css('opacity', opacity);
  3824. }
  3825. },
  3826. /* External Element Dragging
  3827. ------------------------------------------------------------------------------------------------------------------*/
  3828. // Called when a jQuery UI drag is initiated anywhere in the DOM
  3829. externalDragStart: function(ev, ui) {
  3830. var view = this.view;
  3831. var el;
  3832. var accept;
  3833. if (view.opt('droppable')) { // only listen if this setting is on
  3834. el = $((ui ? ui.item : null) || ev.target);
  3835. // Test that the dragged element passes the dropAccept selector or filter function.
  3836. // FYI, the default is "*" (matches all)
  3837. accept = view.opt('dropAccept');
  3838. if ($.isFunction(accept) ? accept.call(el[0], el) : el.is(accept)) {
  3839. if (!this.isDraggingExternal) { // prevent double-listening if fired twice
  3840. this.listenToExternalDrag(el, ev, ui);
  3841. }
  3842. }
  3843. }
  3844. },
  3845. // Called when a jQuery UI drag starts and it needs to be monitored for dropping
  3846. listenToExternalDrag: function(el, ev, ui) {
  3847. var _this = this;
  3848. var calendar = this.view.calendar;
  3849. var meta = getDraggedElMeta(el); // extra data about event drop, including possible event to create
  3850. var dropLocation; // a null value signals an unsuccessful drag
  3851. // listener that tracks mouse movement over date-associated pixel regions
  3852. var dragListener = _this.externalDragListener = new HitDragListener(this, {
  3853. interactionStart: function() {
  3854. _this.isDraggingExternal = true;
  3855. },
  3856. hitOver: function(hit) {
  3857. dropLocation = _this.computeExternalDrop(
  3858. hit.component.getHitSpan(hit), // since we are querying the parent view, might not belong to this grid
  3859. meta
  3860. );
  3861. if ( // invalid hit?
  3862. dropLocation &&
  3863. !calendar.isExternalSpanAllowed(_this.eventToSpan(dropLocation), dropLocation, meta.eventProps)
  3864. ) {
  3865. disableCursor();
  3866. dropLocation = null;
  3867. }
  3868. if (dropLocation) {
  3869. _this.renderDrag(dropLocation); // called without a seg parameter
  3870. }
  3871. },
  3872. hitOut: function() {
  3873. dropLocation = null; // signal unsuccessful
  3874. },
  3875. hitDone: function() { // Called after a hitOut OR before a dragEnd
  3876. enableCursor();
  3877. _this.unrenderDrag();
  3878. },
  3879. interactionEnd: function(ev) {
  3880. if (dropLocation) { // element was dropped on a valid hit
  3881. _this.view.reportExternalDrop(meta, dropLocation, el, ev, ui);
  3882. }
  3883. _this.isDraggingExternal = false;
  3884. _this.externalDragListener = null;
  3885. }
  3886. });
  3887. dragListener.startDrag(ev); // start listening immediately
  3888. },
  3889. // Given a hit to be dropped upon, and misc data associated with the jqui drag (guaranteed to be a plain object),
  3890. // returns the zoned start/end dates for the event that would result from the hypothetical drop. end might be null.
  3891. // Returning a null value signals an invalid drop hit.
  3892. // DOES NOT consider overlap/constraint.
  3893. computeExternalDrop: function(span, meta) {
  3894. var calendar = this.view.calendar;
  3895. var dropLocation = {
  3896. start: calendar.applyTimezone(span.start), // simulate a zoned event start date
  3897. end: null
  3898. };
  3899. // if dropped on an all-day span, and element's metadata specified a time, set it
  3900. if (meta.startTime && !dropLocation.start.hasTime()) {
  3901. dropLocation.start.time(meta.startTime);
  3902. }
  3903. if (meta.duration) {
  3904. dropLocation.end = dropLocation.start.clone().add(meta.duration);
  3905. }
  3906. return dropLocation;
  3907. },
  3908. /* Drag Rendering (for both events and an external elements)
  3909. ------------------------------------------------------------------------------------------------------------------*/
  3910. // Renders a visual indication of an event or external element being dragged.
  3911. // `dropLocation` contains hypothetical start/end/allDay values the event would have if dropped. end can be null.
  3912. // `seg` is the internal segment object that is being dragged. If dragging an external element, `seg` is null.
  3913. // A truthy returned value indicates this method has rendered a helper element.
  3914. // Must return elements used for any mock events.
  3915. renderDrag: function(dropLocation, seg) {
  3916. // subclasses must implement
  3917. },
  3918. // Unrenders a visual indication of an event or external element being dragged
  3919. unrenderDrag: function() {
  3920. // subclasses must implement
  3921. },
  3922. /* Resizing
  3923. ------------------------------------------------------------------------------------------------------------------*/
  3924. // Creates a listener that tracks the user as they resize an event segment.
  3925. // Generic enough to work with any type of Grid.
  3926. buildSegResizeListener: function(seg, isStart) {
  3927. var _this = this;
  3928. var view = this.view;
  3929. var calendar = view.calendar;
  3930. var el = seg.el;
  3931. var event = seg.event;
  3932. var eventEnd = calendar.getEventEnd(event);
  3933. var isDragging;
  3934. var resizeLocation; // zoned event date properties. falsy if invalid resize
  3935. // Tracks mouse movement over the *grid's* coordinate map
  3936. var dragListener = this.segResizeListener = new HitDragListener(this, {
  3937. scroll: view.opt('dragScroll'),
  3938. subjectEl: el,
  3939. interactionStart: function() {
  3940. isDragging = false;
  3941. },
  3942. dragStart: function(ev) {
  3943. isDragging = true;
  3944. _this.handleSegMouseout(seg, ev); // ensure a mouseout on the manipulated event has been reported
  3945. _this.segResizeStart(seg, ev);
  3946. },
  3947. hitOver: function(hit, isOrig, origHit) {
  3948. var origHitSpan = _this.getHitSpan(origHit);
  3949. var hitSpan = _this.getHitSpan(hit);
  3950. resizeLocation = isStart ?
  3951. _this.computeEventStartResize(origHitSpan, hitSpan, event) :
  3952. _this.computeEventEndResize(origHitSpan, hitSpan, event);
  3953. if (resizeLocation) {
  3954. if (!calendar.isEventSpanAllowed(_this.eventToSpan(resizeLocation), event)) {
  3955. disableCursor();
  3956. resizeLocation = null;
  3957. }
  3958. // no change? (FYI, event dates might have zones)
  3959. else if (
  3960. resizeLocation.start.isSame(event.start.clone().stripZone()) &&
  3961. resizeLocation.end.isSame(eventEnd.clone().stripZone())
  3962. ) {
  3963. resizeLocation = null;
  3964. }
  3965. }
  3966. if (resizeLocation) {
  3967. view.hideEvent(event);
  3968. _this.renderEventResize(resizeLocation, seg);
  3969. }
  3970. },
  3971. hitOut: function() { // called before mouse moves to a different hit OR moved out of all hits
  3972. resizeLocation = null;
  3973. view.showEvent(event); // for when out-of-bounds. show original
  3974. },
  3975. hitDone: function() { // resets the rendering to show the original event
  3976. _this.unrenderEventResize();
  3977. enableCursor();
  3978. },
  3979. interactionEnd: function(ev) {
  3980. if (isDragging) {
  3981. _this.segResizeStop(seg, ev);
  3982. }
  3983. if (resizeLocation) { // valid date to resize to?
  3984. // no need to re-show original, will rerender all anyways. esp important if eventRenderWait
  3985. view.reportSegResize(seg, resizeLocation, _this.largeUnit, el, ev);
  3986. }
  3987. else {
  3988. view.showEvent(event);
  3989. }
  3990. _this.segResizeListener = null;
  3991. }
  3992. });
  3993. return dragListener;
  3994. },
  3995. // Called before event segment resizing starts
  3996. segResizeStart: function(seg, ev) {
  3997. this.isResizingSeg = true;
  3998. this.view.publiclyTrigger('eventResizeStart', seg.el[0], seg.event, ev, {}); // last argument is jqui dummy
  3999. },
  4000. // Called after event segment resizing stops
  4001. segResizeStop: function(seg, ev) {
  4002. this.isResizingSeg = false;
  4003. this.view.publiclyTrigger('eventResizeStop', seg.el[0], seg.event, ev, {}); // last argument is jqui dummy
  4004. },
  4005. // Returns new date-information for an event segment being resized from its start
  4006. computeEventStartResize: function(startSpan, endSpan, event) {
  4007. return this.computeEventResize('start', startSpan, endSpan, event);
  4008. },
  4009. // Returns new date-information for an event segment being resized from its end
  4010. computeEventEndResize: function(startSpan, endSpan, event) {
  4011. return this.computeEventResize('end', startSpan, endSpan, event);
  4012. },
  4013. // Returns new zoned date information for an event segment being resized from its start OR end
  4014. // `type` is either 'start' or 'end'.
  4015. // DOES NOT consider overlap/constraint.
  4016. computeEventResize: function(type, startSpan, endSpan, event) {
  4017. var calendar = this.view.calendar;
  4018. var delta = this.diffDates(endSpan[type], startSpan[type]);
  4019. var resizeLocation; // zoned event date properties
  4020. var defaultDuration;
  4021. // build original values to work from, guaranteeing a start and end
  4022. resizeLocation = {
  4023. start: event.start.clone(),
  4024. end: calendar.getEventEnd(event),
  4025. allDay: event.allDay
  4026. };
  4027. // if an all-day event was in a timed area and was resized to a time, adjust start/end to have times
  4028. if (resizeLocation.allDay && durationHasTime(delta)) {
  4029. resizeLocation.allDay = false;
  4030. calendar.normalizeEventTimes(resizeLocation);
  4031. }
  4032. resizeLocation[type].add(delta); // apply delta to start or end
  4033. // if the event was compressed too small, find a new reasonable duration for it
  4034. if (!resizeLocation.start.isBefore(resizeLocation.end)) {
  4035. defaultDuration =
  4036. this.minResizeDuration || // TODO: hack
  4037. (event.allDay ?
  4038. calendar.defaultAllDayEventDuration :
  4039. calendar.defaultTimedEventDuration);
  4040. if (type == 'start') { // resizing the start?
  4041. resizeLocation.start = resizeLocation.end.clone().subtract(defaultDuration);
  4042. }
  4043. else { // resizing the end?
  4044. resizeLocation.end = resizeLocation.start.clone().add(defaultDuration);
  4045. }
  4046. }
  4047. return resizeLocation;
  4048. },
  4049. // Renders a visual indication of an event being resized.
  4050. // `range` has the updated dates of the event. `seg` is the original segment object involved in the drag.
  4051. // Must return elements used for any mock events.
  4052. renderEventResize: function(range, seg) {
  4053. // subclasses must implement
  4054. },
  4055. // Unrenders a visual indication of an event being resized.
  4056. unrenderEventResize: function() {
  4057. // subclasses must implement
  4058. },
  4059. /* Rendering Utils
  4060. ------------------------------------------------------------------------------------------------------------------*/
  4061. // Compute the text that should be displayed on an event's element.
  4062. // `range` can be the Event object itself, or something range-like, with at least a `start`.
  4063. // If event times are disabled, or the event has no time, will return a blank string.
  4064. // If not specified, formatStr will default to the eventTimeFormat setting,
  4065. // and displayEnd will default to the displayEventEnd setting.
  4066. getEventTimeText: function(range, formatStr, displayEnd) {
  4067. if (formatStr == null) {
  4068. formatStr = this.eventTimeFormat;
  4069. }
  4070. if (displayEnd == null) {
  4071. displayEnd = this.displayEventEnd;
  4072. }
  4073. if (this.displayEventTime && range.start.hasTime()) {
  4074. if (displayEnd && range.end) {
  4075. return this.view.formatRange(range, formatStr);
  4076. }
  4077. else {
  4078. return range.start.format(formatStr);
  4079. }
  4080. }
  4081. return '';
  4082. },
  4083. // Generic utility for generating the HTML classNames for an event segment's element
  4084. getSegClasses: function(seg, isDraggable, isResizable) {
  4085. var view = this.view;
  4086. var classes = [
  4087. 'fc-event',
  4088. seg.isStart ? 'fc-start' : 'fc-not-start',
  4089. seg.isEnd ? 'fc-end' : 'fc-not-end'
  4090. ].concat(this.getSegCustomClasses(seg));
  4091. if (isDraggable) {
  4092. classes.push('fc-draggable');
  4093. }
  4094. if (isResizable) {
  4095. classes.push('fc-resizable');
  4096. }
  4097. // event is currently selected? attach a className.
  4098. if (view.isEventSelected(seg.event)) {
  4099. classes.push('fc-selected');
  4100. }
  4101. return classes;
  4102. },
  4103. // List of classes that were defined by the caller of the API in some way
  4104. getSegCustomClasses: function(seg) {
  4105. var event = seg.event;
  4106. return [].concat(
  4107. event.className, // guaranteed to be an array
  4108. event.source ? event.source.className : []
  4109. );
  4110. },
  4111. // Utility for generating event skin-related CSS properties
  4112. getSegSkinCss: function(seg) {
  4113. return {
  4114. 'background-color': this.getSegBackgroundColor(seg),
  4115. 'border-color': this.getSegBorderColor(seg),
  4116. color: this.getSegTextColor(seg)
  4117. };
  4118. },
  4119. // Queries for caller-specified color, then falls back to default
  4120. getSegBackgroundColor: function(seg) {
  4121. return seg.event.backgroundColor ||
  4122. seg.event.color ||
  4123. this.getSegDefaultBackgroundColor(seg);
  4124. },
  4125. getSegDefaultBackgroundColor: function(seg) {
  4126. var source = seg.event.source || {};
  4127. return source.backgroundColor ||
  4128. source.color ||
  4129. this.view.opt('eventBackgroundColor') ||
  4130. this.view.opt('eventColor');
  4131. },
  4132. // Queries for caller-specified color, then falls back to default
  4133. getSegBorderColor: function(seg) {
  4134. return seg.event.borderColor ||
  4135. seg.event.color ||
  4136. this.getSegDefaultBorderColor(seg);
  4137. },
  4138. getSegDefaultBorderColor: function(seg) {
  4139. var source = seg.event.source || {};
  4140. return source.borderColor ||
  4141. source.color ||
  4142. this.view.opt('eventBorderColor') ||
  4143. this.view.opt('eventColor');
  4144. },
  4145. // Queries for caller-specified color, then falls back to default
  4146. getSegTextColor: function(seg) {
  4147. return seg.event.textColor ||
  4148. this.getSegDefaultTextColor(seg);
  4149. },
  4150. getSegDefaultTextColor: function(seg) {
  4151. var source = seg.event.source || {};
  4152. return source.textColor ||
  4153. this.view.opt('eventTextColor');
  4154. },
  4155. /* Converting events -> eventRange -> eventSpan -> eventSegs
  4156. ------------------------------------------------------------------------------------------------------------------*/
  4157. // Generates an array of segments for the given single event
  4158. // Can accept an event "location" as well (which only has start/end and no allDay)
  4159. eventToSegs: function(event) {
  4160. return this.eventsToSegs([ event ]);
  4161. },
  4162. eventToSpan: function(event) {
  4163. return this.eventToSpans(event)[0];
  4164. },
  4165. // Generates spans (always unzoned) for the given event.
  4166. // Does not do any inverting for inverse-background events.
  4167. // Can accept an event "location" as well (which only has start/end and no allDay)
  4168. eventToSpans: function(event) {
  4169. var range = this.eventToRange(event);
  4170. return this.eventRangeToSpans(range, event);
  4171. },
  4172. // Converts an array of event objects into an array of event segment objects.
  4173. // A custom `segSliceFunc` may be given for arbitrarily slicing up events.
  4174. // Doesn't guarantee an order for the resulting array.
  4175. eventsToSegs: function(allEvents, segSliceFunc) {
  4176. var _this = this;
  4177. var eventsById = groupEventsById(allEvents);
  4178. var segs = [];
  4179. $.each(eventsById, function(id, events) {
  4180. var ranges = [];
  4181. var i;
  4182. for (i = 0; i < events.length; i++) {
  4183. ranges.push(_this.eventToRange(events[i]));
  4184. }
  4185. // inverse-background events (utilize only the first event in calculations)
  4186. if (isInverseBgEvent(events[0])) {
  4187. ranges = _this.invertRanges(ranges);
  4188. for (i = 0; i < ranges.length; i++) {
  4189. segs.push.apply(segs, // append to
  4190. _this.eventRangeToSegs(ranges[i], events[0], segSliceFunc));
  4191. }
  4192. }
  4193. // normal event ranges
  4194. else {
  4195. for (i = 0; i < ranges.length; i++) {
  4196. segs.push.apply(segs, // append to
  4197. _this.eventRangeToSegs(ranges[i], events[i], segSliceFunc));
  4198. }
  4199. }
  4200. });
  4201. return segs;
  4202. },
  4203. // Generates the unzoned start/end dates an event appears to occupy
  4204. // Can accept an event "location" as well (which only has start/end and no allDay)
  4205. eventToRange: function(event) {
  4206. var calendar = this.view.calendar;
  4207. var start = event.start.clone().stripZone();
  4208. var end = (
  4209. event.end ?
  4210. event.end.clone() :
  4211. // derive the end from the start and allDay. compute allDay if necessary
  4212. calendar.getDefaultEventEnd(
  4213. event.allDay != null ?
  4214. event.allDay :
  4215. !event.start.hasTime(),
  4216. event.start
  4217. )
  4218. ).stripZone();
  4219. // hack: dynamic locale change forgets to upate stored event localed
  4220. calendar.localizeMoment(start);
  4221. calendar.localizeMoment(end);
  4222. return { start: start, end: end };
  4223. },
  4224. // Given an event's range (unzoned start/end), and the event itself,
  4225. // slice into segments (using the segSliceFunc function if specified)
  4226. eventRangeToSegs: function(range, event, segSliceFunc) {
  4227. var spans = this.eventRangeToSpans(range, event);
  4228. var segs = [];
  4229. var i;
  4230. for (i = 0; i < spans.length; i++) {
  4231. segs.push.apply(segs, // append to
  4232. this.eventSpanToSegs(spans[i], event, segSliceFunc));
  4233. }
  4234. return segs;
  4235. },
  4236. // Given an event's unzoned date range, return an array of "span" objects.
  4237. // Subclasses can override.
  4238. eventRangeToSpans: function(range, event) {
  4239. return [ $.extend({}, range) ]; // copy into a single-item array
  4240. },
  4241. // Given an event's span (unzoned start/end and other misc data), and the event itself,
  4242. // slices into segments and attaches event-derived properties to them.
  4243. eventSpanToSegs: function(span, event, segSliceFunc) {
  4244. var segs = segSliceFunc ? segSliceFunc(span) : this.spanToSegs(span);
  4245. var i, seg;
  4246. for (i = 0; i < segs.length; i++) {
  4247. seg = segs[i];
  4248. seg.event = event;
  4249. seg.eventStartMS = +span.start; // TODO: not the best name after making spans unzoned
  4250. seg.eventDurationMS = span.end - span.start;
  4251. }
  4252. return segs;
  4253. },
  4254. // Produces a new array of range objects that will cover all the time NOT covered by the given ranges.
  4255. // SIDE EFFECT: will mutate the given array and will use its date references.
  4256. invertRanges: function(ranges) {
  4257. var view = this.view;
  4258. var viewStart = view.start.clone(); // need a copy
  4259. var viewEnd = view.end.clone(); // need a copy
  4260. var inverseRanges = [];
  4261. var start = viewStart; // the end of the previous range. the start of the new range
  4262. var i, range;
  4263. // ranges need to be in order. required for our date-walking algorithm
  4264. ranges.sort(compareRanges);
  4265. for (i = 0; i < ranges.length; i++) {
  4266. range = ranges[i];
  4267. // add the span of time before the event (if there is any)
  4268. if (range.start > start) { // compare millisecond time (skip any ambig logic)
  4269. inverseRanges.push({
  4270. start: start,
  4271. end: range.start
  4272. });
  4273. }
  4274. start = range.end;
  4275. }
  4276. // add the span of time after the last event (if there is any)
  4277. if (start < viewEnd) { // compare millisecond time (skip any ambig logic)
  4278. inverseRanges.push({
  4279. start: start,
  4280. end: viewEnd
  4281. });
  4282. }
  4283. return inverseRanges;
  4284. },
  4285. sortEventSegs: function(segs) {
  4286. segs.sort(proxy(this, 'compareEventSegs'));
  4287. },
  4288. // A cmp function for determining which segments should take visual priority
  4289. compareEventSegs: function(seg1, seg2) {
  4290. return seg1.eventStartMS - seg2.eventStartMS || // earlier events go first
  4291. seg2.eventDurationMS - seg1.eventDurationMS || // tie? longer events go first
  4292. seg2.event.allDay - seg1.event.allDay || // tie? put all-day events first (booleans cast to 0/1)
  4293. compareByFieldSpecs(seg1.event, seg2.event, this.view.eventOrderSpecs);
  4294. }
  4295. });
  4296. /* Utilities
  4297. ----------------------------------------------------------------------------------------------------------------------*/
  4298. function pluckEventDateProps(event) {
  4299. return {
  4300. start: event.start.clone(),
  4301. end: event.end ? event.end.clone() : null,
  4302. allDay: event.allDay // keep it the same
  4303. };
  4304. }
  4305. FC.pluckEventDateProps = pluckEventDateProps;
  4306. function isBgEvent(event) { // returns true if background OR inverse-background
  4307. var rendering = getEventRendering(event);
  4308. return rendering === 'background' || rendering === 'inverse-background';
  4309. }
  4310. FC.isBgEvent = isBgEvent; // export
  4311. function isInverseBgEvent(event) {
  4312. return getEventRendering(event) === 'inverse-background';
  4313. }
  4314. function getEventRendering(event) {
  4315. return firstDefined((event.source || {}).rendering, event.rendering);
  4316. }
  4317. function groupEventsById(events) {
  4318. var eventsById = {};
  4319. var i, event;
  4320. for (i = 0; i < events.length; i++) {
  4321. event = events[i];
  4322. (eventsById[event._id] || (eventsById[event._id] = [])).push(event);
  4323. }
  4324. return eventsById;
  4325. }
  4326. // A cmp function for determining which non-inverted "ranges" (see above) happen earlier
  4327. function compareRanges(range1, range2) {
  4328. return range1.start - range2.start; // earlier ranges go first
  4329. }
  4330. /* External-Dragging-Element Data
  4331. ----------------------------------------------------------------------------------------------------------------------*/
  4332. // Require all HTML5 data-* attributes used by FullCalendar to have this prefix.
  4333. // A value of '' will query attributes like data-event. A value of 'fc' will query attributes like data-fc-event.
  4334. FC.dataAttrPrefix = '';
  4335. // Given a jQuery element that might represent a dragged FullCalendar event, returns an intermediate data structure
  4336. // to be used for Event Object creation.
  4337. // A defined `.eventProps`, even when empty, indicates that an event should be created.
  4338. function getDraggedElMeta(el) {
  4339. var prefix = FC.dataAttrPrefix;
  4340. var eventProps; // properties for creating the event, not related to date/time
  4341. var startTime; // a Duration
  4342. var duration;
  4343. var stick;
  4344. if (prefix) { prefix += '-'; }
  4345. eventProps = el.data(prefix + 'event') || null;
  4346. if (eventProps) {
  4347. if (typeof eventProps === 'object') {
  4348. eventProps = $.extend({}, eventProps); // make a copy
  4349. }
  4350. else { // something like 1 or true. still signal event creation
  4351. eventProps = {};
  4352. }
  4353. // pluck special-cased date/time properties
  4354. startTime = eventProps.start;
  4355. if (startTime == null) { startTime = eventProps.time; } // accept 'time' as well
  4356. duration = eventProps.duration;
  4357. stick = eventProps.stick;
  4358. delete eventProps.start;
  4359. delete eventProps.time;
  4360. delete eventProps.duration;
  4361. delete eventProps.stick;
  4362. }
  4363. // fallback to standalone attribute values for each of the date/time properties
  4364. if (startTime == null) { startTime = el.data(prefix + 'start'); }
  4365. if (startTime == null) { startTime = el.data(prefix + 'time'); } // accept 'time' as well
  4366. if (duration == null) { duration = el.data(prefix + 'duration'); }
  4367. if (stick == null) { stick = el.data(prefix + 'stick'); }
  4368. // massage into correct data types
  4369. startTime = startTime != null ? moment.duration(startTime) : null;
  4370. duration = duration != null ? moment.duration(duration) : null;
  4371. stick = Boolean(stick);
  4372. return { eventProps: eventProps, startTime: startTime, duration: duration, stick: stick };
  4373. }
  4374. ;;
  4375. /*
  4376. A set of rendering and date-related methods for a visual component comprised of one or more rows of day columns.
  4377. Prerequisite: the object being mixed into needs to be a *Grid*
  4378. */
  4379. var DayTableMixin = FC.DayTableMixin = {
  4380. breakOnWeeks: false, // should create a new row for each week?
  4381. dayDates: null, // whole-day dates for each column. left to right
  4382. dayIndices: null, // for each day from start, the offset
  4383. daysPerRow: null,
  4384. rowCnt: null,
  4385. colCnt: null,
  4386. colHeadFormat: null,
  4387. // Populates internal variables used for date calculation and rendering
  4388. updateDayTable: function() {
  4389. var view = this.view;
  4390. var date = this.start.clone();
  4391. var dayIndex = -1;
  4392. var dayIndices = [];
  4393. var dayDates = [];
  4394. var daysPerRow;
  4395. var firstDay;
  4396. var rowCnt;
  4397. while (date.isBefore(this.end)) { // loop each day from start to end
  4398. if (view.isHiddenDay(date)) {
  4399. dayIndices.push(dayIndex + 0.5); // mark that it's between indices
  4400. }
  4401. else {
  4402. dayIndex++;
  4403. dayIndices.push(dayIndex);
  4404. dayDates.push(date.clone());
  4405. }
  4406. date.add(1, 'days');
  4407. }
  4408. if (this.breakOnWeeks) {
  4409. // count columns until the day-of-week repeats
  4410. firstDay = dayDates[0].day();
  4411. for (daysPerRow = 1; daysPerRow < dayDates.length; daysPerRow++) {
  4412. if (dayDates[daysPerRow].day() == firstDay) {
  4413. break;
  4414. }
  4415. }
  4416. rowCnt = Math.ceil(dayDates.length / daysPerRow);
  4417. }
  4418. else {
  4419. rowCnt = 1;
  4420. daysPerRow = dayDates.length;
  4421. }
  4422. this.dayDates = dayDates;
  4423. this.dayIndices = dayIndices;
  4424. this.daysPerRow = daysPerRow;
  4425. this.rowCnt = rowCnt;
  4426. this.updateDayTableCols();
  4427. },
  4428. // Computes and assigned the colCnt property and updates any options that may be computed from it
  4429. updateDayTableCols: function() {
  4430. this.colCnt = this.computeColCnt();
  4431. this.colHeadFormat = this.view.opt('columnFormat') || this.computeColHeadFormat();
  4432. },
  4433. // Determines how many columns there should be in the table
  4434. computeColCnt: function() {
  4435. return this.daysPerRow;
  4436. },
  4437. // Computes the ambiguously-timed moment for the given cell
  4438. getCellDate: function(row, col) {
  4439. return this.dayDates[
  4440. this.getCellDayIndex(row, col)
  4441. ].clone();
  4442. },
  4443. // Computes the ambiguously-timed date range for the given cell
  4444. getCellRange: function(row, col) {
  4445. var start = this.getCellDate(row, col);
  4446. var end = start.clone().add(1, 'days');
  4447. return { start: start, end: end };
  4448. },
  4449. // Returns the number of day cells, chronologically, from the first of the grid (0-based)
  4450. getCellDayIndex: function(row, col) {
  4451. return row * this.daysPerRow + this.getColDayIndex(col);
  4452. },
  4453. // Returns the numner of day cells, chronologically, from the first cell in *any given row*
  4454. getColDayIndex: function(col) {
  4455. if (this.isRTL) {
  4456. return this.colCnt - 1 - col;
  4457. }
  4458. else {
  4459. return col;
  4460. }
  4461. },
  4462. // Given a date, returns its chronolocial cell-index from the first cell of the grid.
  4463. // If the date lies between cells (because of hiddenDays), returns a floating-point value between offsets.
  4464. // If before the first offset, returns a negative number.
  4465. // If after the last offset, returns an offset past the last cell offset.
  4466. // Only works for *start* dates of cells. Will not work for exclusive end dates for cells.
  4467. getDateDayIndex: function(date) {
  4468. var dayIndices = this.dayIndices;
  4469. var dayOffset = date.diff(this.start, 'days');
  4470. if (dayOffset < 0) {
  4471. return dayIndices[0] - 1;
  4472. }
  4473. else if (dayOffset >= dayIndices.length) {
  4474. return dayIndices[dayIndices.length - 1] + 1;
  4475. }
  4476. else {
  4477. return dayIndices[dayOffset];
  4478. }
  4479. },
  4480. /* Options
  4481. ------------------------------------------------------------------------------------------------------------------*/
  4482. // Computes a default column header formatting string if `colFormat` is not explicitly defined
  4483. computeColHeadFormat: function() {
  4484. // if more than one week row, or if there are a lot of columns with not much space,
  4485. // put just the day numbers will be in each cell
  4486. if (this.rowCnt > 1 || this.colCnt > 10) {
  4487. return 'ddd'; // "Sat"
  4488. }
  4489. // multiple days, so full single date string WON'T be in title text
  4490. else if (this.colCnt > 1) {
  4491. return this.view.opt('dayOfMonthFormat'); // "Sat 12/10"
  4492. }
  4493. // single day, so full single date string will probably be in title text
  4494. else {
  4495. return 'dddd'; // "Saturday"
  4496. }
  4497. },
  4498. /* Slicing
  4499. ------------------------------------------------------------------------------------------------------------------*/
  4500. // Slices up a date range into a segment for every week-row it intersects with
  4501. sliceRangeByRow: function(range) {
  4502. var daysPerRow = this.daysPerRow;
  4503. var normalRange = this.view.computeDayRange(range); // make whole-day range, considering nextDayThreshold
  4504. var rangeFirst = this.getDateDayIndex(normalRange.start); // inclusive first index
  4505. var rangeLast = this.getDateDayIndex(normalRange.end.clone().subtract(1, 'days')); // inclusive last index
  4506. var segs = [];
  4507. var row;
  4508. var rowFirst, rowLast; // inclusive day-index range for current row
  4509. var segFirst, segLast; // inclusive day-index range for segment
  4510. for (row = 0; row < this.rowCnt; row++) {
  4511. rowFirst = row * daysPerRow;
  4512. rowLast = rowFirst + daysPerRow - 1;
  4513. // intersect segment's offset range with the row's
  4514. segFirst = Math.max(rangeFirst, rowFirst);
  4515. segLast = Math.min(rangeLast, rowLast);
  4516. // deal with in-between indices
  4517. segFirst = Math.ceil(segFirst); // in-between starts round to next cell
  4518. segLast = Math.floor(segLast); // in-between ends round to prev cell
  4519. if (segFirst <= segLast) { // was there any intersection with the current row?
  4520. segs.push({
  4521. row: row,
  4522. // normalize to start of row
  4523. firstRowDayIndex: segFirst - rowFirst,
  4524. lastRowDayIndex: segLast - rowFirst,
  4525. // must be matching integers to be the segment's start/end
  4526. isStart: segFirst === rangeFirst,
  4527. isEnd: segLast === rangeLast
  4528. });
  4529. }
  4530. }
  4531. return segs;
  4532. },
  4533. // Slices up a date range into a segment for every day-cell it intersects with.
  4534. // TODO: make more DRY with sliceRangeByRow somehow.
  4535. sliceRangeByDay: function(range) {
  4536. var daysPerRow = this.daysPerRow;
  4537. var normalRange = this.view.computeDayRange(range); // make whole-day range, considering nextDayThreshold
  4538. var rangeFirst = this.getDateDayIndex(normalRange.start); // inclusive first index
  4539. var rangeLast = this.getDateDayIndex(normalRange.end.clone().subtract(1, 'days')); // inclusive last index
  4540. var segs = [];
  4541. var row;
  4542. var rowFirst, rowLast; // inclusive day-index range for current row
  4543. var i;
  4544. var segFirst, segLast; // inclusive day-index range for segment
  4545. for (row = 0; row < this.rowCnt; row++) {
  4546. rowFirst = row * daysPerRow;
  4547. rowLast = rowFirst + daysPerRow - 1;
  4548. for (i = rowFirst; i <= rowLast; i++) {
  4549. // intersect segment's offset range with the row's
  4550. segFirst = Math.max(rangeFirst, i);
  4551. segLast = Math.min(rangeLast, i);
  4552. // deal with in-between indices
  4553. segFirst = Math.ceil(segFirst); // in-between starts round to next cell
  4554. segLast = Math.floor(segLast); // in-between ends round to prev cell
  4555. if (segFirst <= segLast) { // was there any intersection with the current row?
  4556. segs.push({
  4557. row: row,
  4558. // normalize to start of row
  4559. firstRowDayIndex: segFirst - rowFirst,
  4560. lastRowDayIndex: segLast - rowFirst,
  4561. // must be matching integers to be the segment's start/end
  4562. isStart: segFirst === rangeFirst,
  4563. isEnd: segLast === rangeLast
  4564. });
  4565. }
  4566. }
  4567. }
  4568. return segs;
  4569. },
  4570. /* Header Rendering
  4571. ------------------------------------------------------------------------------------------------------------------*/
  4572. renderHeadHtml: function() {
  4573. var view = this.view;
  4574. return '' +
  4575. '<div class="fc-row ' + view.widgetHeaderClass + '">' +
  4576. '<table>' +
  4577. '<thead>' +
  4578. this.renderHeadTrHtml() +
  4579. '</thead>' +
  4580. '</table>' +
  4581. '</div>';
  4582. },
  4583. renderHeadIntroHtml: function() {
  4584. return this.renderIntroHtml(); // fall back to generic
  4585. },
  4586. renderHeadTrHtml: function() {
  4587. return '' +
  4588. '<tr>' +
  4589. (this.isRTL ? '' : this.renderHeadIntroHtml()) +
  4590. this.renderHeadDateCellsHtml() +
  4591. (this.isRTL ? this.renderHeadIntroHtml() : '') +
  4592. '</tr>';
  4593. },
  4594. renderHeadDateCellsHtml: function() {
  4595. var htmls = [];
  4596. var col, date;
  4597. for (col = 0; col < this.colCnt; col++) {
  4598. date = this.getCellDate(0, col);
  4599. htmls.push(this.renderHeadDateCellHtml(date));
  4600. }
  4601. return htmls.join('');
  4602. },
  4603. // TODO: when internalApiVersion, accept an object for HTML attributes
  4604. // (colspan should be no different)
  4605. renderHeadDateCellHtml: function(date, colspan, otherAttrs) {
  4606. var view = this.view;
  4607. var classNames = [
  4608. 'fc-day-header',
  4609. view.widgetHeaderClass
  4610. ];
  4611. // if only one row of days, the classNames on the header can represent the specific days beneath
  4612. if (this.rowCnt === 1) {
  4613. classNames = classNames.concat(
  4614. // includes the day-of-week class
  4615. // noThemeHighlight=true (don't highlight the header)
  4616. this.getDayClasses(date, true)
  4617. );
  4618. }
  4619. else {
  4620. classNames.push('fc-' + dayIDs[date.day()]); // only add the day-of-week class
  4621. }
  4622. return '' +
  4623. '<th class="' + classNames.join(' ') + '"' +
  4624. (this.rowCnt === 1 ?
  4625. ' data-date="' + date.format('YYYY-MM-DD') + '"' :
  4626. '') +
  4627. (colspan > 1 ?
  4628. ' colspan="' + colspan + '"' :
  4629. '') +
  4630. (otherAttrs ?
  4631. ' ' + otherAttrs :
  4632. '') +
  4633. '>' +
  4634. // don't make a link if the heading could represent multiple days, or if there's only one day (forceOff)
  4635. view.buildGotoAnchorHtml(
  4636. { date: date, forceOff: this.rowCnt > 1 || this.colCnt === 1 },
  4637. htmlEscape(date.format(this.colHeadFormat)) // inner HTML
  4638. ) +
  4639. '</th>';
  4640. },
  4641. /* Background Rendering
  4642. ------------------------------------------------------------------------------------------------------------------*/
  4643. renderBgTrHtml: function(row) {
  4644. return '' +
  4645. '<tr>' +
  4646. (this.isRTL ? '' : this.renderBgIntroHtml(row)) +
  4647. this.renderBgCellsHtml(row) +
  4648. (this.isRTL ? this.renderBgIntroHtml(row) : '') +
  4649. '</tr>';
  4650. },
  4651. renderBgIntroHtml: function(row) {
  4652. return this.renderIntroHtml(); // fall back to generic
  4653. },
  4654. renderBgCellsHtml: function(row) {
  4655. var htmls = [];
  4656. var col, date;
  4657. for (col = 0; col < this.colCnt; col++) {
  4658. date = this.getCellDate(row, col);
  4659. htmls.push(this.renderBgCellHtml(date));
  4660. }
  4661. return htmls.join('');
  4662. },
  4663. renderBgCellHtml: function(date, otherAttrs) {
  4664. var view = this.view;
  4665. var classes = this.getDayClasses(date);
  4666. classes.unshift('fc-day', view.widgetContentClass);
  4667. return '<td class="' + classes.join(' ') + '"' +
  4668. ' data-date="' + date.format('YYYY-MM-DD') + '"' + // if date has a time, won't format it
  4669. (otherAttrs ?
  4670. ' ' + otherAttrs :
  4671. '') +
  4672. '></td>';
  4673. },
  4674. /* Generic
  4675. ------------------------------------------------------------------------------------------------------------------*/
  4676. // Generates the default HTML intro for any row. User classes should override
  4677. renderIntroHtml: function() {
  4678. },
  4679. // TODO: a generic method for dealing with <tr>, RTL, intro
  4680. // when increment internalApiVersion
  4681. // wrapTr (scheduler)
  4682. /* Utils
  4683. ------------------------------------------------------------------------------------------------------------------*/
  4684. // Applies the generic "intro" and "outro" HTML to the given cells.
  4685. // Intro means the leftmost cell when the calendar is LTR and the rightmost cell when RTL. Vice-versa for outro.
  4686. bookendCells: function(trEl) {
  4687. var introHtml = this.renderIntroHtml();
  4688. if (introHtml) {
  4689. if (this.isRTL) {
  4690. trEl.append(introHtml);
  4691. }
  4692. else {
  4693. trEl.prepend(introHtml);
  4694. }
  4695. }
  4696. }
  4697. };
  4698. ;;
  4699. /* A component that renders a grid of whole-days that runs horizontally. There can be multiple rows, one per week.
  4700. ----------------------------------------------------------------------------------------------------------------------*/
  4701. var DayGrid = FC.DayGrid = Grid.extend(DayTableMixin, {
  4702. numbersVisible: false, // should render a row for day/week numbers? set by outside view. TODO: make internal
  4703. bottomCoordPadding: 0, // hack for extending the hit area for the last row of the coordinate grid
  4704. rowEls: null, // set of fake row elements
  4705. cellEls: null, // set of whole-day elements comprising the row's background
  4706. helperEls: null, // set of cell skeleton elements for rendering the mock event "helper"
  4707. rowCoordCache: null,
  4708. colCoordCache: null,
  4709. // Renders the rows and columns into the component's `this.el`, which should already be assigned.
  4710. // isRigid determins whether the individual rows should ignore the contents and be a constant height.
  4711. // Relies on the view's colCnt and rowCnt. In the future, this component should probably be self-sufficient.
  4712. renderDates: function(isRigid) {
  4713. var view = this.view;
  4714. var rowCnt = this.rowCnt;
  4715. var colCnt = this.colCnt;
  4716. var html = '';
  4717. var row;
  4718. var col;
  4719. for (row = 0; row < rowCnt; row++) {
  4720. html += this.renderDayRowHtml(row, isRigid);
  4721. }
  4722. this.el.html(html);
  4723. this.rowEls = this.el.find('.fc-row');
  4724. this.cellEls = this.el.find('.fc-day');
  4725. this.rowCoordCache = new CoordCache({
  4726. els: this.rowEls,
  4727. isVertical: true
  4728. });
  4729. this.colCoordCache = new CoordCache({
  4730. els: this.cellEls.slice(0, this.colCnt), // only the first row
  4731. isHorizontal: true
  4732. });
  4733. // trigger dayRender with each cell's element
  4734. for (row = 0; row < rowCnt; row++) {
  4735. for (col = 0; col < colCnt; col++) {
  4736. view.publiclyTrigger(
  4737. 'dayRender',
  4738. null,
  4739. this.getCellDate(row, col),
  4740. this.getCellEl(row, col)
  4741. );
  4742. }
  4743. }
  4744. },
  4745. unrenderDates: function() {
  4746. this.removeSegPopover();
  4747. },
  4748. renderBusinessHours: function() {
  4749. var segs = this.buildBusinessHourSegs(true); // wholeDay=true
  4750. this.renderFill('businessHours', segs, 'bgevent');
  4751. },
  4752. unrenderBusinessHours: function() {
  4753. this.unrenderFill('businessHours');
  4754. },
  4755. // Generates the HTML for a single row, which is a div that wraps a table.
  4756. // `row` is the row number.
  4757. renderDayRowHtml: function(row, isRigid) {
  4758. var view = this.view;
  4759. var classes = [ 'fc-row', 'fc-week', view.widgetContentClass ];
  4760. if (isRigid) {
  4761. classes.push('fc-rigid');
  4762. }
  4763. return '' +
  4764. '<div class="' + classes.join(' ') + '">' +
  4765. '<div class="fc-bg">' +
  4766. '<table>' +
  4767. this.renderBgTrHtml(row) +
  4768. '</table>' +
  4769. '</div>' +
  4770. '<div class="fc-content-skeleton">' +
  4771. '<table>' +
  4772. (this.numbersVisible ?
  4773. '<thead>' +
  4774. this.renderNumberTrHtml(row) +
  4775. '</thead>' :
  4776. ''
  4777. ) +
  4778. '</table>' +
  4779. '</div>' +
  4780. '</div>';
  4781. },
  4782. /* Grid Number Rendering
  4783. ------------------------------------------------------------------------------------------------------------------*/
  4784. renderNumberTrHtml: function(row) {
  4785. return '' +
  4786. '<tr>' +
  4787. (this.isRTL ? '' : this.renderNumberIntroHtml(row)) +
  4788. this.renderNumberCellsHtml(row) +
  4789. (this.isRTL ? this.renderNumberIntroHtml(row) : '') +
  4790. '</tr>';
  4791. },
  4792. renderNumberIntroHtml: function(row) {
  4793. return this.renderIntroHtml();
  4794. },
  4795. renderNumberCellsHtml: function(row) {
  4796. var htmls = [];
  4797. var col, date;
  4798. for (col = 0; col < this.colCnt; col++) {
  4799. date = this.getCellDate(row, col);
  4800. htmls.push(this.renderNumberCellHtml(date));
  4801. }
  4802. return htmls.join('');
  4803. },
  4804. // Generates the HTML for the <td>s of the "number" row in the DayGrid's content skeleton.
  4805. // The number row will only exist if either day numbers or week numbers are turned on.
  4806. renderNumberCellHtml: function(date) {
  4807. var html = '';
  4808. var classes;
  4809. var weekCalcFirstDoW;
  4810. if (!this.view.dayNumbersVisible && !this.view.cellWeekNumbersVisible) {
  4811. // no numbers in day cell (week number must be along the side)
  4812. return '<td/>'; // will create an empty space above events :(
  4813. }
  4814. classes = this.getDayClasses(date);
  4815. classes.unshift('fc-day-top');
  4816. if (this.view.cellWeekNumbersVisible) {
  4817. // To determine the day of week number change under ISO, we cannot
  4818. // rely on moment.js methods such as firstDayOfWeek() or weekday(),
  4819. // because they rely on the locale's dow (possibly overridden by
  4820. // our firstDay option), which may not be Monday. We cannot change
  4821. // dow, because that would affect the calendar start day as well.
  4822. if (date._locale._fullCalendar_weekCalc === 'ISO') {
  4823. weekCalcFirstDoW = 1; // Monday by ISO 8601 definition
  4824. }
  4825. else {
  4826. weekCalcFirstDoW = date._locale.firstDayOfWeek();
  4827. }
  4828. }
  4829. html += '<td class="' + classes.join(' ') + '" data-date="' + date.format() + '">';
  4830. if (this.view.cellWeekNumbersVisible && (date.day() == weekCalcFirstDoW)) {
  4831. html += this.view.buildGotoAnchorHtml(
  4832. { date: date, type: 'week' },
  4833. { 'class': 'fc-week-number' },
  4834. date.format('w') // inner HTML
  4835. );
  4836. }
  4837. if (this.view.dayNumbersVisible) {
  4838. html += this.view.buildGotoAnchorHtml(
  4839. date,
  4840. { 'class': 'fc-day-number' },
  4841. date.date() // inner HTML
  4842. );
  4843. }
  4844. html += '</td>';
  4845. return html;
  4846. },
  4847. /* Options
  4848. ------------------------------------------------------------------------------------------------------------------*/
  4849. // Computes a default event time formatting string if `timeFormat` is not explicitly defined
  4850. computeEventTimeFormat: function() {
  4851. return this.view.opt('extraSmallTimeFormat'); // like "6p" or "6:30p"
  4852. },
  4853. // Computes a default `displayEventEnd` value if one is not expliclty defined
  4854. computeDisplayEventEnd: function() {
  4855. return this.colCnt == 1; // we'll likely have space if there's only one day
  4856. },
  4857. /* Dates
  4858. ------------------------------------------------------------------------------------------------------------------*/
  4859. rangeUpdated: function() {
  4860. this.updateDayTable();
  4861. },
  4862. // Slices up the given span (unzoned start/end with other misc data) into an array of segments
  4863. spanToSegs: function(span) {
  4864. var segs = this.sliceRangeByRow(span);
  4865. var i, seg;
  4866. for (i = 0; i < segs.length; i++) {
  4867. seg = segs[i];
  4868. if (this.isRTL) {
  4869. seg.leftCol = this.daysPerRow - 1 - seg.lastRowDayIndex;
  4870. seg.rightCol = this.daysPerRow - 1 - seg.firstRowDayIndex;
  4871. }
  4872. else {
  4873. seg.leftCol = seg.firstRowDayIndex;
  4874. seg.rightCol = seg.lastRowDayIndex;
  4875. }
  4876. }
  4877. return segs;
  4878. },
  4879. /* Hit System
  4880. ------------------------------------------------------------------------------------------------------------------*/
  4881. prepareHits: function() {
  4882. this.colCoordCache.build();
  4883. this.rowCoordCache.build();
  4884. this.rowCoordCache.bottoms[this.rowCnt - 1] += this.bottomCoordPadding; // hack
  4885. },
  4886. releaseHits: function() {
  4887. this.colCoordCache.clear();
  4888. this.rowCoordCache.clear();
  4889. },
  4890. queryHit: function(leftOffset, topOffset) {
  4891. if (this.colCoordCache.isLeftInBounds(leftOffset) && this.rowCoordCache.isTopInBounds(topOffset)) {
  4892. var col = this.colCoordCache.getHorizontalIndex(leftOffset);
  4893. var row = this.rowCoordCache.getVerticalIndex(topOffset);
  4894. if (row != null && col != null) {
  4895. return this.getCellHit(row, col);
  4896. }
  4897. }
  4898. },
  4899. getHitSpan: function(hit) {
  4900. return this.getCellRange(hit.row, hit.col);
  4901. },
  4902. getHitEl: function(hit) {
  4903. return this.getCellEl(hit.row, hit.col);
  4904. },
  4905. /* Cell System
  4906. ------------------------------------------------------------------------------------------------------------------*/
  4907. // FYI: the first column is the leftmost column, regardless of date
  4908. getCellHit: function(row, col) {
  4909. return {
  4910. row: row,
  4911. col: col,
  4912. component: this, // needed unfortunately :(
  4913. left: this.colCoordCache.getLeftOffset(col),
  4914. right: this.colCoordCache.getRightOffset(col),
  4915. top: this.rowCoordCache.getTopOffset(row),
  4916. bottom: this.rowCoordCache.getBottomOffset(row)
  4917. };
  4918. },
  4919. getCellEl: function(row, col) {
  4920. return this.cellEls.eq(row * this.colCnt + col);
  4921. },
  4922. /* Event Drag Visualization
  4923. ------------------------------------------------------------------------------------------------------------------*/
  4924. // TODO: move to DayGrid.event, similar to what we did with Grid's drag methods
  4925. // Renders a visual indication of an event or external element being dragged.
  4926. // `eventLocation` has zoned start and end (optional)
  4927. renderDrag: function(eventLocation, seg) {
  4928. // always render a highlight underneath
  4929. this.renderHighlight(this.eventToSpan(eventLocation));
  4930. // if a segment from the same calendar but another component is being dragged, render a helper event
  4931. if (seg && seg.component !== this) {
  4932. return this.renderEventLocationHelper(eventLocation, seg); // returns mock event elements
  4933. }
  4934. },
  4935. // Unrenders any visual indication of a hovering event
  4936. unrenderDrag: function() {
  4937. this.unrenderHighlight();
  4938. this.unrenderHelper();
  4939. },
  4940. /* Event Resize Visualization
  4941. ------------------------------------------------------------------------------------------------------------------*/
  4942. // Renders a visual indication of an event being resized
  4943. renderEventResize: function(eventLocation, seg) {
  4944. this.renderHighlight(this.eventToSpan(eventLocation));
  4945. return this.renderEventLocationHelper(eventLocation, seg); // returns mock event elements
  4946. },
  4947. // Unrenders a visual indication of an event being resized
  4948. unrenderEventResize: function() {
  4949. this.unrenderHighlight();
  4950. this.unrenderHelper();
  4951. },
  4952. /* Event Helper
  4953. ------------------------------------------------------------------------------------------------------------------*/
  4954. // Renders a mock "helper" event. `sourceSeg` is the associated internal segment object. It can be null.
  4955. renderHelper: function(event, sourceSeg) {
  4956. var helperNodes = [];
  4957. var segs = this.eventToSegs(event);
  4958. var rowStructs;
  4959. segs = this.renderFgSegEls(segs); // assigns each seg's el and returns a subset of segs that were rendered
  4960. rowStructs = this.renderSegRows(segs);
  4961. // inject each new event skeleton into each associated row
  4962. this.rowEls.each(function(row, rowNode) {
  4963. var rowEl = $(rowNode); // the .fc-row
  4964. var skeletonEl = $('<div class="fc-helper-skeleton"><table/></div>'); // will be absolutely positioned
  4965. var skeletonTop;
  4966. // If there is an original segment, match the top position. Otherwise, put it at the row's top level
  4967. if (sourceSeg && sourceSeg.row === row) {
  4968. skeletonTop = sourceSeg.el.position().top;
  4969. }
  4970. else {
  4971. skeletonTop = rowEl.find('.fc-content-skeleton tbody').position().top;
  4972. }
  4973. skeletonEl.css('top', skeletonTop)
  4974. .find('table')
  4975. .append(rowStructs[row].tbodyEl);
  4976. rowEl.append(skeletonEl);
  4977. helperNodes.push(skeletonEl[0]);
  4978. });
  4979. return ( // must return the elements rendered
  4980. this.helperEls = $(helperNodes) // array -> jQuery set
  4981. );
  4982. },
  4983. // Unrenders any visual indication of a mock helper event
  4984. unrenderHelper: function() {
  4985. if (this.helperEls) {
  4986. this.helperEls.remove();
  4987. this.helperEls = null;
  4988. }
  4989. },
  4990. /* Fill System (highlight, background events, business hours)
  4991. ------------------------------------------------------------------------------------------------------------------*/
  4992. fillSegTag: 'td', // override the default tag name
  4993. // Renders a set of rectangles over the given segments of days.
  4994. // Only returns segments that successfully rendered.
  4995. renderFill: function(type, segs, className) {
  4996. var nodes = [];
  4997. var i, seg;
  4998. var skeletonEl;
  4999. segs = this.renderFillSegEls(type, segs); // assignes `.el` to each seg. returns successfully rendered segs
  5000. for (i = 0; i < segs.length; i++) {
  5001. seg = segs[i];
  5002. skeletonEl = this.renderFillRow(type, seg, className);
  5003. this.rowEls.eq(seg.row).append(skeletonEl);
  5004. nodes.push(skeletonEl[0]);
  5005. }
  5006. this.elsByFill[type] = $(nodes);
  5007. return segs;
  5008. },
  5009. // Generates the HTML needed for one row of a fill. Requires the seg's el to be rendered.
  5010. renderFillRow: function(type, seg, className) {
  5011. var colCnt = this.colCnt;
  5012. var startCol = seg.leftCol;
  5013. var endCol = seg.rightCol + 1;
  5014. var skeletonEl;
  5015. var trEl;
  5016. className = className || type.toLowerCase();
  5017. skeletonEl = $(
  5018. '<div class="fc-' + className + '-skeleton">' +
  5019. '<table><tr/></table>' +
  5020. '</div>'
  5021. );
  5022. trEl = skeletonEl.find('tr');
  5023. if (startCol > 0) {
  5024. trEl.append('<td colspan="' + startCol + '"/>');
  5025. }
  5026. trEl.append(
  5027. seg.el.attr('colspan', endCol - startCol)
  5028. );
  5029. if (endCol < colCnt) {
  5030. trEl.append('<td colspan="' + (colCnt - endCol) + '"/>');
  5031. }
  5032. this.bookendCells(trEl);
  5033. return skeletonEl;
  5034. }
  5035. });
  5036. ;;
  5037. /* Event-rendering methods for the DayGrid class
  5038. ----------------------------------------------------------------------------------------------------------------------*/
  5039. DayGrid.mixin({
  5040. rowStructs: null, // an array of objects, each holding information about a row's foreground event-rendering
  5041. // Unrenders all events currently rendered on the grid
  5042. unrenderEvents: function() {
  5043. this.removeSegPopover(); // removes the "more.." events popover
  5044. Grid.prototype.unrenderEvents.apply(this, arguments); // calls the super-method
  5045. },
  5046. // Retrieves all rendered segment objects currently rendered on the grid
  5047. getEventSegs: function() {
  5048. return Grid.prototype.getEventSegs.call(this) // get the segments from the super-method
  5049. .concat(this.popoverSegs || []); // append the segments from the "more..." popover
  5050. },
  5051. // Renders the given background event segments onto the grid
  5052. renderBgSegs: function(segs) {
  5053. // don't render timed background events
  5054. var allDaySegs = $.grep(segs, function(seg) {
  5055. return seg.event.allDay;
  5056. });
  5057. return Grid.prototype.renderBgSegs.call(this, allDaySegs); // call the super-method
  5058. },
  5059. // Renders the given foreground event segments onto the grid
  5060. renderFgSegs: function(segs) {
  5061. var rowStructs;
  5062. // render an `.el` on each seg
  5063. // returns a subset of the segs. segs that were actually rendered
  5064. segs = this.renderFgSegEls(segs);
  5065. rowStructs = this.rowStructs = this.renderSegRows(segs);
  5066. // append to each row's content skeleton
  5067. this.rowEls.each(function(i, rowNode) {
  5068. $(rowNode).find('.fc-content-skeleton > table').append(
  5069. rowStructs[i].tbodyEl
  5070. );
  5071. });
  5072. return segs; // return only the segs that were actually rendered
  5073. },
  5074. // Unrenders all currently rendered foreground event segments
  5075. unrenderFgSegs: function() {
  5076. var rowStructs = this.rowStructs || [];
  5077. var rowStruct;
  5078. while ((rowStruct = rowStructs.pop())) {
  5079. rowStruct.tbodyEl.remove();
  5080. }
  5081. this.rowStructs = null;
  5082. },
  5083. // Uses the given events array to generate <tbody> elements that should be appended to each row's content skeleton.
  5084. // Returns an array of rowStruct objects (see the bottom of `renderSegRow`).
  5085. // PRECONDITION: each segment shoud already have a rendered and assigned `.el`
  5086. renderSegRows: function(segs) {
  5087. var rowStructs = [];
  5088. var segRows;
  5089. var row;
  5090. segRows = this.groupSegRows(segs); // group into nested arrays
  5091. // iterate each row of segment groupings
  5092. for (row = 0; row < segRows.length; row++) {
  5093. rowStructs.push(
  5094. this.renderSegRow(row, segRows[row])
  5095. );
  5096. }
  5097. return rowStructs;
  5098. },
  5099. // Builds the HTML to be used for the default element for an individual segment
  5100. fgSegHtml: function(seg, disableResizing) {
  5101. var view = this.view;
  5102. var event = seg.event;
  5103. var isDraggable = view.isEventDraggable(event);
  5104. var isResizableFromStart = !disableResizing && event.allDay &&
  5105. seg.isStart && view.isEventResizableFromStart(event);
  5106. var isResizableFromEnd = !disableResizing && event.allDay &&
  5107. seg.isEnd && view.isEventResizableFromEnd(event);
  5108. var classes = this.getSegClasses(seg, isDraggable, isResizableFromStart || isResizableFromEnd);
  5109. var skinCss = cssToStr(this.getSegSkinCss(seg));
  5110. var timeHtml = '';
  5111. var timeText;
  5112. var titleHtml;
  5113. var urlMeta = event.id ? htmlEscape(event.id) : 'none';
  5114. var metadata = '<div id="'+urlMeta+'" class="white-popup mfp-with-anim mfp-hide"><div class="col-md-8 col-md-offset-2 '+urlMeta+'-metadata-info"></div></div>';
  5115. var detailsJSON = JSON.stringify(event.details);
  5116. classes.unshift('fc-day-grid-event', 'fc-h-event');
  5117. // Only display a timed events time if it is the starting segment
  5118. if (seg.isStart) {
  5119. timeText = this.getEventTimeText(event);
  5120. if (timeText) {
  5121. timeHtml = '<span class="fc-time '+(htmlEscape(event.imagetype || '') || '&nbsp;')+'">' + htmlEscape(timeText) + '</span><br/>';
  5122. }else{
  5123. timeHtml = '<br/>';
  5124. }
  5125. }
  5126. titleHtml =
  5127. '<span class="fc-title">' +
  5128. (htmlEscape(event.title || '') || '&nbsp;') + // we always want one line of height
  5129. '</span>';
  5130. switch(event.imagetypeFilter){
  5131. case 'tv':
  5132. titleHtml = titleHtml + '<br/><small class="fc-title m-l-5 hidden-xs">' +
  5133. (htmlEscape(event.details.bottomTitle || '') || '&nbsp;') + // we always want one line of height
  5134. '</small>';
  5135. break;
  5136. case 'music':
  5137. titleHtml = titleHtml + '<br/><small class="fc-title m-l-5 hidden-xs">' +
  5138. (htmlEscape(event.details.topTitle || '') || '&nbsp;') + // we always want one line of height
  5139. '</small>';
  5140. break;
  5141. case 'film':
  5142. titleHtml = titleHtml + '<br/><small class="fc-title m-l-5 hidden-xs">' +
  5143. (htmlEscape(event.details.studio || '') || '&nbsp;') + // we always want one line of height
  5144. '</small>';
  5145. break;
  5146. default:
  5147. titleHtml = titleHtml + '<br/><small class="fc-title m-l-5 hidden-xs">' +
  5148. (htmlEscape('' || '') || '&nbsp;') + // we always want one line of height
  5149. '</small>';
  5150. }
  5151. imageHtml =
  5152. '<span class="fc-status '+ event.bgColor +'"></span><span class="fc-image"><i class="fa fa-' +
  5153. (htmlEscape(event.imagetype || '') || '&nbsp;') + // we always want one line of height
  5154. '"></i></span>';
  5155. return '<a class=" ' + classes.join(' ') + '"' +
  5156. (event.id ?
  5157. ' data-effect="mfp-zoom-out" data-target="'+ htmlEscape(event.id) +'" data-details="'+htmlEscape(detailsJSON) +'" data-mfp-src="#' + htmlEscape(event.id) + '"' :
  5158. ''
  5159. ) +
  5160. (skinCss ?
  5161. ' style="' + skinCss + '"' :
  5162. ''
  5163. ) +
  5164. '>' +
  5165. '<div class="fc-content">' +
  5166. (this.isRTL ?
  5167. titleHtml + ' ' + timeHtml : // put a natural space in between
  5168. imageHtml + ' ' + timeHtml + ' ' + titleHtml //
  5169. ) +
  5170. '</div>' +
  5171. (isResizableFromStart ?
  5172. '<div class="fc-resizer fc-start-resizer" />' :
  5173. ''
  5174. ) +
  5175. (isResizableFromEnd ?
  5176. '<div class="fc-resizer fc-end-resizer" />' :
  5177. ''
  5178. ) +metadata+
  5179. '</a>';
  5180. },
  5181. // Given a row # and an array of segments all in the same row, render a <tbody> element, a skeleton that contains
  5182. // the segments. Returns object with a bunch of internal data about how the render was calculated.
  5183. // NOTE: modifies rowSegs
  5184. renderSegRow: function(row, rowSegs) {
  5185. var colCnt = this.colCnt;
  5186. var segLevels = this.buildSegLevels(rowSegs); // group into sub-arrays of levels
  5187. var levelCnt = Math.max(1, segLevels.length); // ensure at least one level
  5188. var tbody = $('<tbody/>');
  5189. var segMatrix = []; // lookup for which segments are rendered into which level+col cells
  5190. var cellMatrix = []; // lookup for all <td> elements of the level+col matrix
  5191. var loneCellMatrix = []; // lookup for <td> elements that only take up a single column
  5192. var i, levelSegs;
  5193. var col;
  5194. var tr;
  5195. var j, seg;
  5196. var td;
  5197. // populates empty cells from the current column (`col`) to `endCol`
  5198. function emptyCellsUntil(endCol) {
  5199. while (col < endCol) {
  5200. // try to grab a cell from the level above and extend its rowspan. otherwise, create a fresh cell
  5201. td = (loneCellMatrix[i - 1] || [])[col];
  5202. if (td) {
  5203. td.attr(
  5204. 'rowspan',
  5205. parseInt(td.attr('rowspan') || 1, 10) + 1
  5206. );
  5207. }
  5208. else {
  5209. td = $('<td/>');
  5210. tr.append(td);
  5211. }
  5212. cellMatrix[i][col] = td;
  5213. loneCellMatrix[i][col] = td;
  5214. col++;
  5215. }
  5216. }
  5217. for (i = 0; i < levelCnt; i++) { // iterate through all levels
  5218. levelSegs = segLevels[i];
  5219. col = 0;
  5220. tr = $('<tr/>');
  5221. segMatrix.push([]);
  5222. cellMatrix.push([]);
  5223. loneCellMatrix.push([]);
  5224. // levelCnt might be 1 even though there are no actual levels. protect against this.
  5225. // this single empty row is useful for styling.
  5226. if (levelSegs) {
  5227. for (j = 0; j < levelSegs.length; j++) { // iterate through segments in level
  5228. seg = levelSegs[j];
  5229. emptyCellsUntil(seg.leftCol);
  5230. // create a container that occupies or more columns. append the event element.
  5231. td = $('<td class="fc-event-container"/>').append(seg.el);
  5232. if (seg.leftCol != seg.rightCol) {
  5233. td.attr('colspan', seg.rightCol - seg.leftCol + 1);
  5234. }
  5235. else { // a single-column segment
  5236. loneCellMatrix[i][col] = td;
  5237. }
  5238. while (col <= seg.rightCol) {
  5239. cellMatrix[i][col] = td;
  5240. segMatrix[i][col] = seg;
  5241. col++;
  5242. }
  5243. tr.append(td);
  5244. }
  5245. }
  5246. emptyCellsUntil(colCnt); // finish off the row
  5247. this.bookendCells(tr);
  5248. tbody.append(tr);
  5249. }
  5250. return { // a "rowStruct"
  5251. row: row, // the row number
  5252. tbodyEl: tbody,
  5253. cellMatrix: cellMatrix,
  5254. segMatrix: segMatrix,
  5255. segLevels: segLevels,
  5256. segs: rowSegs
  5257. };
  5258. },
  5259. // Stacks a flat array of segments, which are all assumed to be in the same row, into subarrays of vertical levels.
  5260. // NOTE: modifies segs
  5261. buildSegLevels: function(segs) {
  5262. var levels = [];
  5263. var i, seg;
  5264. var j;
  5265. // Give preference to elements with certain criteria, so they have
  5266. // a chance to be closer to the top.
  5267. this.sortEventSegs(segs);
  5268. for (i = 0; i < segs.length; i++) {
  5269. seg = segs[i];
  5270. // loop through levels, starting with the topmost, until the segment doesn't collide with other segments
  5271. for (j = 0; j < levels.length; j++) {
  5272. if (!isDaySegCollision(seg, levels[j])) {
  5273. break;
  5274. }
  5275. }
  5276. // `j` now holds the desired subrow index
  5277. seg.level = j;
  5278. // create new level array if needed and append segment
  5279. (levels[j] || (levels[j] = [])).push(seg);
  5280. }
  5281. // order segments left-to-right. very important if calendar is RTL
  5282. for (j = 0; j < levels.length; j++) {
  5283. levels[j].sort(compareDaySegCols);
  5284. }
  5285. return levels;
  5286. },
  5287. // Given a flat array of segments, return an array of sub-arrays, grouped by each segment's row
  5288. groupSegRows: function(segs) {
  5289. var segRows = [];
  5290. var i;
  5291. for (i = 0; i < this.rowCnt; i++) {
  5292. segRows.push([]);
  5293. }
  5294. for (i = 0; i < segs.length; i++) {
  5295. segRows[segs[i].row].push(segs[i]);
  5296. }
  5297. return segRows;
  5298. }
  5299. });
  5300. // Computes whether two segments' columns collide. They are assumed to be in the same row.
  5301. function isDaySegCollision(seg, otherSegs) {
  5302. var i, otherSeg;
  5303. for (i = 0; i < otherSegs.length; i++) {
  5304. otherSeg = otherSegs[i];
  5305. if (
  5306. otherSeg.leftCol <= seg.rightCol &&
  5307. otherSeg.rightCol >= seg.leftCol
  5308. ) {
  5309. return true;
  5310. }
  5311. }
  5312. return false;
  5313. }
  5314. // A cmp function for determining the leftmost event
  5315. function compareDaySegCols(a, b) {
  5316. return a.leftCol - b.leftCol;
  5317. }
  5318. ;;
  5319. /* Methods relate to limiting the number events for a given day on a DayGrid
  5320. ----------------------------------------------------------------------------------------------------------------------*/
  5321. // NOTE: all the segs being passed around in here are foreground segs
  5322. DayGrid.mixin({
  5323. segPopover: null, // the Popover that holds events that can't fit in a cell. null when not visible
  5324. popoverSegs: null, // an array of segment objects that the segPopover holds. null when not visible
  5325. removeSegPopover: function() {
  5326. if (this.segPopover) {
  5327. this.segPopover.hide(); // in handler, will call segPopover's removeElement
  5328. }
  5329. },
  5330. // Limits the number of "levels" (vertically stacking layers of events) for each row of the grid.
  5331. // `levelLimit` can be false (don't limit), a number, or true (should be computed).
  5332. limitRows: function(levelLimit) {
  5333. var rowStructs = this.rowStructs || [];
  5334. var row; // row #
  5335. var rowLevelLimit;
  5336. for (row = 0; row < rowStructs.length; row++) {
  5337. this.unlimitRow(row);
  5338. if (!levelLimit) {
  5339. rowLevelLimit = false;
  5340. }
  5341. else if (typeof levelLimit === 'number') {
  5342. rowLevelLimit = levelLimit;
  5343. }
  5344. else {
  5345. rowLevelLimit = this.computeRowLevelLimit(row);
  5346. }
  5347. if (rowLevelLimit !== false) {
  5348. this.limitRow(row, rowLevelLimit);
  5349. }
  5350. }
  5351. },
  5352. // Computes the number of levels a row will accomodate without going outside its bounds.
  5353. // Assumes the row is "rigid" (maintains a constant height regardless of what is inside).
  5354. // `row` is the row number.
  5355. computeRowLevelLimit: function(row) {
  5356. var rowEl = this.rowEls.eq(row); // the containing "fake" row div
  5357. var rowHeight = rowEl.height(); // TODO: cache somehow?
  5358. var trEls = this.rowStructs[row].tbodyEl.children();
  5359. var i, trEl;
  5360. var trHeight;
  5361. function iterInnerHeights(i, childNode) {
  5362. trHeight = Math.max(trHeight, $(childNode).outerHeight());
  5363. }
  5364. // Reveal one level <tr> at a time and stop when we find one out of bounds
  5365. for (i = 0; i < trEls.length; i++) {
  5366. trEl = trEls.eq(i).removeClass('fc-limited'); // reset to original state (reveal)
  5367. // with rowspans>1 and IE8, trEl.outerHeight() would return the height of the largest cell,
  5368. // so instead, find the tallest inner content element.
  5369. trHeight = 0;
  5370. trEl.find('> td > :first-child').each(iterInnerHeights);
  5371. if (trEl.position().top + trHeight > rowHeight) {
  5372. return i;
  5373. }
  5374. }
  5375. return false; // should not limit at all
  5376. },
  5377. // Limits the given grid row to the maximum number of levels and injects "more" links if necessary.
  5378. // `row` is the row number.
  5379. // `levelLimit` is a number for the maximum (inclusive) number of levels allowed.
  5380. limitRow: function(row, levelLimit) {
  5381. var _this = this;
  5382. var rowStruct = this.rowStructs[row];
  5383. var moreNodes = []; // array of "more" <a> links and <td> DOM nodes
  5384. var col = 0; // col #, left-to-right (not chronologically)
  5385. var levelSegs; // array of segment objects in the last allowable level, ordered left-to-right
  5386. var cellMatrix; // a matrix (by level, then column) of all <td> jQuery elements in the row
  5387. var limitedNodes; // array of temporarily hidden level <tr> and segment <td> DOM nodes
  5388. var i, seg;
  5389. var segsBelow; // array of segment objects below `seg` in the current `col`
  5390. var totalSegsBelow; // total number of segments below `seg` in any of the columns `seg` occupies
  5391. var colSegsBelow; // array of segment arrays, below seg, one for each column (offset from segs's first column)
  5392. var td, rowspan;
  5393. var segMoreNodes; // array of "more" <td> cells that will stand-in for the current seg's cell
  5394. var j;
  5395. var moreTd, moreWrap, moreLink;
  5396. // Iterates through empty level cells and places "more" links inside if need be
  5397. function emptyCellsUntil(endCol) { // goes from current `col` to `endCol`
  5398. while (col < endCol) {
  5399. segsBelow = _this.getCellSegs(row, col, levelLimit);
  5400. if (segsBelow.length) {
  5401. td = cellMatrix[levelLimit - 1][col];
  5402. moreLink = _this.renderMoreLink(row, col, segsBelow);
  5403. moreWrap = $('<div/>').append(moreLink);
  5404. td.append(moreWrap);
  5405. moreNodes.push(moreWrap[0]);
  5406. }
  5407. col++;
  5408. }
  5409. }
  5410. if (levelLimit && levelLimit < rowStruct.segLevels.length) { // is it actually over the limit?
  5411. levelSegs = rowStruct.segLevels[levelLimit - 1];
  5412. cellMatrix = rowStruct.cellMatrix;
  5413. limitedNodes = rowStruct.tbodyEl.children().slice(levelLimit) // get level <tr> elements past the limit
  5414. .addClass('fc-limited').get(); // hide elements and get a simple DOM-nodes array
  5415. // iterate though segments in the last allowable level
  5416. for (i = 0; i < levelSegs.length; i++) {
  5417. seg = levelSegs[i];
  5418. emptyCellsUntil(seg.leftCol); // process empty cells before the segment
  5419. // determine *all* segments below `seg` that occupy the same columns
  5420. colSegsBelow = [];
  5421. totalSegsBelow = 0;
  5422. while (col <= seg.rightCol) {
  5423. segsBelow = this.getCellSegs(row, col, levelLimit);
  5424. colSegsBelow.push(segsBelow);
  5425. totalSegsBelow += segsBelow.length;
  5426. col++;
  5427. }
  5428. if (totalSegsBelow) { // do we need to replace this segment with one or many "more" links?
  5429. td = cellMatrix[levelLimit - 1][seg.leftCol]; // the segment's parent cell
  5430. rowspan = td.attr('rowspan') || 1;
  5431. segMoreNodes = [];
  5432. // make a replacement <td> for each column the segment occupies. will be one for each colspan
  5433. for (j = 0; j < colSegsBelow.length; j++) {
  5434. moreTd = $('<td class="fc-more-cell"/>').attr('rowspan', rowspan);
  5435. segsBelow = colSegsBelow[j];
  5436. moreLink = this.renderMoreLink(
  5437. row,
  5438. seg.leftCol + j,
  5439. [ seg ].concat(segsBelow) // count seg as hidden too
  5440. );
  5441. moreWrap = $('<div/>').append(moreLink);
  5442. moreTd.append(moreWrap);
  5443. segMoreNodes.push(moreTd[0]);
  5444. moreNodes.push(moreTd[0]);
  5445. }
  5446. td.addClass('fc-limited').after($(segMoreNodes)); // hide original <td> and inject replacements
  5447. limitedNodes.push(td[0]);
  5448. }
  5449. }
  5450. emptyCellsUntil(this.colCnt); // finish off the level
  5451. rowStruct.moreEls = $(moreNodes); // for easy undoing later
  5452. rowStruct.limitedEls = $(limitedNodes); // for easy undoing later
  5453. }
  5454. },
  5455. // Reveals all levels and removes all "more"-related elements for a grid's row.
  5456. // `row` is a row number.
  5457. unlimitRow: function(row) {
  5458. var rowStruct = this.rowStructs[row];
  5459. if (rowStruct.moreEls) {
  5460. rowStruct.moreEls.remove();
  5461. rowStruct.moreEls = null;
  5462. }
  5463. if (rowStruct.limitedEls) {
  5464. rowStruct.limitedEls.removeClass('fc-limited');
  5465. rowStruct.limitedEls = null;
  5466. }
  5467. },
  5468. // Renders an <a> element that represents hidden event element for a cell.
  5469. // Responsible for attaching click handler as well.
  5470. renderMoreLink: function(row, col, hiddenSegs) {
  5471. var _this = this;
  5472. var view = this.view;
  5473. return $('<a class="fc-more"/>')
  5474. .text(
  5475. this.getMoreLinkText(hiddenSegs.length)
  5476. )
  5477. .on('click', function(ev) {
  5478. var clickOption = view.opt('eventLimitClick');
  5479. var date = _this.getCellDate(row, col);
  5480. var moreEl = $(this);
  5481. var dayEl = _this.getCellEl(row, col);
  5482. var allSegs = _this.getCellSegs(row, col);
  5483. // rescope the segments to be within the cell's date
  5484. var reslicedAllSegs = _this.resliceDaySegs(allSegs, date);
  5485. var reslicedHiddenSegs = _this.resliceDaySegs(hiddenSegs, date);
  5486. if (typeof clickOption === 'function') {
  5487. // the returned value can be an atomic option
  5488. clickOption = view.publiclyTrigger('eventLimitClick', null, {
  5489. date: date,
  5490. dayEl: dayEl,
  5491. moreEl: moreEl,
  5492. segs: reslicedAllSegs,
  5493. hiddenSegs: reslicedHiddenSegs
  5494. }, ev);
  5495. }
  5496. if (clickOption === 'popover') {
  5497. _this.showSegPopover(row, col, moreEl, reslicedAllSegs);
  5498. }
  5499. else if (typeof clickOption === 'string') { // a view name
  5500. view.calendar.zoomTo(date, clickOption);
  5501. }
  5502. });
  5503. },
  5504. // Reveals the popover that displays all events within a cell
  5505. showSegPopover: function(row, col, moreLink, segs) {
  5506. var _this = this;
  5507. var view = this.view;
  5508. var moreWrap = moreLink.parent(); // the <div> wrapper around the <a>
  5509. var topEl; // the element we want to match the top coordinate of
  5510. var options;
  5511. if (this.rowCnt == 1) {
  5512. topEl = view.el; // will cause the popover to cover any sort of header
  5513. }
  5514. else {
  5515. topEl = this.rowEls.eq(row); // will align with top of row
  5516. }
  5517. options = {
  5518. className: 'fc-more-popover',
  5519. content: this.renderSegPopoverContent(row, col, segs),
  5520. parentEl: this.view.el.parent().parent().parent(), // attach to root of view. guarantees outside of scrollbars.
  5521. top: topEl.offset().top,
  5522. autoHide: true, // when the user clicks elsewhere, hide the popover
  5523. viewportConstrain: view.opt('popoverViewportConstrain'),
  5524. hide: function() {
  5525. // kill everything when the popover is hidden
  5526. // notify events to be removed
  5527. if (_this.popoverSegs) {
  5528. var seg;
  5529. for (var i = 0; i < _this.popoverSegs.length; ++i) {
  5530. seg = _this.popoverSegs[i];
  5531. view.publiclyTrigger('eventDestroy', seg.event, seg.event, seg.el);
  5532. }
  5533. }
  5534. _this.segPopover.removeElement();
  5535. _this.segPopover = null;
  5536. _this.popoverSegs = null;
  5537. }
  5538. };
  5539. // Determine horizontal coordinate.
  5540. // We use the moreWrap instead of the <td> to avoid border confusion.
  5541. if (this.isRTL) {
  5542. options.right = moreWrap.offset().left + moreWrap.outerWidth() + 1; // +1 to be over cell border
  5543. }
  5544. else {
  5545. options.left = moreWrap.offset().left - 1; // -1 to be over cell border
  5546. }
  5547. this.segPopover = new Popover(options);
  5548. this.segPopover.show();
  5549. inlineLoad();
  5550. // the popover doesn't live within the grid's container element, and thus won't get the event
  5551. // delegated-handlers for free. attach event-related handlers to the popover.
  5552. this.bindSegHandlersToEl(this.segPopover.el);
  5553. },
  5554. // Builds the inner DOM contents of the segment popover
  5555. renderSegPopoverContent: function(row, col, segs) {
  5556. var view = this.view;
  5557. var isTheme = view.opt('theme');
  5558. var title = this.getCellDate(row, col).format(view.opt('dayPopoverFormat'));
  5559. var content = $(
  5560. '<div class="fc-header ' + view.widgetHeaderClass + '">' +
  5561. '<span class="fc-close ' +
  5562. (isTheme ? 'ui-icon ui-icon-closethick' : 'fc-icon fc-icon-x') +
  5563. '"></span>' +
  5564. '<span class="fc-title">' +
  5565. htmlEscape(title) +
  5566. '</span>' +
  5567. '<div class="fc-clear"/>' +
  5568. '</div>' +
  5569. '<div class="fc-body ' + view.widgetContentClass + '">' +
  5570. '<div class="fc-event-container"></div>' +
  5571. '</div>'
  5572. );
  5573. var segContainer = content.find('.fc-event-container');
  5574. var i;
  5575. // render each seg's `el` and only return the visible segs
  5576. segs = this.renderFgSegEls(segs, true); // disableResizing=true
  5577. this.popoverSegs = segs;
  5578. for (i = 0; i < segs.length; i++) {
  5579. // because segments in the popover are not part of a grid coordinate system, provide a hint to any
  5580. // grids that want to do drag-n-drop about which cell it came from
  5581. this.hitsNeeded();
  5582. segs[i].hit = this.getCellHit(row, col);
  5583. this.hitsNotNeeded();
  5584. segContainer.append(segs[i].el);
  5585. }
  5586. return content;
  5587. },
  5588. // Given the events within an array of segment objects, reslice them to be in a single day
  5589. resliceDaySegs: function(segs, dayDate) {
  5590. // build an array of the original events
  5591. var events = $.map(segs, function(seg) {
  5592. return seg.event;
  5593. });
  5594. var dayStart = dayDate.clone();
  5595. var dayEnd = dayStart.clone().add(1, 'days');
  5596. var dayRange = { start: dayStart, end: dayEnd };
  5597. // slice the events with a custom slicing function
  5598. segs = this.eventsToSegs(
  5599. events,
  5600. function(range) {
  5601. var seg = intersectRanges(range, dayRange); // undefind if no intersection
  5602. return seg ? [ seg ] : []; // must return an array of segments
  5603. }
  5604. );
  5605. // force an order because eventsToSegs doesn't guarantee one
  5606. this.sortEventSegs(segs);
  5607. return segs;
  5608. },
  5609. // Generates the text that should be inside a "more" link, given the number of events it represents
  5610. getMoreLinkText: function(num) {
  5611. var opt = this.view.opt('eventLimitText');
  5612. if (typeof opt === 'function') {
  5613. return opt(num);
  5614. }
  5615. else {
  5616. return '+' + num + ' ' + opt;
  5617. }
  5618. },
  5619. // Returns segments within a given cell.
  5620. // If `startLevel` is specified, returns only events including and below that level. Otherwise returns all segs.
  5621. getCellSegs: function(row, col, startLevel) {
  5622. var segMatrix = this.rowStructs[row].segMatrix;
  5623. var level = startLevel || 0;
  5624. var segs = [];
  5625. var seg;
  5626. while (level < segMatrix.length) {
  5627. seg = segMatrix[level][col];
  5628. if (seg) {
  5629. segs.push(seg);
  5630. }
  5631. level++;
  5632. }
  5633. return segs;
  5634. }
  5635. });
  5636. ;;
  5637. /* A component that renders one or more columns of vertical time slots
  5638. ----------------------------------------------------------------------------------------------------------------------*/
  5639. // We mixin DayTable, even though there is only a single row of days
  5640. var TimeGrid = FC.TimeGrid = Grid.extend(DayTableMixin, {
  5641. slotDuration: null, // duration of a "slot", a distinct time segment on given day, visualized by lines
  5642. snapDuration: null, // granularity of time for dragging and selecting
  5643. snapsPerSlot: null,
  5644. minTime: null, // Duration object that denotes the first visible time of any given day
  5645. maxTime: null, // Duration object that denotes the exclusive visible end time of any given day
  5646. labelFormat: null, // formatting string for times running along vertical axis
  5647. labelInterval: null, // duration of how often a label should be displayed for a slot
  5648. colEls: null, // cells elements in the day-row background
  5649. slatContainerEl: null, // div that wraps all the slat rows
  5650. slatEls: null, // elements running horizontally across all columns
  5651. nowIndicatorEls: null,
  5652. colCoordCache: null,
  5653. slatCoordCache: null,
  5654. constructor: function() {
  5655. Grid.apply(this, arguments); // call the super-constructor
  5656. this.processOptions();
  5657. },
  5658. // Renders the time grid into `this.el`, which should already be assigned.
  5659. // Relies on the view's colCnt. In the future, this component should probably be self-sufficient.
  5660. renderDates: function() {
  5661. this.el.html(this.renderHtml());
  5662. this.colEls = this.el.find('.fc-day');
  5663. this.slatContainerEl = this.el.find('.fc-slats');
  5664. this.slatEls = this.slatContainerEl.find('tr');
  5665. this.colCoordCache = new CoordCache({
  5666. els: this.colEls,
  5667. isHorizontal: true
  5668. });
  5669. this.slatCoordCache = new CoordCache({
  5670. els: this.slatEls,
  5671. isVertical: true
  5672. });
  5673. this.renderContentSkeleton();
  5674. },
  5675. // Renders the basic HTML skeleton for the grid
  5676. renderHtml: function() {
  5677. return '' +
  5678. '<div class="fc-bg">' +
  5679. '<table>' +
  5680. this.renderBgTrHtml(0) + // row=0
  5681. '</table>' +
  5682. '</div>' +
  5683. '<div class="fc-slats">' +
  5684. '<table>' +
  5685. this.renderSlatRowHtml() +
  5686. '</table>' +
  5687. '</div>';
  5688. },
  5689. // Generates the HTML for the horizontal "slats" that run width-wise. Has a time axis on a side. Depends on RTL.
  5690. renderSlatRowHtml: function() {
  5691. var view = this.view;
  5692. var isRTL = this.isRTL;
  5693. var html = '';
  5694. var slotTime = moment.duration(+this.minTime); // wish there was .clone() for durations
  5695. var slotDate; // will be on the view's first day, but we only care about its time
  5696. var isLabeled;
  5697. var axisHtml;
  5698. // Calculate the time for each slot
  5699. while (slotTime < this.maxTime) {
  5700. slotDate = this.start.clone().time(slotTime);
  5701. isLabeled = isInt(divideDurationByDuration(slotTime, this.labelInterval));
  5702. axisHtml =
  5703. '<td class="fc-axis fc-time ' + view.widgetContentClass + '" ' + view.axisStyleAttr() + '>' +
  5704. (isLabeled ?
  5705. '<span>' + // for matchCellWidths
  5706. htmlEscape(slotDate.format(this.labelFormat)) +
  5707. '</span>' :
  5708. ''
  5709. ) +
  5710. '</td>';
  5711. html +=
  5712. '<tr data-time="' + slotDate.format('HH:mm:ss') + '"' +
  5713. (isLabeled ? '' : ' class="fc-minor"') +
  5714. '>' +
  5715. (!isRTL ? axisHtml : '') +
  5716. '<td class="' + view.widgetContentClass + '"/>' +
  5717. (isRTL ? axisHtml : '') +
  5718. "</tr>";
  5719. slotTime.add(this.slotDuration);
  5720. }
  5721. return html;
  5722. },
  5723. /* Options
  5724. ------------------------------------------------------------------------------------------------------------------*/
  5725. // Parses various options into properties of this object
  5726. processOptions: function() {
  5727. var view = this.view;
  5728. var slotDuration = view.opt('slotDuration');
  5729. var snapDuration = view.opt('snapDuration');
  5730. var input;
  5731. slotDuration = moment.duration(slotDuration);
  5732. snapDuration = snapDuration ? moment.duration(snapDuration) : slotDuration;
  5733. this.slotDuration = slotDuration;
  5734. this.snapDuration = snapDuration;
  5735. this.snapsPerSlot = slotDuration / snapDuration; // TODO: ensure an integer multiple?
  5736. this.minResizeDuration = snapDuration; // hack
  5737. this.minTime = moment.duration(view.opt('minTime'));
  5738. this.maxTime = moment.duration(view.opt('maxTime'));
  5739. // might be an array value (for TimelineView).
  5740. // if so, getting the most granular entry (the last one probably).
  5741. input = view.opt('slotLabelFormat');
  5742. if ($.isArray(input)) {
  5743. input = input[input.length - 1];
  5744. }
  5745. this.labelFormat =
  5746. input ||
  5747. view.opt('smallTimeFormat'); // the computed default
  5748. input = view.opt('slotLabelInterval');
  5749. this.labelInterval = input ?
  5750. moment.duration(input) :
  5751. this.computeLabelInterval(slotDuration);
  5752. },
  5753. // Computes an automatic value for slotLabelInterval
  5754. computeLabelInterval: function(slotDuration) {
  5755. var i;
  5756. var labelInterval;
  5757. var slotsPerLabel;
  5758. // find the smallest stock label interval that results in more than one slots-per-label
  5759. for (i = AGENDA_STOCK_SUB_DURATIONS.length - 1; i >= 0; i--) {
  5760. labelInterval = moment.duration(AGENDA_STOCK_SUB_DURATIONS[i]);
  5761. slotsPerLabel = divideDurationByDuration(labelInterval, slotDuration);
  5762. if (isInt(slotsPerLabel) && slotsPerLabel > 1) {
  5763. return labelInterval;
  5764. }
  5765. }
  5766. return moment.duration(slotDuration); // fall back. clone
  5767. },
  5768. // Computes a default event time formatting string if `timeFormat` is not explicitly defined
  5769. computeEventTimeFormat: function() {
  5770. return this.view.opt('noMeridiemTimeFormat'); // like "6:30" (no AM/PM)
  5771. },
  5772. // Computes a default `displayEventEnd` value if one is not expliclty defined
  5773. computeDisplayEventEnd: function() {
  5774. return true;
  5775. },
  5776. /* Hit System
  5777. ------------------------------------------------------------------------------------------------------------------*/
  5778. prepareHits: function() {
  5779. this.colCoordCache.build();
  5780. this.slatCoordCache.build();
  5781. },
  5782. releaseHits: function() {
  5783. this.colCoordCache.clear();
  5784. // NOTE: don't clear slatCoordCache because we rely on it for computeTimeTop
  5785. },
  5786. queryHit: function(leftOffset, topOffset) {
  5787. var snapsPerSlot = this.snapsPerSlot;
  5788. var colCoordCache = this.colCoordCache;
  5789. var slatCoordCache = this.slatCoordCache;
  5790. if (colCoordCache.isLeftInBounds(leftOffset) && slatCoordCache.isTopInBounds(topOffset)) {
  5791. var colIndex = colCoordCache.getHorizontalIndex(leftOffset);
  5792. var slatIndex = slatCoordCache.getVerticalIndex(topOffset);
  5793. if (colIndex != null && slatIndex != null) {
  5794. var slatTop = slatCoordCache.getTopOffset(slatIndex);
  5795. var slatHeight = slatCoordCache.getHeight(slatIndex);
  5796. var partial = (topOffset - slatTop) / slatHeight; // floating point number between 0 and 1
  5797. var localSnapIndex = Math.floor(partial * snapsPerSlot); // the snap # relative to start of slat
  5798. var snapIndex = slatIndex * snapsPerSlot + localSnapIndex;
  5799. var snapTop = slatTop + (localSnapIndex / snapsPerSlot) * slatHeight;
  5800. var snapBottom = slatTop + ((localSnapIndex + 1) / snapsPerSlot) * slatHeight;
  5801. return {
  5802. col: colIndex,
  5803. snap: snapIndex,
  5804. component: this, // needed unfortunately :(
  5805. left: colCoordCache.getLeftOffset(colIndex),
  5806. right: colCoordCache.getRightOffset(colIndex),
  5807. top: snapTop,
  5808. bottom: snapBottom
  5809. };
  5810. }
  5811. }
  5812. },
  5813. getHitSpan: function(hit) {
  5814. var start = this.getCellDate(0, hit.col); // row=0
  5815. var time = this.computeSnapTime(hit.snap); // pass in the snap-index
  5816. var end;
  5817. start.time(time);
  5818. end = start.clone().add(this.snapDuration);
  5819. return { start: start, end: end };
  5820. },
  5821. getHitEl: function(hit) {
  5822. return this.colEls.eq(hit.col);
  5823. },
  5824. /* Dates
  5825. ------------------------------------------------------------------------------------------------------------------*/
  5826. rangeUpdated: function() {
  5827. this.updateDayTable();
  5828. },
  5829. // Given a row number of the grid, representing a "snap", returns a time (Duration) from its start-of-day
  5830. computeSnapTime: function(snapIndex) {
  5831. return moment.duration(this.minTime + this.snapDuration * snapIndex);
  5832. },
  5833. // Slices up the given span (unzoned start/end with other misc data) into an array of segments
  5834. spanToSegs: function(span) {
  5835. var segs = this.sliceRangeByTimes(span);
  5836. var i;
  5837. for (i = 0; i < segs.length; i++) {
  5838. if (this.isRTL) {
  5839. segs[i].col = this.daysPerRow - 1 - segs[i].dayIndex;
  5840. }
  5841. else {
  5842. segs[i].col = segs[i].dayIndex;
  5843. }
  5844. }
  5845. return segs;
  5846. },
  5847. sliceRangeByTimes: function(range) {
  5848. var segs = [];
  5849. var seg;
  5850. var dayIndex;
  5851. var dayDate;
  5852. var dayRange;
  5853. for (dayIndex = 0; dayIndex < this.daysPerRow; dayIndex++) {
  5854. dayDate = this.dayDates[dayIndex].clone(); // TODO: better API for this?
  5855. dayRange = {
  5856. start: dayDate.clone().time(this.minTime),
  5857. end: dayDate.clone().time(this.maxTime)
  5858. };
  5859. seg = intersectRanges(range, dayRange); // both will be ambig timezone
  5860. if (seg) {
  5861. seg.dayIndex = dayIndex;
  5862. segs.push(seg);
  5863. }
  5864. }
  5865. return segs;
  5866. },
  5867. /* Coordinates
  5868. ------------------------------------------------------------------------------------------------------------------*/
  5869. updateSize: function(isResize) { // NOT a standard Grid method
  5870. this.slatCoordCache.build();
  5871. if (isResize) {
  5872. this.updateSegVerticals(
  5873. [].concat(this.fgSegs || [], this.bgSegs || [], this.businessSegs || [])
  5874. );
  5875. }
  5876. },
  5877. getTotalSlatHeight: function() {
  5878. return this.slatContainerEl.outerHeight();
  5879. },
  5880. // Computes the top coordinate, relative to the bounds of the grid, of the given date.
  5881. // A `startOfDayDate` must be given for avoiding ambiguity over how to treat midnight.
  5882. computeDateTop: function(date, startOfDayDate) {
  5883. return this.computeTimeTop(
  5884. moment.duration(
  5885. date - startOfDayDate.clone().stripTime()
  5886. )
  5887. );
  5888. },
  5889. // Computes the top coordinate, relative to the bounds of the grid, of the given time (a Duration).
  5890. computeTimeTop: function(time) {
  5891. var len = this.slatEls.length;
  5892. var slatCoverage = (time - this.minTime) / this.slotDuration; // floating-point value of # of slots covered
  5893. var slatIndex;
  5894. var slatRemainder;
  5895. // compute a floating-point number for how many slats should be progressed through.
  5896. // from 0 to number of slats (inclusive)
  5897. // constrained because minTime/maxTime might be customized.
  5898. slatCoverage = Math.max(0, slatCoverage);
  5899. slatCoverage = Math.min(len, slatCoverage);
  5900. // an integer index of the furthest whole slat
  5901. // from 0 to number slats (*exclusive*, so len-1)
  5902. slatIndex = Math.floor(slatCoverage);
  5903. slatIndex = Math.min(slatIndex, len - 1);
  5904. // how much further through the slatIndex slat (from 0.0-1.0) must be covered in addition.
  5905. // could be 1.0 if slatCoverage is covering *all* the slots
  5906. slatRemainder = slatCoverage - slatIndex;
  5907. return this.slatCoordCache.getTopPosition(slatIndex) +
  5908. this.slatCoordCache.getHeight(slatIndex) * slatRemainder;
  5909. },
  5910. /* Event Drag Visualization
  5911. ------------------------------------------------------------------------------------------------------------------*/
  5912. // Renders a visual indication of an event being dragged over the specified date(s).
  5913. // A returned value of `true` signals that a mock "helper" event has been rendered.
  5914. renderDrag: function(eventLocation, seg) {
  5915. if (seg) { // if there is event information for this drag, render a helper event
  5916. // returns mock event elements
  5917. // signal that a helper has been rendered
  5918. return this.renderEventLocationHelper(eventLocation, seg);
  5919. }
  5920. else {
  5921. // otherwise, just render a highlight
  5922. this.renderHighlight(this.eventToSpan(eventLocation));
  5923. }
  5924. },
  5925. // Unrenders any visual indication of an event being dragged
  5926. unrenderDrag: function() {
  5927. this.unrenderHelper();
  5928. this.unrenderHighlight();
  5929. },
  5930. /* Event Resize Visualization
  5931. ------------------------------------------------------------------------------------------------------------------*/
  5932. // Renders a visual indication of an event being resized
  5933. renderEventResize: function(eventLocation, seg) {
  5934. return this.renderEventLocationHelper(eventLocation, seg); // returns mock event elements
  5935. },
  5936. // Unrenders any visual indication of an event being resized
  5937. unrenderEventResize: function() {
  5938. this.unrenderHelper();
  5939. },
  5940. /* Event Helper
  5941. ------------------------------------------------------------------------------------------------------------------*/
  5942. // Renders a mock "helper" event. `sourceSeg` is the original segment object and might be null (an external drag)
  5943. renderHelper: function(event, sourceSeg) {
  5944. return this.renderHelperSegs(this.eventToSegs(event), sourceSeg); // returns mock event elements
  5945. },
  5946. // Unrenders any mock helper event
  5947. unrenderHelper: function() {
  5948. this.unrenderHelperSegs();
  5949. },
  5950. /* Business Hours
  5951. ------------------------------------------------------------------------------------------------------------------*/
  5952. renderBusinessHours: function() {
  5953. this.renderBusinessSegs(
  5954. this.buildBusinessHourSegs()
  5955. );
  5956. },
  5957. unrenderBusinessHours: function() {
  5958. this.unrenderBusinessSegs();
  5959. },
  5960. /* Now Indicator
  5961. ------------------------------------------------------------------------------------------------------------------*/
  5962. getNowIndicatorUnit: function() {
  5963. return 'minute'; // will refresh on the minute
  5964. },
  5965. renderNowIndicator: function(date) {
  5966. // seg system might be overkill, but it handles scenario where line needs to be rendered
  5967. // more than once because of columns with the same date (resources columns for example)
  5968. var segs = this.spanToSegs({ start: date, end: date });
  5969. var top = this.computeDateTop(date, date);
  5970. var nodes = [];
  5971. var i;
  5972. // render lines within the columns
  5973. for (i = 0; i < segs.length; i++) {
  5974. nodes.push($('<div class="fc-now-indicator fc-now-indicator-line"></div>')
  5975. .css('top', top)
  5976. .appendTo(this.colContainerEls.eq(segs[i].col))[0]);
  5977. }
  5978. // render an arrow over the axis
  5979. if (segs.length > 0) { // is the current time in view?
  5980. nodes.push($('<div class="fc-now-indicator fc-now-indicator-arrow"></div>')
  5981. .css('top', top)
  5982. .appendTo(this.el.find('.fc-content-skeleton'))[0]);
  5983. }
  5984. this.nowIndicatorEls = $(nodes);
  5985. },
  5986. unrenderNowIndicator: function() {
  5987. if (this.nowIndicatorEls) {
  5988. this.nowIndicatorEls.remove();
  5989. this.nowIndicatorEls = null;
  5990. }
  5991. },
  5992. /* Selection
  5993. ------------------------------------------------------------------------------------------------------------------*/
  5994. // Renders a visual indication of a selection. Overrides the default, which was to simply render a highlight.
  5995. renderSelection: function(span) {
  5996. if (this.view.opt('selectHelper')) { // this setting signals that a mock helper event should be rendered
  5997. // normally acceps an eventLocation, span has a start/end, which is good enough
  5998. this.renderEventLocationHelper(span);
  5999. }
  6000. else {
  6001. this.renderHighlight(span);
  6002. }
  6003. },
  6004. // Unrenders any visual indication of a selection
  6005. unrenderSelection: function() {
  6006. this.unrenderHelper();
  6007. this.unrenderHighlight();
  6008. },
  6009. /* Highlight
  6010. ------------------------------------------------------------------------------------------------------------------*/
  6011. renderHighlight: function(span) {
  6012. this.renderHighlightSegs(this.spanToSegs(span));
  6013. },
  6014. unrenderHighlight: function() {
  6015. this.unrenderHighlightSegs();
  6016. }
  6017. });
  6018. ;;
  6019. /* Methods for rendering SEGMENTS, pieces of content that live on the view
  6020. ( this file is no longer just for events )
  6021. ----------------------------------------------------------------------------------------------------------------------*/
  6022. TimeGrid.mixin({
  6023. colContainerEls: null, // containers for each column
  6024. // inner-containers for each column where different types of segs live
  6025. fgContainerEls: null,
  6026. bgContainerEls: null,
  6027. helperContainerEls: null,
  6028. highlightContainerEls: null,
  6029. businessContainerEls: null,
  6030. // arrays of different types of displayed segments
  6031. fgSegs: null,
  6032. bgSegs: null,
  6033. helperSegs: null,
  6034. highlightSegs: null,
  6035. businessSegs: null,
  6036. // Renders the DOM that the view's content will live in
  6037. renderContentSkeleton: function() {
  6038. var cellHtml = '';
  6039. var i;
  6040. var skeletonEl;
  6041. for (i = 0; i < this.colCnt; i++) {
  6042. cellHtml +=
  6043. '<td>' +
  6044. '<div class="fc-content-col">' +
  6045. '<div class="fc-event-container fc-helper-container"></div>' +
  6046. '<div class="fc-event-container"></div>' +
  6047. '<div class="fc-highlight-container"></div>' +
  6048. '<div class="fc-bgevent-container"></div>' +
  6049. '<div class="fc-business-container"></div>' +
  6050. '</div>' +
  6051. '</td>';
  6052. }
  6053. skeletonEl = $(
  6054. '<div class="fc-content-skeleton">' +
  6055. '<table>' +
  6056. '<tr>' + cellHtml + '</tr>' +
  6057. '</table>' +
  6058. '</div>'
  6059. );
  6060. this.colContainerEls = skeletonEl.find('.fc-content-col');
  6061. this.helperContainerEls = skeletonEl.find('.fc-helper-container');
  6062. this.fgContainerEls = skeletonEl.find('.fc-event-container:not(.fc-helper-container)');
  6063. this.bgContainerEls = skeletonEl.find('.fc-bgevent-container');
  6064. this.highlightContainerEls = skeletonEl.find('.fc-highlight-container');
  6065. this.businessContainerEls = skeletonEl.find('.fc-business-container');
  6066. this.bookendCells(skeletonEl.find('tr')); // TODO: do this on string level
  6067. this.el.append(skeletonEl);
  6068. },
  6069. /* Foreground Events
  6070. ------------------------------------------------------------------------------------------------------------------*/
  6071. renderFgSegs: function(segs) {
  6072. segs = this.renderFgSegsIntoContainers(segs, this.fgContainerEls);
  6073. this.fgSegs = segs;
  6074. return segs; // needed for Grid::renderEvents
  6075. },
  6076. unrenderFgSegs: function() {
  6077. this.unrenderNamedSegs('fgSegs');
  6078. },
  6079. /* Foreground Helper Events
  6080. ------------------------------------------------------------------------------------------------------------------*/
  6081. renderHelperSegs: function(segs, sourceSeg) {
  6082. var helperEls = [];
  6083. var i, seg;
  6084. var sourceEl;
  6085. segs = this.renderFgSegsIntoContainers(segs, this.helperContainerEls);
  6086. // Try to make the segment that is in the same row as sourceSeg look the same
  6087. for (i = 0; i < segs.length; i++) {
  6088. seg = segs[i];
  6089. if (sourceSeg && sourceSeg.col === seg.col) {
  6090. sourceEl = sourceSeg.el;
  6091. seg.el.css({
  6092. left: sourceEl.css('left'),
  6093. right: sourceEl.css('right'),
  6094. 'margin-left': sourceEl.css('margin-left'),
  6095. 'margin-right': sourceEl.css('margin-right')
  6096. });
  6097. }
  6098. helperEls.push(seg.el[0]);
  6099. }
  6100. this.helperSegs = segs;
  6101. return $(helperEls); // must return rendered helpers
  6102. },
  6103. unrenderHelperSegs: function() {
  6104. this.unrenderNamedSegs('helperSegs');
  6105. },
  6106. /* Background Events
  6107. ------------------------------------------------------------------------------------------------------------------*/
  6108. renderBgSegs: function(segs) {
  6109. segs = this.renderFillSegEls('bgEvent', segs); // TODO: old fill system
  6110. this.updateSegVerticals(segs);
  6111. this.attachSegsByCol(this.groupSegsByCol(segs), this.bgContainerEls);
  6112. this.bgSegs = segs;
  6113. return segs; // needed for Grid::renderEvents
  6114. },
  6115. unrenderBgSegs: function() {
  6116. this.unrenderNamedSegs('bgSegs');
  6117. },
  6118. /* Highlight
  6119. ------------------------------------------------------------------------------------------------------------------*/
  6120. renderHighlightSegs: function(segs) {
  6121. segs = this.renderFillSegEls('highlight', segs); // TODO: old fill system
  6122. this.updateSegVerticals(segs);
  6123. this.attachSegsByCol(this.groupSegsByCol(segs), this.highlightContainerEls);
  6124. this.highlightSegs = segs;
  6125. },
  6126. unrenderHighlightSegs: function() {
  6127. this.unrenderNamedSegs('highlightSegs');
  6128. },
  6129. /* Business Hours
  6130. ------------------------------------------------------------------------------------------------------------------*/
  6131. renderBusinessSegs: function(segs) {
  6132. segs = this.renderFillSegEls('businessHours', segs); // TODO: old fill system
  6133. this.updateSegVerticals(segs);
  6134. this.attachSegsByCol(this.groupSegsByCol(segs), this.businessContainerEls);
  6135. this.businessSegs = segs;
  6136. },
  6137. unrenderBusinessSegs: function() {
  6138. this.unrenderNamedSegs('businessSegs');
  6139. },
  6140. /* Seg Rendering Utils
  6141. ------------------------------------------------------------------------------------------------------------------*/
  6142. // Given a flat array of segments, return an array of sub-arrays, grouped by each segment's col
  6143. groupSegsByCol: function(segs) {
  6144. var segsByCol = [];
  6145. var i;
  6146. for (i = 0; i < this.colCnt; i++) {
  6147. segsByCol.push([]);
  6148. }
  6149. for (i = 0; i < segs.length; i++) {
  6150. segsByCol[segs[i].col].push(segs[i]);
  6151. }
  6152. return segsByCol;
  6153. },
  6154. // Given segments grouped by column, insert the segments' elements into a parallel array of container
  6155. // elements, each living within a column.
  6156. attachSegsByCol: function(segsByCol, containerEls) {
  6157. var col;
  6158. var segs;
  6159. var i;
  6160. for (col = 0; col < this.colCnt; col++) { // iterate each column grouping
  6161. segs = segsByCol[col];
  6162. for (i = 0; i < segs.length; i++) {
  6163. containerEls.eq(col).append(segs[i].el);
  6164. }
  6165. }
  6166. },
  6167. // Given the name of a property of `this` object, assumed to be an array of segments,
  6168. // loops through each segment and removes from DOM. Will null-out the property afterwards.
  6169. unrenderNamedSegs: function(propName) {
  6170. var segs = this[propName];
  6171. var i;
  6172. if (segs) {
  6173. for (i = 0; i < segs.length; i++) {
  6174. segs[i].el.remove();
  6175. }
  6176. this[propName] = null;
  6177. }
  6178. },
  6179. /* Foreground Event Rendering Utils
  6180. ------------------------------------------------------------------------------------------------------------------*/
  6181. // Given an array of foreground segments, render a DOM element for each, computes position,
  6182. // and attaches to the column inner-container elements.
  6183. renderFgSegsIntoContainers: function(segs, containerEls) {
  6184. var segsByCol;
  6185. var col;
  6186. segs = this.renderFgSegEls(segs); // will call fgSegHtml
  6187. segsByCol = this.groupSegsByCol(segs);
  6188. for (col = 0; col < this.colCnt; col++) {
  6189. this.updateFgSegCoords(segsByCol[col]);
  6190. }
  6191. this.attachSegsByCol(segsByCol, containerEls);
  6192. return segs;
  6193. },
  6194. // Renders the HTML for a single event segment's default rendering
  6195. fgSegHtml: function(seg, disableResizing) {
  6196. var view = this.view;
  6197. var event = seg.event;
  6198. var isDraggable = view.isEventDraggable(event);
  6199. var isResizableFromStart = !disableResizing && seg.isStart && view.isEventResizableFromStart(event);
  6200. var isResizableFromEnd = !disableResizing && seg.isEnd && view.isEventResizableFromEnd(event);
  6201. var classes = this.getSegClasses(seg, isDraggable, isResizableFromStart || isResizableFromEnd);
  6202. var skinCss = cssToStr(this.getSegSkinCss(seg));
  6203. var timeText;
  6204. var fullTimeText; // more verbose time text. for the print stylesheet
  6205. var startTimeText; // just the start time text
  6206. classes.unshift('fc-time-grid-event', 'fc-v-event');
  6207. if (view.isMultiDayEvent(event)) { // if the event appears to span more than one day...
  6208. // Don't display time text on segments that run entirely through a day.
  6209. // That would appear as midnight-midnight and would look dumb.
  6210. // Otherwise, display the time text for the *segment's* times (like 6pm-midnight or midnight-10am)
  6211. if (seg.isStart || seg.isEnd) {
  6212. timeText = this.getEventTimeText(seg);
  6213. fullTimeText = this.getEventTimeText(seg, 'LT');
  6214. startTimeText = this.getEventTimeText(seg, null, false); // displayEnd=false
  6215. }
  6216. } else {
  6217. // Display the normal time text for the *event's* times
  6218. timeText = this.getEventTimeText(event);
  6219. fullTimeText = this.getEventTimeText(event, 'LT');
  6220. startTimeText = this.getEventTimeText(event, null, false); // displayEnd=false
  6221. }
  6222. return '<a class="' + classes.join(' ') + '"' +
  6223. (event.url ?
  6224. ' target="_blank" href="' + htmlEscape(event.url) + '"' :
  6225. ''
  6226. ) +
  6227. (skinCss ?
  6228. ' style="' + skinCss + '"' :
  6229. ''
  6230. ) +
  6231. '>' +
  6232. '<div class="fc-content">' +
  6233. (timeText ?
  6234. '<div class="fc-time"' +
  6235. ' data-start="' + htmlEscape(startTimeText) + '"' +
  6236. ' data-full="' + htmlEscape(fullTimeText) + '"' +
  6237. '>' +
  6238. '<span>' + htmlEscape(timeText) + '</span>' +
  6239. '</div>' :
  6240. ''
  6241. ) +
  6242. (event.title ?
  6243. '<div class="fc-title">' +
  6244. htmlEscape(event.title) +
  6245. '</div>' :
  6246. ''
  6247. ) +
  6248. '</div>' +
  6249. '<div class="fc-bg"/>' +
  6250. /* TODO: write CSS for this
  6251. (isResizableFromStart ?
  6252. '<div class="fc-resizer fc-start-resizer" />' :
  6253. ''
  6254. ) +
  6255. */
  6256. (isResizableFromEnd ?
  6257. '<div class="fc-resizer fc-end-resizer" />' :
  6258. ''
  6259. ) +
  6260. '</a>';
  6261. },
  6262. /* Seg Position Utils
  6263. ------------------------------------------------------------------------------------------------------------------*/
  6264. // Refreshes the CSS top/bottom coordinates for each segment element.
  6265. // Works when called after initial render, after a window resize/zoom for example.
  6266. updateSegVerticals: function(segs) {
  6267. this.computeSegVerticals(segs);
  6268. this.assignSegVerticals(segs);
  6269. },
  6270. // For each segment in an array, computes and assigns its top and bottom properties
  6271. computeSegVerticals: function(segs) {
  6272. var i, seg;
  6273. for (i = 0; i < segs.length; i++) {
  6274. seg = segs[i];
  6275. seg.top = this.computeDateTop(seg.start, seg.start);
  6276. seg.bottom = this.computeDateTop(seg.end, seg.start);
  6277. }
  6278. },
  6279. // Given segments that already have their top/bottom properties computed, applies those values to
  6280. // the segments' elements.
  6281. assignSegVerticals: function(segs) {
  6282. var i, seg;
  6283. for (i = 0; i < segs.length; i++) {
  6284. seg = segs[i];
  6285. seg.el.css(this.generateSegVerticalCss(seg));
  6286. }
  6287. },
  6288. // Generates an object with CSS properties for the top/bottom coordinates of a segment element
  6289. generateSegVerticalCss: function(seg) {
  6290. return {
  6291. top: seg.top,
  6292. bottom: -seg.bottom // flipped because needs to be space beyond bottom edge of event container
  6293. };
  6294. },
  6295. /* Foreground Event Positioning Utils
  6296. ------------------------------------------------------------------------------------------------------------------*/
  6297. // Given segments that are assumed to all live in the *same column*,
  6298. // compute their verical/horizontal coordinates and assign to their elements.
  6299. updateFgSegCoords: function(segs) {
  6300. this.computeSegVerticals(segs); // horizontals relies on this
  6301. this.computeFgSegHorizontals(segs); // compute horizontal coordinates, z-index's, and reorder the array
  6302. this.assignSegVerticals(segs);
  6303. this.assignFgSegHorizontals(segs);
  6304. },
  6305. // Given an array of segments that are all in the same column, sets the backwardCoord and forwardCoord on each.
  6306. // NOTE: Also reorders the given array by date!
  6307. computeFgSegHorizontals: function(segs) {
  6308. var levels;
  6309. var level0;
  6310. var i;
  6311. this.sortEventSegs(segs); // order by certain criteria
  6312. levels = buildSlotSegLevels(segs);
  6313. computeForwardSlotSegs(levels);
  6314. if ((level0 = levels[0])) {
  6315. for (i = 0; i < level0.length; i++) {
  6316. computeSlotSegPressures(level0[i]);
  6317. }
  6318. for (i = 0; i < level0.length; i++) {
  6319. this.computeFgSegForwardBack(level0[i], 0, 0);
  6320. }
  6321. }
  6322. },
  6323. // Calculate seg.forwardCoord and seg.backwardCoord for the segment, where both values range
  6324. // from 0 to 1. If the calendar is left-to-right, the seg.backwardCoord maps to "left" and
  6325. // seg.forwardCoord maps to "right" (via percentage). Vice-versa if the calendar is right-to-left.
  6326. //
  6327. // The segment might be part of a "series", which means consecutive segments with the same pressure
  6328. // who's width is unknown until an edge has been hit. `seriesBackwardPressure` is the number of
  6329. // segments behind this one in the current series, and `seriesBackwardCoord` is the starting
  6330. // coordinate of the first segment in the series.
  6331. computeFgSegForwardBack: function(seg, seriesBackwardPressure, seriesBackwardCoord) {
  6332. var forwardSegs = seg.forwardSegs;
  6333. var i;
  6334. if (seg.forwardCoord === undefined) { // not already computed
  6335. if (!forwardSegs.length) {
  6336. // if there are no forward segments, this segment should butt up against the edge
  6337. seg.forwardCoord = 1;
  6338. }
  6339. else {
  6340. // sort highest pressure first
  6341. this.sortForwardSegs(forwardSegs);
  6342. // this segment's forwardCoord will be calculated from the backwardCoord of the
  6343. // highest-pressure forward segment.
  6344. this.computeFgSegForwardBack(forwardSegs[0], seriesBackwardPressure + 1, seriesBackwardCoord);
  6345. seg.forwardCoord = forwardSegs[0].backwardCoord;
  6346. }
  6347. // calculate the backwardCoord from the forwardCoord. consider the series
  6348. seg.backwardCoord = seg.forwardCoord -
  6349. (seg.forwardCoord - seriesBackwardCoord) / // available width for series
  6350. (seriesBackwardPressure + 1); // # of segments in the series
  6351. // use this segment's coordinates to computed the coordinates of the less-pressurized
  6352. // forward segments
  6353. for (i=0; i<forwardSegs.length; i++) {
  6354. this.computeFgSegForwardBack(forwardSegs[i], 0, seg.forwardCoord);
  6355. }
  6356. }
  6357. },
  6358. sortForwardSegs: function(forwardSegs) {
  6359. forwardSegs.sort(proxy(this, 'compareForwardSegs'));
  6360. },
  6361. // A cmp function for determining which forward segment to rely on more when computing coordinates.
  6362. compareForwardSegs: function(seg1, seg2) {
  6363. // put higher-pressure first
  6364. return seg2.forwardPressure - seg1.forwardPressure ||
  6365. // put segments that are closer to initial edge first (and favor ones with no coords yet)
  6366. (seg1.backwardCoord || 0) - (seg2.backwardCoord || 0) ||
  6367. // do normal sorting...
  6368. this.compareEventSegs(seg1, seg2);
  6369. },
  6370. // Given foreground event segments that have already had their position coordinates computed,
  6371. // assigns position-related CSS values to their elements.
  6372. assignFgSegHorizontals: function(segs) {
  6373. var i, seg;
  6374. for (i = 0; i < segs.length; i++) {
  6375. seg = segs[i];
  6376. seg.el.css(this.generateFgSegHorizontalCss(seg));
  6377. // if the height is short, add a className for alternate styling
  6378. if (seg.bottom - seg.top < 30) {
  6379. seg.el.addClass('fc-short');
  6380. }
  6381. }
  6382. },
  6383. // Generates an object with CSS properties/values that should be applied to an event segment element.
  6384. // Contains important positioning-related properties that should be applied to any event element, customized or not.
  6385. generateFgSegHorizontalCss: function(seg) {
  6386. var shouldOverlap = this.view.opt('slotEventOverlap');
  6387. var backwardCoord = seg.backwardCoord; // the left side if LTR. the right side if RTL. floating-point
  6388. var forwardCoord = seg.forwardCoord; // the right side if LTR. the left side if RTL. floating-point
  6389. var props = this.generateSegVerticalCss(seg); // get top/bottom first
  6390. var left; // amount of space from left edge, a fraction of the total width
  6391. var right; // amount of space from right edge, a fraction of the total width
  6392. if (shouldOverlap) {
  6393. // double the width, but don't go beyond the maximum forward coordinate (1.0)
  6394. forwardCoord = Math.min(1, backwardCoord + (forwardCoord - backwardCoord) * 2);
  6395. }
  6396. if (this.isRTL) {
  6397. left = 1 - forwardCoord;
  6398. right = backwardCoord;
  6399. }
  6400. else {
  6401. left = backwardCoord;
  6402. right = 1 - forwardCoord;
  6403. }
  6404. props.zIndex = seg.level + 1; // convert from 0-base to 1-based
  6405. props.left = left * 100 + '%';
  6406. props.right = right * 100 + '%';
  6407. if (shouldOverlap && seg.forwardPressure) {
  6408. // add padding to the edge so that forward stacked events don't cover the resizer's icon
  6409. props[this.isRTL ? 'marginLeft' : 'marginRight'] = 10 * 2; // 10 is a guesstimate of the icon's width
  6410. }
  6411. return props;
  6412. }
  6413. });
  6414. // Builds an array of segments "levels". The first level will be the leftmost tier of segments if the calendar is
  6415. // left-to-right, or the rightmost if the calendar is right-to-left. Assumes the segments are already ordered by date.
  6416. function buildSlotSegLevels(segs) {
  6417. var levels = [];
  6418. var i, seg;
  6419. var j;
  6420. for (i=0; i<segs.length; i++) {
  6421. seg = segs[i];
  6422. // go through all the levels and stop on the first level where there are no collisions
  6423. for (j=0; j<levels.length; j++) {
  6424. if (!computeSlotSegCollisions(seg, levels[j]).length) {
  6425. break;
  6426. }
  6427. }
  6428. seg.level = j;
  6429. (levels[j] || (levels[j] = [])).push(seg);
  6430. }
  6431. return levels;
  6432. }
  6433. // For every segment, figure out the other segments that are in subsequent
  6434. // levels that also occupy the same vertical space. Accumulate in seg.forwardSegs
  6435. function computeForwardSlotSegs(levels) {
  6436. var i, level;
  6437. var j, seg;
  6438. var k;
  6439. for (i=0; i<levels.length; i++) {
  6440. level = levels[i];
  6441. for (j=0; j<level.length; j++) {
  6442. seg = level[j];
  6443. seg.forwardSegs = [];
  6444. for (k=i+1; k<levels.length; k++) {
  6445. computeSlotSegCollisions(seg, levels[k], seg.forwardSegs);
  6446. }
  6447. }
  6448. }
  6449. }
  6450. // Figure out which path forward (via seg.forwardSegs) results in the longest path until
  6451. // the furthest edge is reached. The number of segments in this path will be seg.forwardPressure
  6452. function computeSlotSegPressures(seg) {
  6453. var forwardSegs = seg.forwardSegs;
  6454. var forwardPressure = 0;
  6455. var i, forwardSeg;
  6456. if (seg.forwardPressure === undefined) { // not already computed
  6457. for (i=0; i<forwardSegs.length; i++) {
  6458. forwardSeg = forwardSegs[i];
  6459. // figure out the child's maximum forward path
  6460. computeSlotSegPressures(forwardSeg);
  6461. // either use the existing maximum, or use the child's forward pressure
  6462. // plus one (for the forwardSeg itself)
  6463. forwardPressure = Math.max(
  6464. forwardPressure,
  6465. 1 + forwardSeg.forwardPressure
  6466. );
  6467. }
  6468. seg.forwardPressure = forwardPressure;
  6469. }
  6470. }
  6471. // Find all the segments in `otherSegs` that vertically collide with `seg`.
  6472. // Append into an optionally-supplied `results` array and return.
  6473. function computeSlotSegCollisions(seg, otherSegs, results) {
  6474. results = results || [];
  6475. for (var i=0; i<otherSegs.length; i++) {
  6476. if (isSlotSegCollision(seg, otherSegs[i])) {
  6477. results.push(otherSegs[i]);
  6478. }
  6479. }
  6480. return results;
  6481. }
  6482. // Do these segments occupy the same vertical space?
  6483. function isSlotSegCollision(seg1, seg2) {
  6484. return seg1.bottom > seg2.top && seg1.top < seg2.bottom;
  6485. }
  6486. ;;
  6487. /* An abstract class from which other views inherit from
  6488. ----------------------------------------------------------------------------------------------------------------------*/
  6489. var View = FC.View = Class.extend(EmitterMixin, ListenerMixin, {
  6490. type: null, // subclass' view name (string)
  6491. name: null, // deprecated. use `type` instead
  6492. title: null, // the text that will be displayed in the header's title
  6493. calendar: null, // owner Calendar object
  6494. options: null, // hash containing all options. already merged with view-specific-options
  6495. el: null, // the view's containing element. set by Calendar
  6496. isDateSet: false,
  6497. isDateRendered: false,
  6498. dateRenderQueue: null,
  6499. isEventsBound: false,
  6500. isEventsSet: false,
  6501. isEventsRendered: false,
  6502. eventRenderQueue: null,
  6503. // range the view is actually displaying (moments)
  6504. start: null,
  6505. end: null, // exclusive
  6506. // range the view is formally responsible for (moments)
  6507. // may be different from start/end. for example, a month view might have 1st-31st, excluding padded dates
  6508. intervalStart: null,
  6509. intervalEnd: null, // exclusive
  6510. intervalDuration: null,
  6511. intervalUnit: null, // name of largest unit being displayed, like "month" or "week"
  6512. isRTL: false,
  6513. isSelected: false, // boolean whether a range of time is user-selected or not
  6514. selectedEvent: null,
  6515. eventOrderSpecs: null, // criteria for ordering events when they have same date/time
  6516. // classNames styled by jqui themes
  6517. widgetHeaderClass: null,
  6518. widgetContentClass: null,
  6519. highlightStateClass: null,
  6520. // for date utils, computed from options
  6521. nextDayThreshold: null,
  6522. isHiddenDayHash: null,
  6523. // now indicator
  6524. isNowIndicatorRendered: null,
  6525. initialNowDate: null, // result first getNow call
  6526. initialNowQueriedMs: null, // ms time the getNow was called
  6527. nowIndicatorTimeoutID: null, // for refresh timing of now indicator
  6528. nowIndicatorIntervalID: null, // "
  6529. constructor: function(calendar, type, options, intervalDuration) {
  6530. this.calendar = calendar;
  6531. this.type = this.name = type; // .name is deprecated
  6532. this.options = options;
  6533. this.intervalDuration = intervalDuration || moment.duration(1, 'day');
  6534. this.nextDayThreshold = moment.duration(this.opt('nextDayThreshold'));
  6535. this.initThemingProps();
  6536. this.initHiddenDays();
  6537. this.isRTL = this.opt('isRTL');
  6538. this.eventOrderSpecs = parseFieldSpecs(this.opt('eventOrder'));
  6539. this.dateRenderQueue = new TaskQueue();
  6540. this.eventRenderQueue = new TaskQueue(this.opt('eventRenderWait'));
  6541. this.initialize();
  6542. },
  6543. // A good place for subclasses to initialize member variables
  6544. initialize: function() {
  6545. // subclasses can implement
  6546. },
  6547. // Retrieves an option with the given name
  6548. opt: function(name) {
  6549. return this.options[name];
  6550. },
  6551. // Triggers handlers that are view-related. Modifies args before passing to calendar.
  6552. publiclyTrigger: function(name, thisObj) { // arguments beyond thisObj are passed along
  6553. var calendar = this.calendar;
  6554. return calendar.publiclyTrigger.apply(
  6555. calendar,
  6556. [name, thisObj || this].concat(
  6557. Array.prototype.slice.call(arguments, 2), // arguments beyond thisObj
  6558. [ this ] // always make the last argument a reference to the view. TODO: deprecate
  6559. )
  6560. );
  6561. },
  6562. // Returns a proxy of the given promise that will be rejected if the given event fires
  6563. // before the promise resolves.
  6564. rejectOn: function(eventName, promise) {
  6565. var _this = this;
  6566. return new Promise(function(resolve, reject) {
  6567. _this.one(eventName, reject);
  6568. function cleanup() {
  6569. _this.off(eventName, reject);
  6570. }
  6571. promise.then(function(res) { // success
  6572. cleanup();
  6573. resolve(res);
  6574. }, function() { // failure
  6575. cleanup();
  6576. reject();
  6577. });
  6578. });
  6579. },
  6580. /* Date Computation
  6581. ------------------------------------------------------------------------------------------------------------------*/
  6582. // Updates all internal dates for displaying the given unzoned range.
  6583. setRange: function(range) {
  6584. $.extend(this, range); // assigns every property to this object's member variables
  6585. this.updateTitle();
  6586. },
  6587. // Given a single current unzoned date, produce information about what range to display.
  6588. // Subclasses can override. Must return all properties.
  6589. computeRange: function(date) {
  6590. var intervalUnit = computeIntervalUnit(this.intervalDuration);
  6591. var intervalStart = date.clone().startOf(intervalUnit);
  6592. var intervalEnd = intervalStart.clone().add(this.intervalDuration);
  6593. var start, end;
  6594. // normalize the range's time-ambiguity
  6595. if (/year|month|week|day/.test(intervalUnit)) { // whole-days?
  6596. intervalStart.stripTime();
  6597. intervalEnd.stripTime();
  6598. }
  6599. else { // needs to have a time?
  6600. if (!intervalStart.hasTime()) {
  6601. intervalStart = this.calendar.time(0); // give 00:00 time
  6602. }
  6603. if (!intervalEnd.hasTime()) {
  6604. intervalEnd = this.calendar.time(0); // give 00:00 time
  6605. }
  6606. }
  6607. start = intervalStart.clone();
  6608. start = this.skipHiddenDays(start);
  6609. end = intervalEnd.clone();
  6610. end = this.skipHiddenDays(end, -1, true); // exclusively move backwards
  6611. return {
  6612. intervalUnit: intervalUnit,
  6613. intervalStart: intervalStart,
  6614. intervalEnd: intervalEnd,
  6615. start: start,
  6616. end: end
  6617. };
  6618. },
  6619. // Computes the new date when the user hits the prev button, given the current date
  6620. computePrevDate: function(date) {
  6621. return this.massageCurrentDate(
  6622. date.clone().startOf(this.intervalUnit).subtract(this.intervalDuration), -1
  6623. );
  6624. },
  6625. // Computes the new date when the user hits the next button, given the current date
  6626. computeNextDate: function(date) {
  6627. return this.massageCurrentDate(
  6628. date.clone().startOf(this.intervalUnit).add(this.intervalDuration)
  6629. );
  6630. },
  6631. // Given an arbitrarily calculated current date of the calendar, returns a date that is ensured to be completely
  6632. // visible. `direction` is optional and indicates which direction the current date was being
  6633. // incremented or decremented (1 or -1).
  6634. massageCurrentDate: function(date, direction) {
  6635. if (this.intervalDuration.as('days') <= 1) { // if the view displays a single day or smaller
  6636. if (this.isHiddenDay(date)) {
  6637. date = this.skipHiddenDays(date, direction);
  6638. date.startOf('day');
  6639. }
  6640. }
  6641. return date;
  6642. },
  6643. /* Title and Date Formatting
  6644. ------------------------------------------------------------------------------------------------------------------*/
  6645. // Sets the view's title property to the most updated computed value
  6646. updateTitle: function() {
  6647. this.title = this.computeTitle();
  6648. this.calendar.setToolbarsTitle(this.title);
  6649. },
  6650. // Computes what the title at the top of the calendar should be for this view
  6651. computeTitle: function() {
  6652. var start, end;
  6653. // for views that span a large unit of time, show the proper interval, ignoring stray days before and after
  6654. if (this.intervalUnit === 'year' || this.intervalUnit === 'month') {
  6655. start = this.intervalStart;
  6656. end = this.intervalEnd;
  6657. }
  6658. else { // for day units or smaller, use the actual day range
  6659. start = this.start;
  6660. end = this.end;
  6661. }
  6662. return this.formatRange(
  6663. {
  6664. // in case intervalStart/End has a time, make sure timezone is correct
  6665. start: this.calendar.applyTimezone(start),
  6666. end: this.calendar.applyTimezone(end)
  6667. },
  6668. this.opt('titleFormat') || this.computeTitleFormat(),
  6669. this.opt('titleRangeSeparator')
  6670. );
  6671. },
  6672. // Generates the format string that should be used to generate the title for the current date range.
  6673. // Attempts to compute the most appropriate format if not explicitly specified with `titleFormat`.
  6674. computeTitleFormat: function() {
  6675. if (this.intervalUnit == 'year') {
  6676. return 'YYYY';
  6677. }
  6678. else if (this.intervalUnit == 'month') {
  6679. return this.opt('monthYearFormat'); // like "September 2014"
  6680. }
  6681. else if (this.intervalDuration.as('days') > 1) {
  6682. return 'll'; // multi-day range. shorter, like "Sep 9 - 10 2014"
  6683. }
  6684. else {
  6685. return 'LL'; // one day. longer, like "September 9 2014"
  6686. }
  6687. },
  6688. // Utility for formatting a range. Accepts a range object, formatting string, and optional separator.
  6689. // Displays all-day ranges naturally, with an inclusive end. Takes the current isRTL into account.
  6690. // The timezones of the dates within `range` will be respected.
  6691. formatRange: function(range, formatStr, separator) {
  6692. var end = range.end;
  6693. if (!end.hasTime()) { // all-day?
  6694. end = end.clone().subtract(1); // convert to inclusive. last ms of previous day
  6695. }
  6696. return formatRange(range.start, end, formatStr, separator, this.opt('isRTL'));
  6697. },
  6698. getAllDayHtml: function() {
  6699. return this.opt('allDayHtml') || htmlEscape(this.opt('allDayText'));
  6700. },
  6701. /* Navigation
  6702. ------------------------------------------------------------------------------------------------------------------*/
  6703. // Generates HTML for an anchor to another view into the calendar.
  6704. // Will either generate an <a> tag or a non-clickable <span> tag, depending on enabled settings.
  6705. // `gotoOptions` can either be a moment input, or an object with the form:
  6706. // { date, type, forceOff }
  6707. // `type` is a view-type like "day" or "week". default value is "day".
  6708. // `attrs` and `innerHtml` are use to generate the rest of the HTML tag.
  6709. buildGotoAnchorHtml: function(gotoOptions, attrs, innerHtml) {
  6710. var date, type, forceOff;
  6711. var finalOptions;
  6712. if ($.isPlainObject(gotoOptions)) {
  6713. date = gotoOptions.date;
  6714. type = gotoOptions.type;
  6715. forceOff = gotoOptions.forceOff;
  6716. }
  6717. else {
  6718. date = gotoOptions; // a single moment input
  6719. }
  6720. date = FC.moment(date); // if a string, parse it
  6721. finalOptions = { // for serialization into the link
  6722. date: date.format('YYYY-MM-DD'),
  6723. type: type || 'day'
  6724. };
  6725. if (typeof attrs === 'string') {
  6726. innerHtml = attrs;
  6727. attrs = null;
  6728. }
  6729. attrs = attrs ? ' ' + attrsToStr(attrs) : ''; // will have a leading space
  6730. innerHtml = innerHtml || '';
  6731. if (!forceOff && this.opt('navLinks')) {
  6732. return '<a' + attrs +
  6733. ' data-goto="' + htmlEscape(JSON.stringify(finalOptions)) + '">' +
  6734. innerHtml +
  6735. '</a>';
  6736. }
  6737. else {
  6738. return '<span' + attrs + '>' +
  6739. innerHtml +
  6740. '</span>';
  6741. }
  6742. },
  6743. // Rendering Non-date-related Content
  6744. // -----------------------------------------------------------------------------------------------------------------
  6745. // Sets the container element that the view should render inside of, does global DOM-related initializations,
  6746. // and renders all the non-date-related content inside.
  6747. setElement: function(el) {
  6748. this.el = el;
  6749. this.bindGlobalHandlers();
  6750. this.renderSkeleton();
  6751. },
  6752. // Removes the view's container element from the DOM, clearing any content beforehand.
  6753. // Undoes any other DOM-related attachments.
  6754. removeElement: function() {
  6755. this.unsetDate();
  6756. this.unrenderSkeleton();
  6757. this.unbindGlobalHandlers();
  6758. this.el.remove();
  6759. // NOTE: don't null-out this.el in case the View was destroyed within an API callback.
  6760. // We don't null-out the View's other jQuery element references upon destroy,
  6761. // so we shouldn't kill this.el either.
  6762. },
  6763. // Renders the basic structure of the view before any content is rendered
  6764. renderSkeleton: function() {
  6765. // subclasses should implement
  6766. },
  6767. // Unrenders the basic structure of the view
  6768. unrenderSkeleton: function() {
  6769. // subclasses should implement
  6770. },
  6771. // Date Setting/Unsetting
  6772. // -----------------------------------------------------------------------------------------------------------------
  6773. setDate: function(date) {
  6774. var isReset = this.isDateSet;
  6775. this.isDateSet = true;
  6776. this.handleDate(date, isReset);
  6777. this.trigger(isReset ? 'dateReset' : 'dateSet', date);
  6778. },
  6779. unsetDate: function() {
  6780. if (this.isDateSet) {
  6781. this.isDateSet = false;
  6782. this.handleDateUnset();
  6783. this.trigger('dateUnset');
  6784. }
  6785. },
  6786. // Date Handling
  6787. // -----------------------------------------------------------------------------------------------------------------
  6788. handleDate: function(date, isReset) {
  6789. var _this = this;
  6790. this.unbindEvents(); // will do nothing if not already bound
  6791. this.requestDateRender(date).then(function() {
  6792. // wish we could start earlier, but setRange/computeRange needs to execute first
  6793. _this.bindEvents(); // will request events
  6794. });
  6795. },
  6796. handleDateUnset: function() {
  6797. this.unbindEvents();
  6798. this.requestDateUnrender();
  6799. },
  6800. // Date Render Queuing
  6801. // -----------------------------------------------------------------------------------------------------------------
  6802. // if date not specified, uses current
  6803. requestDateRender: function(date) {
  6804. var _this = this;
  6805. return this.dateRenderQueue.add(function() {
  6806. return _this.executeDateRender(date);
  6807. });
  6808. },
  6809. requestDateUnrender: function() {
  6810. var _this = this;
  6811. return this.dateRenderQueue.add(function() {
  6812. return _this.executeDateUnrender();
  6813. });
  6814. },
  6815. // Date High-level Rendering
  6816. // -----------------------------------------------------------------------------------------------------------------
  6817. // if date not specified, uses current
  6818. executeDateRender: function(date) {
  6819. var _this = this;
  6820. // if rendering a new date, reset scroll to initial state (scrollTime)
  6821. if (date) {
  6822. this.captureInitialScroll();
  6823. }
  6824. else {
  6825. this.captureScroll(); // a rerender of the current date
  6826. }
  6827. this.freezeHeight();
  6828. return this.executeDateUnrender().then(function() {
  6829. if (date) {
  6830. _this.setRange(_this.computeRange(date));
  6831. }
  6832. if (_this.render) {
  6833. _this.render(); // TODO: deprecate
  6834. }
  6835. _this.renderDates();
  6836. _this.updateSize();
  6837. _this.renderBusinessHours(); // might need coordinates, so should go after updateSize()
  6838. _this.startNowIndicator();
  6839. _this.thawHeight();
  6840. _this.releaseScroll();
  6841. _this.isDateRendered = true;
  6842. _this.onDateRender();
  6843. _this.trigger('dateRender');
  6844. });
  6845. },
  6846. executeDateUnrender: function() {
  6847. var _this = this;
  6848. if (_this.isDateRendered) {
  6849. return this.requestEventsUnrender().then(function() {
  6850. _this.unselect();
  6851. _this.stopNowIndicator();
  6852. _this.triggerUnrender();
  6853. _this.unrenderBusinessHours();
  6854. _this.unrenderDates();
  6855. if (_this.destroy) {
  6856. _this.destroy(); // TODO: deprecate
  6857. }
  6858. _this.isDateRendered = false;
  6859. _this.trigger('dateUnrender');
  6860. });
  6861. }
  6862. else {
  6863. return Promise.resolve();
  6864. }
  6865. },
  6866. // Date Rendering Triggers
  6867. // -----------------------------------------------------------------------------------------------------------------
  6868. onDateRender: function() {
  6869. this.triggerRender();
  6870. },
  6871. // Date Low-level Rendering
  6872. // -----------------------------------------------------------------------------------------------------------------
  6873. // date-cell content only
  6874. renderDates: function() {
  6875. // subclasses should implement
  6876. },
  6877. // date-cell content only
  6878. unrenderDates: function() {
  6879. // subclasses should override
  6880. },
  6881. // Misc view rendering utils
  6882. // -------------------------
  6883. // Signals that the view's content has been rendered
  6884. triggerRender: function() {
  6885. this.publiclyTrigger('viewRender', this, this, this.el);
  6886. },
  6887. // Signals that the view's content is about to be unrendered
  6888. triggerUnrender: function() {
  6889. this.publiclyTrigger('viewDestroy', this, this, this.el);
  6890. },
  6891. // Binds DOM handlers to elements that reside outside the view container, such as the document
  6892. bindGlobalHandlers: function() {
  6893. this.listenTo(GlobalEmitter.get(), {
  6894. touchstart: this.processUnselect,
  6895. mousedown: this.handleDocumentMousedown
  6896. });
  6897. },
  6898. // Unbinds DOM handlers from elements that reside outside the view container
  6899. unbindGlobalHandlers: function() {
  6900. this.stopListeningTo(GlobalEmitter.get());
  6901. },
  6902. // Initializes internal variables related to theming
  6903. initThemingProps: function() {
  6904. var tm = this.opt('theme') ? 'ui' : 'fc';
  6905. this.widgetHeaderClass = tm + '-widget-header';
  6906. this.widgetContentClass = tm + '-widget-content';
  6907. this.highlightStateClass = tm + '-state-highlight';
  6908. },
  6909. /* Business Hours
  6910. ------------------------------------------------------------------------------------------------------------------*/
  6911. // Renders business-hours onto the view. Assumes updateSize has already been called.
  6912. renderBusinessHours: function() {
  6913. // subclasses should implement
  6914. },
  6915. // Unrenders previously-rendered business-hours
  6916. unrenderBusinessHours: function() {
  6917. // subclasses should implement
  6918. },
  6919. /* Now Indicator
  6920. ------------------------------------------------------------------------------------------------------------------*/
  6921. // Immediately render the current time indicator and begins re-rendering it at an interval,
  6922. // which is defined by this.getNowIndicatorUnit().
  6923. // TODO: somehow do this for the current whole day's background too
  6924. startNowIndicator: function() {
  6925. var _this = this;
  6926. var unit;
  6927. var update;
  6928. var delay; // ms wait value
  6929. if (this.opt('nowIndicator')) {
  6930. unit = this.getNowIndicatorUnit();
  6931. if (unit) {
  6932. update = proxy(this, 'updateNowIndicator'); // bind to `this`
  6933. this.initialNowDate = this.calendar.getNow();
  6934. this.initialNowQueriedMs = +new Date();
  6935. this.renderNowIndicator(this.initialNowDate);
  6936. this.isNowIndicatorRendered = true;
  6937. // wait until the beginning of the next interval
  6938. delay = this.initialNowDate.clone().startOf(unit).add(1, unit) - this.initialNowDate;
  6939. this.nowIndicatorTimeoutID = setTimeout(function() {
  6940. _this.nowIndicatorTimeoutID = null;
  6941. update();
  6942. delay = +moment.duration(1, unit);
  6943. delay = Math.max(100, delay); // prevent too frequent
  6944. _this.nowIndicatorIntervalID = setInterval(update, delay); // update every interval
  6945. }, delay);
  6946. }
  6947. }
  6948. },
  6949. // rerenders the now indicator, computing the new current time from the amount of time that has passed
  6950. // since the initial getNow call.
  6951. updateNowIndicator: function() {
  6952. if (this.isNowIndicatorRendered) {
  6953. this.unrenderNowIndicator();
  6954. this.renderNowIndicator(
  6955. this.initialNowDate.clone().add(new Date() - this.initialNowQueriedMs) // add ms
  6956. );
  6957. }
  6958. },
  6959. // Immediately unrenders the view's current time indicator and stops any re-rendering timers.
  6960. // Won't cause side effects if indicator isn't rendered.
  6961. stopNowIndicator: function() {
  6962. if (this.isNowIndicatorRendered) {
  6963. if (this.nowIndicatorTimeoutID) {
  6964. clearTimeout(this.nowIndicatorTimeoutID);
  6965. this.nowIndicatorTimeoutID = null;
  6966. }
  6967. if (this.nowIndicatorIntervalID) {
  6968. clearTimeout(this.nowIndicatorIntervalID);
  6969. this.nowIndicatorIntervalID = null;
  6970. }
  6971. this.unrenderNowIndicator();
  6972. this.isNowIndicatorRendered = false;
  6973. }
  6974. },
  6975. // Returns a string unit, like 'second' or 'minute' that defined how often the current time indicator
  6976. // should be refreshed. If something falsy is returned, no time indicator is rendered at all.
  6977. getNowIndicatorUnit: function() {
  6978. // subclasses should implement
  6979. },
  6980. // Renders a current time indicator at the given datetime
  6981. renderNowIndicator: function(date) {
  6982. // subclasses should implement
  6983. },
  6984. // Undoes the rendering actions from renderNowIndicator
  6985. unrenderNowIndicator: function() {
  6986. // subclasses should implement
  6987. },
  6988. /* Dimensions
  6989. ------------------------------------------------------------------------------------------------------------------*/
  6990. // Refreshes anything dependant upon sizing of the container element of the grid
  6991. updateSize: function(isResize) {
  6992. if (isResize) {
  6993. this.captureScroll();
  6994. }
  6995. this.updateHeight(isResize);
  6996. this.updateWidth(isResize);
  6997. this.updateNowIndicator();
  6998. if (isResize) {
  6999. this.releaseScroll();
  7000. }
  7001. },
  7002. // Refreshes the horizontal dimensions of the calendar
  7003. updateWidth: function(isResize) {
  7004. // subclasses should implement
  7005. },
  7006. // Refreshes the vertical dimensions of the calendar
  7007. updateHeight: function(isResize) {
  7008. var calendar = this.calendar; // we poll the calendar for height information
  7009. this.setHeight(
  7010. calendar.getSuggestedViewHeight(),
  7011. calendar.isHeightAuto()
  7012. );
  7013. },
  7014. // Updates the vertical dimensions of the calendar to the specified height.
  7015. // if `isAuto` is set to true, height becomes merely a suggestion and the view should use its "natural" height.
  7016. setHeight: function(height, isAuto) {
  7017. // subclasses should implement
  7018. },
  7019. /* Scroller
  7020. ------------------------------------------------------------------------------------------------------------------*/
  7021. capturedScroll: null,
  7022. capturedScrollDepth: 0,
  7023. captureScroll: function() {
  7024. if (!(this.capturedScrollDepth++)) {
  7025. this.capturedScroll = this.isDateRendered ? this.queryScroll() : {}; // require a render first
  7026. return true; // root?
  7027. }
  7028. return false;
  7029. },
  7030. captureInitialScroll: function(forcedScroll) {
  7031. if (this.captureScroll()) { // root?
  7032. this.capturedScroll.isInitial = true;
  7033. if (forcedScroll) {
  7034. $.extend(this.capturedScroll, forcedScroll);
  7035. }
  7036. else {
  7037. this.capturedScroll.isComputed = true;
  7038. }
  7039. }
  7040. },
  7041. releaseScroll: function() {
  7042. var scroll = this.capturedScroll;
  7043. var isRoot = this.discardScroll();
  7044. if (scroll.isComputed) {
  7045. if (isRoot) {
  7046. // only compute initial scroll if it will actually be used (is the root capture)
  7047. $.extend(scroll, this.computeInitialScroll());
  7048. }
  7049. else {
  7050. scroll = null; // scroll couldn't be computed. don't apply it to the DOM
  7051. }
  7052. }
  7053. if (scroll) {
  7054. // we act immediately on a releaseScroll operation, as opposed to captureScroll.
  7055. // if capture/release wraps a render operation that screws up the scroll,
  7056. // we still want to restore it a good state after, regardless of depth.
  7057. if (scroll.isInitial) {
  7058. this.hardSetScroll(scroll); // outsmart how browsers set scroll on initial DOM
  7059. }
  7060. else {
  7061. this.setScroll(scroll);
  7062. }
  7063. }
  7064. },
  7065. discardScroll: function() {
  7066. if (!(--this.capturedScrollDepth)) {
  7067. this.capturedScroll = null;
  7068. return true; // root?
  7069. }
  7070. return false;
  7071. },
  7072. computeInitialScroll: function() {
  7073. return {};
  7074. },
  7075. queryScroll: function() {
  7076. return {};
  7077. },
  7078. hardSetScroll: function(scroll) {
  7079. var _this = this;
  7080. var exec = function() { _this.setScroll(scroll); };
  7081. exec();
  7082. setTimeout(exec, 0); // to surely clear the browser's initial scroll for the DOM
  7083. },
  7084. setScroll: function(scroll) {
  7085. },
  7086. /* Height Freezing
  7087. ------------------------------------------------------------------------------------------------------------------*/
  7088. freezeHeight: function() {
  7089. this.calendar.freezeContentHeight();
  7090. },
  7091. thawHeight: function() {
  7092. this.calendar.thawContentHeight();
  7093. },
  7094. // Event Binding/Unbinding
  7095. // -----------------------------------------------------------------------------------------------------------------
  7096. bindEvents: function() {
  7097. var _this = this;
  7098. if (!this.isEventsBound) {
  7099. this.isEventsBound = true;
  7100. this.rejectOn('eventsUnbind', this.requestEvents()).then(function(events) { // TODO: test rejection
  7101. _this.listenTo(_this.calendar, 'eventsReset', _this.setEvents);
  7102. _this.setEvents(events);
  7103. });
  7104. }
  7105. },
  7106. unbindEvents: function() {
  7107. if (this.isEventsBound) {
  7108. this.isEventsBound = false;
  7109. this.stopListeningTo(this.calendar, 'eventsReset');
  7110. this.unsetEvents();
  7111. this.trigger('eventsUnbind');
  7112. }
  7113. },
  7114. // Event Setting/Unsetting
  7115. // -----------------------------------------------------------------------------------------------------------------
  7116. setEvents: function(events) {
  7117. var isReset = this.isEventSet;
  7118. this.isEventsSet = true;
  7119. this.handleEvents(events, isReset);
  7120. this.trigger(isReset ? 'eventsReset' : 'eventsSet', events);
  7121. },
  7122. unsetEvents: function() {
  7123. if (this.isEventsSet) {
  7124. this.isEventsSet = false;
  7125. this.handleEventsUnset();
  7126. this.trigger('eventsUnset');
  7127. }
  7128. },
  7129. whenEventsSet: function() {
  7130. var _this = this;
  7131. if (this.isEventsSet) {
  7132. return Promise.resolve(this.getCurrentEvents());
  7133. }
  7134. else {
  7135. return new Promise(function(resolve) {
  7136. _this.one('eventsSet', resolve);
  7137. });
  7138. }
  7139. },
  7140. // Event Handling
  7141. // -----------------------------------------------------------------------------------------------------------------
  7142. handleEvents: function(events, isReset) {
  7143. this.requestEventsRender(events);
  7144. },
  7145. handleEventsUnset: function() {
  7146. this.requestEventsUnrender();
  7147. },
  7148. // Event Render Queuing
  7149. // -----------------------------------------------------------------------------------------------------------------
  7150. // assumes any previous event renders have been cleared already
  7151. requestEventsRender: function(events) {
  7152. var _this = this;
  7153. return this.eventRenderQueue.add(function() { // might not return a promise if debounced!? bad
  7154. return _this.executeEventsRender(events);
  7155. });
  7156. },
  7157. requestEventsUnrender: function() {
  7158. var _this = this;
  7159. if (this.isEventsRendered) {
  7160. return this.eventRenderQueue.addQuickly(function() {
  7161. return _this.executeEventsUnrender();
  7162. });
  7163. }
  7164. else {
  7165. return Promise.resolve();
  7166. }
  7167. },
  7168. requestCurrentEventsRender: function() {
  7169. if (this.isEventsSet) {
  7170. this.requestEventsRender(this.getCurrentEvents());
  7171. }
  7172. else {
  7173. return Promise.reject();
  7174. }
  7175. },
  7176. // Event High-level Rendering
  7177. // -----------------------------------------------------------------------------------------------------------------
  7178. executeEventsRender: function(events) {
  7179. var _this = this;
  7180. this.captureScroll();
  7181. this.freezeHeight();
  7182. return this.executeEventsUnrender().then(function() {
  7183. _this.renderEvents(events);
  7184. _this.thawHeight();
  7185. _this.releaseScroll();
  7186. _this.isEventsRendered = true;
  7187. _this.onEventsRender();
  7188. _this.trigger('eventsRender');
  7189. });
  7190. },
  7191. executeEventsUnrender: function() {
  7192. if (this.isEventsRendered) {
  7193. this.onBeforeEventsUnrender();
  7194. this.captureScroll();
  7195. this.freezeHeight();
  7196. if (this.destroyEvents) {
  7197. this.destroyEvents(); // TODO: deprecate
  7198. }
  7199. this.unrenderEvents();
  7200. this.thawHeight();
  7201. this.releaseScroll();
  7202. this.isEventsRendered = false;
  7203. this.trigger('eventsUnrender');
  7204. }
  7205. return Promise.resolve(); // always synchronous
  7206. },
  7207. // Event Rendering Triggers
  7208. // -----------------------------------------------------------------------------------------------------------------
  7209. // Signals that all events have been rendered
  7210. onEventsRender: function() {
  7211. this.renderedEventSegEach(function(seg) {
  7212. this.publiclyTrigger('eventAfterRender', seg.event, seg.event, seg.el);
  7213. });
  7214. this.publiclyTrigger('eventAfterAllRender');
  7215. },
  7216. // Signals that all event elements are about to be removed
  7217. onBeforeEventsUnrender: function() {
  7218. this.renderedEventSegEach(function(seg) {
  7219. this.publiclyTrigger('eventDestroy', seg.event, seg.event, seg.el);
  7220. });
  7221. },
  7222. // Event Low-level Rendering
  7223. // -----------------------------------------------------------------------------------------------------------------
  7224. // Renders the events onto the view.
  7225. renderEvents: function(events) {
  7226. // subclasses should implement
  7227. },
  7228. // Removes event elements from the view.
  7229. unrenderEvents: function() {
  7230. // subclasses should implement
  7231. },
  7232. // Event Data Access
  7233. // -----------------------------------------------------------------------------------------------------------------
  7234. requestEvents: function() {
  7235. return this.calendar.requestEvents(this.start, this.end);
  7236. },
  7237. getCurrentEvents: function() {
  7238. return this.calendar.getPrunedEventCache();
  7239. },
  7240. // Event Rendering Utils
  7241. // -----------------------------------------------------------------------------------------------------------------
  7242. // Given an event and the default element used for rendering, returns the element that should actually be used.
  7243. // Basically runs events and elements through the eventRender hook.
  7244. resolveEventEl: function(event, el) {
  7245. var custom = this.publiclyTrigger('eventRender', event, event, el);
  7246. if (custom === false) { // means don't render at all
  7247. el = null;
  7248. }
  7249. else if (custom && custom !== true) {
  7250. el = $(custom);
  7251. }
  7252. return el;
  7253. },
  7254. // Hides all rendered event segments linked to the given event
  7255. showEvent: function(event) {
  7256. this.renderedEventSegEach(function(seg) {
  7257. seg.el.css('visibility', '');
  7258. }, event);
  7259. },
  7260. // Shows all rendered event segments linked to the given event
  7261. hideEvent: function(event) {
  7262. this.renderedEventSegEach(function(seg) {
  7263. seg.el.css('visibility', 'hidden');
  7264. }, event);
  7265. },
  7266. // Iterates through event segments that have been rendered (have an el). Goes through all by default.
  7267. // If the optional `event` argument is specified, only iterates through segments linked to that event.
  7268. // The `this` value of the callback function will be the view.
  7269. renderedEventSegEach: function(func, event) {
  7270. var segs = this.getEventSegs();
  7271. var i;
  7272. for (i = 0; i < segs.length; i++) {
  7273. if (!event || segs[i].event._id === event._id) {
  7274. if (segs[i].el) {
  7275. func.call(this, segs[i]);
  7276. }
  7277. }
  7278. }
  7279. },
  7280. // Retrieves all the rendered segment objects for the view
  7281. getEventSegs: function() {
  7282. // subclasses must implement
  7283. return [];
  7284. },
  7285. /* Event Drag-n-Drop
  7286. ------------------------------------------------------------------------------------------------------------------*/
  7287. // Computes if the given event is allowed to be dragged by the user
  7288. isEventDraggable: function(event) {
  7289. return this.isEventStartEditable(event);
  7290. },
  7291. isEventStartEditable: function(event) {
  7292. return firstDefined(
  7293. event.startEditable,
  7294. (event.source || {}).startEditable,
  7295. this.opt('eventStartEditable'),
  7296. this.isEventGenerallyEditable(event)
  7297. );
  7298. },
  7299. isEventGenerallyEditable: function(event) {
  7300. return firstDefined(
  7301. event.editable,
  7302. (event.source || {}).editable,
  7303. this.opt('editable')
  7304. );
  7305. },
  7306. // Must be called when an event in the view is dropped onto new location.
  7307. // `dropLocation` is an object that contains the new zoned start/end/allDay values for the event.
  7308. reportSegDrop: function(seg, dropLocation, largeUnit, el, ev) {
  7309. var calendar = this.calendar;
  7310. var mutateResult = calendar.mutateSeg(seg, dropLocation, largeUnit);
  7311. var undoFunc = function() {
  7312. mutateResult.undo();
  7313. calendar.reportEventChange();
  7314. };
  7315. this.triggerEventDrop(seg.event, mutateResult.dateDelta, undoFunc, el, ev);
  7316. calendar.reportEventChange(); // will rerender events
  7317. },
  7318. // Triggers event-drop handlers that have subscribed via the API
  7319. triggerEventDrop: function(event, dateDelta, undoFunc, el, ev) {
  7320. this.publiclyTrigger('eventDrop', el[0], event, dateDelta, undoFunc, ev, {}); // {} = jqui dummy
  7321. },
  7322. /* External Element Drag-n-Drop
  7323. ------------------------------------------------------------------------------------------------------------------*/
  7324. // Must be called when an external element, via jQuery UI, has been dropped onto the calendar.
  7325. // `meta` is the parsed data that has been embedded into the dragging event.
  7326. // `dropLocation` is an object that contains the new zoned start/end/allDay values for the event.
  7327. reportExternalDrop: function(meta, dropLocation, el, ev, ui) {
  7328. var eventProps = meta.eventProps;
  7329. var eventInput;
  7330. var event;
  7331. // Try to build an event object and render it. TODO: decouple the two
  7332. if (eventProps) {
  7333. eventInput = $.extend({}, eventProps, dropLocation);
  7334. event = this.calendar.renderEvent(eventInput, meta.stick)[0]; // renderEvent returns an array
  7335. }
  7336. this.triggerExternalDrop(event, dropLocation, el, ev, ui);
  7337. },
  7338. // Triggers external-drop handlers that have subscribed via the API
  7339. triggerExternalDrop: function(event, dropLocation, el, ev, ui) {
  7340. // trigger 'drop' regardless of whether element represents an event
  7341. this.publiclyTrigger('drop', el[0], dropLocation.start, ev, ui);
  7342. if (event) {
  7343. this.publiclyTrigger('eventReceive', null, event); // signal an external event landed
  7344. }
  7345. },
  7346. /* Drag-n-Drop Rendering (for both events and external elements)
  7347. ------------------------------------------------------------------------------------------------------------------*/
  7348. // Renders a visual indication of a event or external-element drag over the given drop zone.
  7349. // If an external-element, seg will be `null`.
  7350. // Must return elements used for any mock events.
  7351. renderDrag: function(dropLocation, seg) {
  7352. // subclasses must implement
  7353. },
  7354. // Unrenders a visual indication of an event or external-element being dragged.
  7355. unrenderDrag: function() {
  7356. // subclasses must implement
  7357. },
  7358. /* Event Resizing
  7359. ------------------------------------------------------------------------------------------------------------------*/
  7360. // Computes if the given event is allowed to be resized from its starting edge
  7361. isEventResizableFromStart: function(event) {
  7362. return this.opt('eventResizableFromStart') && this.isEventResizable(event);
  7363. },
  7364. // Computes if the given event is allowed to be resized from its ending edge
  7365. isEventResizableFromEnd: function(event) {
  7366. return this.isEventResizable(event);
  7367. },
  7368. // Computes if the given event is allowed to be resized by the user at all
  7369. isEventResizable: function(event) {
  7370. var source = event.source || {};
  7371. return firstDefined(
  7372. event.durationEditable,
  7373. source.durationEditable,
  7374. this.opt('eventDurationEditable'),
  7375. event.editable,
  7376. source.editable,
  7377. this.opt('editable')
  7378. );
  7379. },
  7380. // Must be called when an event in the view has been resized to a new length
  7381. reportSegResize: function(seg, resizeLocation, largeUnit, el, ev) {
  7382. var calendar = this.calendar;
  7383. var mutateResult = calendar.mutateSeg(seg, resizeLocation, largeUnit);
  7384. var undoFunc = function() {
  7385. mutateResult.undo();
  7386. calendar.reportEventChange();
  7387. };
  7388. this.triggerEventResize(seg.event, mutateResult.durationDelta, undoFunc, el, ev);
  7389. calendar.reportEventChange(); // will rerender events
  7390. },
  7391. // Triggers event-resize handlers that have subscribed via the API
  7392. triggerEventResize: function(event, durationDelta, undoFunc, el, ev) {
  7393. this.publiclyTrigger('eventResize', el[0], event, durationDelta, undoFunc, ev, {}); // {} = jqui dummy
  7394. },
  7395. /* Selection (time range)
  7396. ------------------------------------------------------------------------------------------------------------------*/
  7397. // Selects a date span on the view. `start` and `end` are both Moments.
  7398. // `ev` is the native mouse event that begin the interaction.
  7399. select: function(span, ev) {
  7400. this.unselect(ev);
  7401. this.renderSelection(span);
  7402. this.reportSelection(span, ev);
  7403. },
  7404. // Renders a visual indication of the selection
  7405. renderSelection: function(span) {
  7406. // subclasses should implement
  7407. },
  7408. // Called when a new selection is made. Updates internal state and triggers handlers.
  7409. reportSelection: function(span, ev) {
  7410. this.isSelected = true;
  7411. this.triggerSelect(span, ev);
  7412. },
  7413. // Triggers handlers to 'select'
  7414. triggerSelect: function(span, ev) {
  7415. this.publiclyTrigger(
  7416. 'select',
  7417. null,
  7418. this.calendar.applyTimezone(span.start), // convert to calendar's tz for external API
  7419. this.calendar.applyTimezone(span.end), // "
  7420. ev
  7421. );
  7422. },
  7423. // Undoes a selection. updates in the internal state and triggers handlers.
  7424. // `ev` is the native mouse event that began the interaction.
  7425. unselect: function(ev) {
  7426. if (this.isSelected) {
  7427. this.isSelected = false;
  7428. if (this.destroySelection) {
  7429. this.destroySelection(); // TODO: deprecate
  7430. }
  7431. this.unrenderSelection();
  7432. this.publiclyTrigger('unselect', null, ev);
  7433. }
  7434. },
  7435. // Unrenders a visual indication of selection
  7436. unrenderSelection: function() {
  7437. // subclasses should implement
  7438. },
  7439. /* Event Selection
  7440. ------------------------------------------------------------------------------------------------------------------*/
  7441. selectEvent: function(event) {
  7442. if (!this.selectedEvent || this.selectedEvent !== event) {
  7443. this.unselectEvent();
  7444. this.renderedEventSegEach(function(seg) {
  7445. seg.el.addClass('fc-selected');
  7446. }, event);
  7447. this.selectedEvent = event;
  7448. }
  7449. },
  7450. unselectEvent: function() {
  7451. if (this.selectedEvent) {
  7452. this.renderedEventSegEach(function(seg) {
  7453. seg.el.removeClass('fc-selected');
  7454. }, this.selectedEvent);
  7455. this.selectedEvent = null;
  7456. }
  7457. },
  7458. isEventSelected: function(event) {
  7459. // event references might change on refetchEvents(), while selectedEvent doesn't,
  7460. // so compare IDs
  7461. return this.selectedEvent && this.selectedEvent._id === event._id;
  7462. },
  7463. /* Mouse / Touch Unselecting (time range & event unselection)
  7464. ------------------------------------------------------------------------------------------------------------------*/
  7465. // TODO: move consistently to down/start or up/end?
  7466. // TODO: don't kill previous selection if touch scrolling
  7467. handleDocumentMousedown: function(ev) {
  7468. if (isPrimaryMouseButton(ev)) {
  7469. this.processUnselect(ev);
  7470. }
  7471. },
  7472. processUnselect: function(ev) {
  7473. this.processRangeUnselect(ev);
  7474. this.processEventUnselect(ev);
  7475. },
  7476. processRangeUnselect: function(ev) {
  7477. var ignore;
  7478. // is there a time-range selection?
  7479. if (this.isSelected && this.opt('unselectAuto')) {
  7480. // only unselect if the clicked element is not identical to or inside of an 'unselectCancel' element
  7481. ignore = this.opt('unselectCancel');
  7482. if (!ignore || !$(ev.target).closest(ignore).length) {
  7483. this.unselect(ev);
  7484. }
  7485. }
  7486. },
  7487. processEventUnselect: function(ev) {
  7488. if (this.selectedEvent) {
  7489. if (!$(ev.target).closest('.fc-selected').length) {
  7490. this.unselectEvent();
  7491. }
  7492. }
  7493. },
  7494. /* Day Click
  7495. ------------------------------------------------------------------------------------------------------------------*/
  7496. // Triggers handlers to 'dayClick'
  7497. // Span has start/end of the clicked area. Only the start is useful.
  7498. triggerDayClick: function(span, dayEl, ev) {
  7499. this.publiclyTrigger(
  7500. 'dayClick',
  7501. dayEl,
  7502. this.calendar.applyTimezone(span.start), // convert to calendar's timezone for external API
  7503. ev
  7504. );
  7505. },
  7506. /* Date Utils
  7507. ------------------------------------------------------------------------------------------------------------------*/
  7508. // Initializes internal variables related to calculating hidden days-of-week
  7509. initHiddenDays: function() {
  7510. var hiddenDays = this.opt('hiddenDays') || []; // array of day-of-week indices that are hidden
  7511. var isHiddenDayHash = []; // is the day-of-week hidden? (hash with day-of-week-index -> bool)
  7512. var dayCnt = 0;
  7513. var i;
  7514. if (this.opt('weekends') === false) {
  7515. hiddenDays.push(0, 6); // 0=sunday, 6=saturday
  7516. }
  7517. for (i = 0; i < 7; i++) {
  7518. if (
  7519. !(isHiddenDayHash[i] = $.inArray(i, hiddenDays) !== -1)
  7520. ) {
  7521. dayCnt++;
  7522. }
  7523. }
  7524. if (!dayCnt) {
  7525. throw 'invalid hiddenDays'; // all days were hidden? bad.
  7526. }
  7527. this.isHiddenDayHash = isHiddenDayHash;
  7528. },
  7529. // Is the current day hidden?
  7530. // `day` is a day-of-week index (0-6), or a Moment
  7531. isHiddenDay: function(day) {
  7532. if (moment.isMoment(day)) {
  7533. day = day.day();
  7534. }
  7535. return this.isHiddenDayHash[day];
  7536. },
  7537. // Incrementing the current day until it is no longer a hidden day, returning a copy.
  7538. // If the initial value of `date` is not a hidden day, don't do anything.
  7539. // Pass `isExclusive` as `true` if you are dealing with an end date.
  7540. // `inc` defaults to `1` (increment one day forward each time)
  7541. skipHiddenDays: function(date, inc, isExclusive) {
  7542. var out = date.clone();
  7543. inc = inc || 1;
  7544. while (
  7545. this.isHiddenDayHash[(out.day() + (isExclusive ? inc : 0) + 7) % 7]
  7546. ) {
  7547. out.add(inc, 'days');
  7548. }
  7549. return out;
  7550. },
  7551. // Returns the date range of the full days the given range visually appears to occupy.
  7552. // Returns a new range object.
  7553. computeDayRange: function(range) {
  7554. var startDay = range.start.clone().stripTime(); // the beginning of the day the range starts
  7555. var end = range.end;
  7556. var endDay = null;
  7557. var endTimeMS;
  7558. if (end) {
  7559. endDay = end.clone().stripTime(); // the beginning of the day the range exclusively ends
  7560. endTimeMS = +end.time(); // # of milliseconds into `endDay`
  7561. // If the end time is actually inclusively part of the next day and is equal to or
  7562. // beyond the next day threshold, adjust the end to be the exclusive end of `endDay`.
  7563. // Otherwise, leaving it as inclusive will cause it to exclude `endDay`.
  7564. if (endTimeMS && endTimeMS >= this.nextDayThreshold) {
  7565. endDay.add(1, 'days');
  7566. }
  7567. }
  7568. // If no end was specified, or if it is within `startDay` but not past nextDayThreshold,
  7569. // assign the default duration of one day.
  7570. if (!end || endDay <= startDay) {
  7571. endDay = startDay.clone().add(1, 'days');
  7572. }
  7573. return { start: startDay, end: endDay };
  7574. },
  7575. // Does the given event visually appear to occupy more than one day?
  7576. isMultiDayEvent: function(event) {
  7577. var range = this.computeDayRange(event); // event is range-ish
  7578. return range.end.diff(range.start, 'days') > 1;
  7579. }
  7580. });
  7581. ;;
  7582. /*
  7583. Embodies a div that has potential scrollbars
  7584. */
  7585. var Scroller = FC.Scroller = Class.extend({
  7586. el: null, // the guaranteed outer element
  7587. scrollEl: null, // the element with the scrollbars
  7588. overflowX: null,
  7589. overflowY: null,
  7590. constructor: function(options) {
  7591. options = options || {};
  7592. this.overflowX = options.overflowX || options.overflow || 'auto';
  7593. this.overflowY = options.overflowY || options.overflow || 'auto';
  7594. },
  7595. render: function() {
  7596. this.el = this.renderEl();
  7597. this.applyOverflow();
  7598. },
  7599. renderEl: function() {
  7600. return (this.scrollEl = $('<div style="ovnerflow:auto !important" class="fc-scroller"></div>'));
  7601. },
  7602. // sets to natural height, unlocks overflow
  7603. clear: function() {
  7604. this.setHeight('auto');
  7605. this.applyOverflow();
  7606. },
  7607. destroy: function() {
  7608. this.el.remove();
  7609. },
  7610. // Overflow
  7611. // -----------------------------------------------------------------------------------------------------------------
  7612. applyOverflow: function() {
  7613. this.scrollEl.css({
  7614. 'overflow-x': this.overflowX,
  7615. 'overflow-y': this.overflowY
  7616. });
  7617. },
  7618. // Causes any 'auto' overflow values to resolves to 'scroll' or 'hidden'.
  7619. // Useful for preserving scrollbar widths regardless of future resizes.
  7620. // Can pass in scrollbarWidths for optimization.
  7621. lockOverflow: function(scrollbarWidths) {
  7622. var overflowX = this.overflowX;
  7623. var overflowY = this.overflowY;
  7624. scrollbarWidths = scrollbarWidths || this.getScrollbarWidths();
  7625. if (overflowX === 'auto') {
  7626. overflowX = (
  7627. scrollbarWidths.top || scrollbarWidths.bottom || // horizontal scrollbars?
  7628. // OR scrolling pane with massless scrollbars?
  7629. this.scrollEl[0].scrollWidth - 1 > this.scrollEl[0].clientWidth
  7630. // subtract 1 because of IE off-by-one issue
  7631. ) ? 'scroll' : 'hidden';
  7632. }
  7633. if (overflowY === 'auto') {
  7634. overflowY = (
  7635. scrollbarWidths.left || scrollbarWidths.right || // vertical scrollbars?
  7636. // OR scrolling pane with massless scrollbars?
  7637. this.scrollEl[0].scrollHeight - 1 > this.scrollEl[0].clientHeight
  7638. // subtract 1 because of IE off-by-one issue
  7639. ) ? 'scroll' : 'hidden';
  7640. }
  7641. this.scrollEl.css({ 'overflow-x': overflowX, 'overflow-y': overflowY });
  7642. },
  7643. // Getters / Setters
  7644. // -----------------------------------------------------------------------------------------------------------------
  7645. setHeight: function(height) {
  7646. this.scrollEl.height(height);
  7647. },
  7648. getScrollTop: function() {
  7649. return this.scrollEl.scrollTop();
  7650. },
  7651. setScrollTop: function(top) {
  7652. this.scrollEl.scrollTop(top);
  7653. },
  7654. getClientWidth: function() {
  7655. return this.scrollEl[0].clientWidth;
  7656. },
  7657. getClientHeight: function() {
  7658. return this.scrollEl[0].clientHeight;
  7659. },
  7660. getScrollbarWidths: function() {
  7661. return getScrollbarWidths(this.scrollEl);
  7662. }
  7663. });
  7664. ;;
  7665. function Iterator(items) {
  7666. this.items = items || [];
  7667. }
  7668. /* Calls a method on every item passing the arguments through */
  7669. Iterator.prototype.proxyCall = function(methodName) {
  7670. var args = Array.prototype.slice.call(arguments, 1);
  7671. var results = [];
  7672. this.items.forEach(function(item) {
  7673. results.push(item[methodName].apply(item, args));
  7674. });
  7675. return results;
  7676. };
  7677. ;;
  7678. /* Toolbar with buttons and title
  7679. ----------------------------------------------------------------------------------------------------------------------*/
  7680. function Toolbar(calendar, toolbarOptions) {
  7681. var t = this;
  7682. // exports
  7683. t.setToolbarOptions = setToolbarOptions;
  7684. t.render = render;
  7685. t.removeElement = removeElement;
  7686. t.updateTitle = updateTitle;
  7687. t.activateButton = activateButton;
  7688. t.deactivateButton = deactivateButton;
  7689. t.disableButton = disableButton;
  7690. t.enableButton = enableButton;
  7691. t.getViewsWithButtons = getViewsWithButtons;
  7692. t.el = null; // mirrors local `el`
  7693. // locals
  7694. var el;
  7695. var viewsWithButtons = [];
  7696. var tm;
  7697. // method to update toolbar-specific options, not calendar-wide options
  7698. function setToolbarOptions(newToolbarOptions) {
  7699. toolbarOptions = newToolbarOptions;
  7700. }
  7701. // can be called repeatedly and will rerender
  7702. function render() {
  7703. var sections = toolbarOptions.layout;
  7704. tm = calendar.options.theme ? 'ui' : 'fc';
  7705. if (sections) {
  7706. if (!el) {
  7707. el = this.el = $("<div class='fc-toolbar "+ toolbarOptions.extraClasses + "'/>");
  7708. }
  7709. else {
  7710. el.empty();
  7711. }
  7712. el.append(renderSection('left'))
  7713. .append(renderSection('right'))
  7714. .append(renderSection('center'))
  7715. .append('<div class="fc-clear"/>');
  7716. }
  7717. else {
  7718. removeElement();
  7719. }
  7720. }
  7721. function removeElement() {
  7722. if (el) {
  7723. el.remove();
  7724. el = t.el = null;
  7725. }
  7726. }
  7727. function renderSection(position) {
  7728. var sectionEl = $('<div class="fc-' + position + '"/>');
  7729. var buttonStr = toolbarOptions.layout[position];
  7730. if (buttonStr) {
  7731. $.each(buttonStr.split(' '), function(i) {
  7732. var groupChildren = $();
  7733. var isOnlyButtons = true;
  7734. var groupEl;
  7735. $.each(this.split(','), function(j, buttonName) {
  7736. var customButtonProps;
  7737. var viewSpec;
  7738. var buttonClick;
  7739. var overrideText; // text explicitly set by calendar's constructor options. overcomes icons
  7740. var defaultText;
  7741. var themeIcon;
  7742. var normalIcon;
  7743. var innerHtml;
  7744. var classes;
  7745. var button; // the element
  7746. if (buttonName == 'title') {
  7747. groupChildren = groupChildren.add($('<h2>&nbsp;</h2>')); // we always want it to take up height
  7748. isOnlyButtons = false;
  7749. }
  7750. else {
  7751. if ((customButtonProps = (calendar.options.customButtons || {})[buttonName])) {
  7752. buttonClick = function(ev) {
  7753. if (customButtonProps.click) {
  7754. customButtonProps.click.call(button[0], ev);
  7755. }
  7756. };
  7757. overrideText = ''; // icons will override text
  7758. defaultText = customButtonProps.text;
  7759. }
  7760. else if ((viewSpec = calendar.getViewSpec(buttonName))) {
  7761. buttonClick = function() {
  7762. calendar.changeView(buttonName);
  7763. };
  7764. viewsWithButtons.push(buttonName);
  7765. overrideText = viewSpec.buttonTextOverride;
  7766. defaultText = viewSpec.buttonTextDefault;
  7767. }
  7768. else if (calendar[buttonName]) { // a calendar method
  7769. buttonClick = function() {
  7770. calendar[buttonName]();
  7771. };
  7772. overrideText = (calendar.overrides.buttonText || {})[buttonName];
  7773. defaultText = calendar.options.buttonText[buttonName]; // everything else is considered default
  7774. }
  7775. if (buttonClick) {
  7776. themeIcon =
  7777. customButtonProps ?
  7778. customButtonProps.themeIcon :
  7779. calendar.options.themeButtonIcons[buttonName];
  7780. normalIcon =
  7781. customButtonProps ?
  7782. customButtonProps.icon :
  7783. calendar.options.buttonIcons[buttonName];
  7784. if (overrideText) {
  7785. innerHtml = htmlEscape(overrideText);
  7786. }
  7787. else if (themeIcon && calendar.options.theme) {
  7788. innerHtml = "<span class='ui-icon ui-icon-" + themeIcon + "'></span>";
  7789. }
  7790. else if (normalIcon && !calendar.options.theme) {
  7791. innerHtml = "<span class='fc-icon fc-icon-" + normalIcon + "'></span>";
  7792. }
  7793. else {
  7794. innerHtml = htmlEscape(defaultText);
  7795. }
  7796. classes = [
  7797. 'fc-' + buttonName + '-button',
  7798. tm + '-button',
  7799. tm + '-state-default'
  7800. ];
  7801. button = $( // type="button" so that it doesn't submit a form
  7802. '<button type="button" class="' + classes.join(' ') + '">' +
  7803. innerHtml +
  7804. '</button>'
  7805. )
  7806. .click(function(ev) {
  7807. // don't process clicks for disabled buttons
  7808. if (!button.hasClass(tm + '-state-disabled')) {
  7809. buttonClick(ev);
  7810. // after the click action, if the button becomes the "active" tab, or disabled,
  7811. // it should never have a hover class, so remove it now.
  7812. if (
  7813. button.hasClass(tm + '-state-active') ||
  7814. button.hasClass(tm + '-state-disabled')
  7815. ) {
  7816. button.removeClass(tm + '-state-hover');
  7817. }
  7818. }
  7819. })
  7820. .mousedown(function() {
  7821. // the *down* effect (mouse pressed in).
  7822. // only on buttons that are not the "active" tab, or disabled
  7823. button
  7824. .not('.' + tm + '-state-active')
  7825. .not('.' + tm + '-state-disabled')
  7826. .addClass(tm + '-state-down');
  7827. })
  7828. .mouseup(function() {
  7829. // undo the *down* effect
  7830. button.removeClass(tm + '-state-down');
  7831. })
  7832. .hover(
  7833. function() {
  7834. // the *hover* effect.
  7835. // only on buttons that are not the "active" tab, or disabled
  7836. button
  7837. .not('.' + tm + '-state-active')
  7838. .not('.' + tm + '-state-disabled')
  7839. .addClass(tm + '-state-hover');
  7840. },
  7841. function() {
  7842. // undo the *hover* effect
  7843. button
  7844. .removeClass(tm + '-state-hover')
  7845. .removeClass(tm + '-state-down'); // if mouseleave happens before mouseup
  7846. }
  7847. );
  7848. groupChildren = groupChildren.add(button);
  7849. }
  7850. }
  7851. });
  7852. if (isOnlyButtons) {
  7853. groupChildren
  7854. .first().addClass(tm + '-corner-left').end()
  7855. .last().addClass(tm + '-corner-right').end();
  7856. }
  7857. if (groupChildren.length > 1) {
  7858. groupEl = $('<div/>');
  7859. if (isOnlyButtons) {
  7860. groupEl.addClass('fc-button-group');
  7861. }
  7862. groupEl.append(groupChildren);
  7863. sectionEl.append(groupEl);
  7864. }
  7865. else {
  7866. sectionEl.append(groupChildren); // 1 or 0 children
  7867. }
  7868. });
  7869. }
  7870. return sectionEl;
  7871. }
  7872. function updateTitle(text) {
  7873. if (el) {
  7874. el.find('h2').text(text);
  7875. }
  7876. }
  7877. function activateButton(buttonName) {
  7878. if (el) {
  7879. el.find('.fc-' + buttonName + '-button')
  7880. .addClass(tm + '-state-active');
  7881. }
  7882. }
  7883. function deactivateButton(buttonName) {
  7884. if (el) {
  7885. el.find('.fc-' + buttonName + '-button')
  7886. .removeClass(tm + '-state-active');
  7887. }
  7888. }
  7889. function disableButton(buttonName) {
  7890. if (el) {
  7891. el.find('.fc-' + buttonName + '-button')
  7892. .prop('disabled', true)
  7893. .addClass(tm + '-state-disabled');
  7894. }
  7895. }
  7896. function enableButton(buttonName) {
  7897. if (el) {
  7898. el.find('.fc-' + buttonName + '-button')
  7899. .prop('disabled', false)
  7900. .removeClass(tm + '-state-disabled');
  7901. }
  7902. }
  7903. function getViewsWithButtons() {
  7904. return viewsWithButtons;
  7905. }
  7906. }
  7907. ;;
  7908. var Calendar = FC.Calendar = Class.extend({
  7909. dirDefaults: null, // option defaults related to LTR or RTL
  7910. localeDefaults: null, // option defaults related to current locale
  7911. overrides: null, // option overrides given to the fullCalendar constructor
  7912. dynamicOverrides: null, // options set with dynamic setter method. higher precedence than view overrides.
  7913. options: null, // all defaults combined with overrides
  7914. viewSpecCache: null, // cache of view definitions
  7915. view: null, // current View object
  7916. header: null,
  7917. footer: null,
  7918. loadingLevel: 0, // number of simultaneous loading tasks
  7919. // a lot of this class' OOP logic is scoped within this constructor function,
  7920. // but in the future, write individual methods on the prototype.
  7921. constructor: Calendar_constructor,
  7922. // Subclasses can override this for initialization logic after the constructor has been called
  7923. initialize: function() {
  7924. },
  7925. // Computes the flattened options hash for the calendar and assigns to `this.options`.
  7926. // Assumes this.overrides and this.dynamicOverrides have already been initialized.
  7927. populateOptionsHash: function() {
  7928. var locale, localeDefaults;
  7929. var isRTL, dirDefaults;
  7930. locale = firstDefined( // explicit locale option given?
  7931. this.dynamicOverrides.locale,
  7932. this.overrides.locale
  7933. );
  7934. localeDefaults = localeOptionHash[locale];
  7935. if (!localeDefaults) { // explicit locale option not given or invalid?
  7936. locale = Calendar.defaults.locale;
  7937. localeDefaults = localeOptionHash[locale] || {};
  7938. }
  7939. isRTL = firstDefined( // based on options computed so far, is direction RTL?
  7940. this.dynamicOverrides.isRTL,
  7941. this.overrides.isRTL,
  7942. localeDefaults.isRTL,
  7943. Calendar.defaults.isRTL
  7944. );
  7945. dirDefaults = isRTL ? Calendar.rtlDefaults : {};
  7946. this.dirDefaults = dirDefaults;
  7947. this.localeDefaults = localeDefaults;
  7948. this.options = mergeOptions([ // merge defaults and overrides. lowest to highest precedence
  7949. Calendar.defaults, // global defaults
  7950. dirDefaults,
  7951. localeDefaults,
  7952. this.overrides,
  7953. this.dynamicOverrides
  7954. ]);
  7955. populateInstanceComputableOptions(this.options); // fill in gaps with computed options
  7956. },
  7957. // Gets information about how to create a view. Will use a cache.
  7958. getViewSpec: function(viewType) {
  7959. var cache = this.viewSpecCache;
  7960. return cache[viewType] || (cache[viewType] = this.buildViewSpec(viewType));
  7961. },
  7962. // Given a duration singular unit, like "week" or "day", finds a matching view spec.
  7963. // Preference is given to views that have corresponding buttons.
  7964. getUnitViewSpec: function(unit) {
  7965. var viewTypes;
  7966. var i;
  7967. var spec;
  7968. if ($.inArray(unit, intervalUnits) != -1) {
  7969. // put views that have buttons first. there will be duplicates, but oh well
  7970. viewTypes = this.header.getViewsWithButtons(); // TODO: include footer as well?
  7971. $.each(FC.views, function(viewType) { // all views
  7972. viewTypes.push(viewType);
  7973. });
  7974. for (i = 0; i < viewTypes.length; i++) {
  7975. spec = this.getViewSpec(viewTypes[i]);
  7976. if (spec) {
  7977. if (spec.singleUnit == unit) {
  7978. return spec;
  7979. }
  7980. }
  7981. }
  7982. }
  7983. },
  7984. // Builds an object with information on how to create a given view
  7985. buildViewSpec: function(requestedViewType) {
  7986. var viewOverrides = this.overrides.views || {};
  7987. var specChain = []; // for the view. lowest to highest priority
  7988. var defaultsChain = []; // for the view. lowest to highest priority
  7989. var overridesChain = []; // for the view. lowest to highest priority
  7990. var viewType = requestedViewType;
  7991. var spec; // for the view
  7992. var overrides; // for the view
  7993. var duration;
  7994. var unit;
  7995. // iterate from the specific view definition to a more general one until we hit an actual View class
  7996. while (viewType) {
  7997. spec = fcViews[viewType];
  7998. overrides = viewOverrides[viewType];
  7999. viewType = null; // clear. might repopulate for another iteration
  8000. if (typeof spec === 'function') { // TODO: deprecate
  8001. spec = { 'class': spec };
  8002. }
  8003. if (spec) {
  8004. specChain.unshift(spec);
  8005. defaultsChain.unshift(spec.defaults || {});
  8006. duration = duration || spec.duration;
  8007. viewType = viewType || spec.type;
  8008. }
  8009. if (overrides) {
  8010. overridesChain.unshift(overrides); // view-specific option hashes have options at zero-level
  8011. duration = duration || overrides.duration;
  8012. viewType = viewType || overrides.type;
  8013. }
  8014. }
  8015. spec = mergeProps(specChain);
  8016. spec.type = requestedViewType;
  8017. if (!spec['class']) {
  8018. return false;
  8019. }
  8020. if (duration) {
  8021. duration = moment.duration(duration);
  8022. if (duration.valueOf()) { // valid?
  8023. spec.duration = duration;
  8024. unit = computeIntervalUnit(duration);
  8025. // view is a single-unit duration, like "week" or "day"
  8026. // incorporate options for this. lowest priority
  8027. if (duration.as(unit) === 1) {
  8028. spec.singleUnit = unit;
  8029. overridesChain.unshift(viewOverrides[unit] || {});
  8030. }
  8031. }
  8032. }
  8033. spec.defaults = mergeOptions(defaultsChain);
  8034. spec.overrides = mergeOptions(overridesChain);
  8035. this.buildViewSpecOptions(spec);
  8036. this.buildViewSpecButtonText(spec, requestedViewType);
  8037. return spec;
  8038. },
  8039. // Builds and assigns a view spec's options object from its already-assigned defaults and overrides
  8040. buildViewSpecOptions: function(spec) {
  8041. spec.options = mergeOptions([ // lowest to highest priority
  8042. Calendar.defaults, // global defaults
  8043. spec.defaults, // view's defaults (from ViewSubclass.defaults)
  8044. this.dirDefaults,
  8045. this.localeDefaults, // locale and dir take precedence over view's defaults!
  8046. this.overrides, // calendar's overrides (options given to constructor)
  8047. spec.overrides, // view's overrides (view-specific options)
  8048. this.dynamicOverrides // dynamically set via setter. highest precedence
  8049. ]);
  8050. populateInstanceComputableOptions(spec.options);
  8051. },
  8052. // Computes and assigns a view spec's buttonText-related options
  8053. buildViewSpecButtonText: function(spec, requestedViewType) {
  8054. // given an options object with a possible `buttonText` hash, lookup the buttonText for the
  8055. // requested view, falling back to a generic unit entry like "week" or "day"
  8056. function queryButtonText(options) {
  8057. var buttonText = options.buttonText || {};
  8058. return buttonText[requestedViewType] ||
  8059. // view can decide to look up a certain key
  8060. (spec.buttonTextKey ? buttonText[spec.buttonTextKey] : null) ||
  8061. // a key like "month"
  8062. (spec.singleUnit ? buttonText[spec.singleUnit] : null);
  8063. }
  8064. // highest to lowest priority
  8065. spec.buttonTextOverride =
  8066. queryButtonText(this.dynamicOverrides) ||
  8067. queryButtonText(this.overrides) || // constructor-specified buttonText lookup hash takes precedence
  8068. spec.overrides.buttonText; // `buttonText` for view-specific options is a string
  8069. // highest to lowest priority. mirrors buildViewSpecOptions
  8070. spec.buttonTextDefault =
  8071. queryButtonText(this.localeDefaults) ||
  8072. queryButtonText(this.dirDefaults) ||
  8073. spec.defaults.buttonText || // a single string. from ViewSubclass.defaults
  8074. queryButtonText(Calendar.defaults) ||
  8075. (spec.duration ? this.humanizeDuration(spec.duration) : null) || // like "3 days"
  8076. requestedViewType; // fall back to given view name
  8077. },
  8078. // Given a view name for a custom view or a standard view, creates a ready-to-go View object
  8079. instantiateView: function(viewType) {
  8080. var spec = this.getViewSpec(viewType);
  8081. return new spec['class'](this, viewType, spec.options, spec.duration);
  8082. },
  8083. // Returns a boolean about whether the view is okay to instantiate at some point
  8084. isValidViewType: function(viewType) {
  8085. return Boolean(this.getViewSpec(viewType));
  8086. },
  8087. // Should be called when any type of async data fetching begins
  8088. pushLoading: function() {
  8089. if (!(this.loadingLevel++)) {
  8090. this.publiclyTrigger('loading', null, true, this.view);
  8091. }
  8092. },
  8093. // Should be called when any type of async data fetching completes
  8094. popLoading: function() {
  8095. if (!(--this.loadingLevel)) {
  8096. this.publiclyTrigger('loading', null, false, this.view);
  8097. }
  8098. },
  8099. // Given arguments to the select method in the API, returns a span (unzoned start/end and other info)
  8100. buildSelectSpan: function(zonedStartInput, zonedEndInput) {
  8101. var start = this.moment(zonedStartInput).stripZone();
  8102. var end;
  8103. if (zonedEndInput) {
  8104. end = this.moment(zonedEndInput).stripZone();
  8105. }
  8106. else if (start.hasTime()) {
  8107. end = start.clone().add(this.defaultTimedEventDuration);
  8108. }
  8109. else {
  8110. end = start.clone().add(this.defaultAllDayEventDuration);
  8111. }
  8112. return { start: start, end: end };
  8113. }
  8114. });
  8115. Calendar.mixin(EmitterMixin);
  8116. function Calendar_constructor(element, overrides) {
  8117. var t = this;
  8118. // declare the current calendar instance relies on GlobalEmitter. needed for garbage collection.
  8119. GlobalEmitter.needed();
  8120. // Exports
  8121. // -----------------------------------------------------------------------------------
  8122. t.render = render;
  8123. t.destroy = destroy;
  8124. t.rerenderEvents = rerenderEvents;
  8125. t.changeView = renderView; // `renderView` will switch to another view
  8126. t.select = select;
  8127. t.unselect = unselect;
  8128. t.prev = prev;
  8129. t.next = next;
  8130. t.prevYear = prevYear;
  8131. t.nextYear = nextYear;
  8132. t.today = today;
  8133. t.gotoDate = gotoDate;
  8134. t.incrementDate = incrementDate;
  8135. t.zoomTo = zoomTo;
  8136. t.getDate = getDate;
  8137. t.getCalendar = getCalendar;
  8138. t.getView = getView;
  8139. t.option = option; // getter/setter method
  8140. t.publiclyTrigger = publiclyTrigger;
  8141. // Options
  8142. // -----------------------------------------------------------------------------------
  8143. t.dynamicOverrides = {};
  8144. t.viewSpecCache = {};
  8145. t.optionHandlers = {}; // for Calendar.options.js
  8146. t.overrides = $.extend({}, overrides); // make a copy
  8147. t.populateOptionsHash(); // sets this.options
  8148. // Locale-data Internals
  8149. // -----------------------------------------------------------------------------------
  8150. // Apply overrides to the current locale's data
  8151. var localeData;
  8152. // Called immediately, and when any of the options change.
  8153. // Happens before any internal objects rebuild or rerender, because this is very core.
  8154. t.bindOptions([
  8155. 'locale', 'monthNames', 'monthNamesShort', 'dayNames', 'dayNamesShort', 'firstDay', 'weekNumberCalculation'
  8156. ], function(locale, monthNames, monthNamesShort, dayNames, dayNamesShort, firstDay, weekNumberCalculation) {
  8157. // normalize
  8158. if (weekNumberCalculation === 'iso') {
  8159. weekNumberCalculation = 'ISO'; // normalize
  8160. }
  8161. localeData = createObject( // make a cheap copy
  8162. getMomentLocaleData(locale) // will fall back to en
  8163. );
  8164. if (monthNames) {
  8165. localeData._months = monthNames;
  8166. }
  8167. if (monthNamesShort) {
  8168. localeData._monthsShort = monthNamesShort;
  8169. }
  8170. if (dayNames) {
  8171. localeData._weekdays = dayNames;
  8172. }
  8173. if (dayNamesShort) {
  8174. localeData._weekdaysShort = dayNamesShort;
  8175. }
  8176. if (firstDay == null && weekNumberCalculation === 'ISO') {
  8177. firstDay = 1;
  8178. }
  8179. if (firstDay != null) {
  8180. var _week = createObject(localeData._week); // _week: { dow: # }
  8181. _week.dow = firstDay;
  8182. localeData._week = _week;
  8183. }
  8184. if ( // whitelist certain kinds of input
  8185. weekNumberCalculation === 'ISO' ||
  8186. weekNumberCalculation === 'local' ||
  8187. typeof weekNumberCalculation === 'function'
  8188. ) {
  8189. localeData._fullCalendar_weekCalc = weekNumberCalculation; // moment-ext will know what to do with it
  8190. }
  8191. // If the internal current date object already exists, move to new locale.
  8192. // We do NOT need to do this technique for event dates, because this happens when converting to "segments".
  8193. if (date) {
  8194. localizeMoment(date); // sets to localeData
  8195. }
  8196. });
  8197. // Calendar-specific Date Utilities
  8198. // -----------------------------------------------------------------------------------
  8199. t.defaultAllDayEventDuration = moment.duration(t.options.defaultAllDayEventDuration);
  8200. t.defaultTimedEventDuration = moment.duration(t.options.defaultTimedEventDuration);
  8201. // Builds a moment using the settings of the current calendar: timezone and locale.
  8202. // Accepts anything the vanilla moment() constructor accepts.
  8203. t.moment = function() {
  8204. var mom;
  8205. if (t.options.timezone === 'local') {
  8206. mom = FC.moment.apply(null, arguments);
  8207. // Force the moment to be local, because FC.moment doesn't guarantee it.
  8208. if (mom.hasTime()) { // don't give ambiguously-timed moments a local zone
  8209. mom.local();
  8210. }
  8211. }
  8212. else if (t.options.timezone === 'UTC') {
  8213. mom = FC.moment.utc.apply(null, arguments); // process as UTC
  8214. }
  8215. else {
  8216. mom = FC.moment.parseZone.apply(null, arguments); // let the input decide the zone
  8217. }
  8218. localizeMoment(mom);
  8219. return mom;
  8220. };
  8221. // Updates the given moment's locale settings to the current calendar locale settings.
  8222. function localizeMoment(mom) {
  8223. mom._locale = localeData;
  8224. }
  8225. t.localizeMoment = localizeMoment;
  8226. // Returns a boolean about whether or not the calendar knows how to calculate
  8227. // the timezone offset of arbitrary dates in the current timezone.
  8228. t.getIsAmbigTimezone = function() {
  8229. return t.options.timezone !== 'local' && t.options.timezone !== 'UTC';
  8230. };
  8231. // Returns a copy of the given date in the current timezone. Has no effect on dates without times.
  8232. t.applyTimezone = function(date) {
  8233. if (!date.hasTime()) {
  8234. return date.clone();
  8235. }
  8236. var zonedDate = t.moment(date.toArray());
  8237. var timeAdjust = date.time() - zonedDate.time();
  8238. var adjustedZonedDate;
  8239. // Safari sometimes has problems with this coersion when near DST. Adjust if necessary. (bug #2396)
  8240. if (timeAdjust) { // is the time result different than expected?
  8241. adjustedZonedDate = zonedDate.clone().add(timeAdjust); // add milliseconds
  8242. if (date.time() - adjustedZonedDate.time() === 0) { // does it match perfectly now?
  8243. zonedDate = adjustedZonedDate;
  8244. }
  8245. }
  8246. return zonedDate;
  8247. };
  8248. // Returns a moment for the current date, as defined by the client's computer or from the `now` option.
  8249. // Will return an moment with an ambiguous timezone.
  8250. t.getNow = function() {
  8251. var now = t.options.now;
  8252. if (typeof now === 'function') {
  8253. now = now();
  8254. }
  8255. return t.moment(now).stripZone();
  8256. };
  8257. // Get an event's normalized end date. If not present, calculate it from the defaults.
  8258. t.getEventEnd = function(event) {
  8259. if (event.end) {
  8260. return event.end.clone();
  8261. }
  8262. else {
  8263. return t.getDefaultEventEnd(event.allDay, event.start);
  8264. }
  8265. };
  8266. // Given an event's allDay status and start date, return what its fallback end date should be.
  8267. // TODO: rename to computeDefaultEventEnd
  8268. t.getDefaultEventEnd = function(allDay, zonedStart) {
  8269. var end = zonedStart.clone();
  8270. if (allDay) {
  8271. end.stripTime().add(t.defaultAllDayEventDuration);
  8272. }
  8273. else {
  8274. end.add(t.defaultTimedEventDuration);
  8275. }
  8276. if (t.getIsAmbigTimezone()) {
  8277. end.stripZone(); // we don't know what the tzo should be
  8278. }
  8279. return end;
  8280. };
  8281. // Produces a human-readable string for the given duration.
  8282. // Side-effect: changes the locale of the given duration.
  8283. t.humanizeDuration = function(duration) {
  8284. return duration.locale(t.options.locale).humanize();
  8285. };
  8286. // Imports
  8287. // -----------------------------------------------------------------------------------
  8288. EventManager.call(t);
  8289. // Locals
  8290. // -----------------------------------------------------------------------------------
  8291. var _element = element[0];
  8292. var toolbarsManager;
  8293. var header;
  8294. var footer;
  8295. var content;
  8296. var tm; // for making theme classes
  8297. var currentView; // NOTE: keep this in sync with this.view
  8298. var viewsByType = {}; // holds all instantiated view instances, current or not
  8299. var suggestedViewHeight;
  8300. var windowResizeProxy; // wraps the windowResize function
  8301. var ignoreWindowResize = 0;
  8302. var date; // unzoned
  8303. // Main Rendering
  8304. // -----------------------------------------------------------------------------------
  8305. // compute the initial ambig-timezone date
  8306. if (t.options.defaultDate != null) {
  8307. date = t.moment(t.options.defaultDate).stripZone();
  8308. }
  8309. else {
  8310. date = t.getNow(); // getNow already returns unzoned
  8311. }
  8312. function render() {
  8313. if (!content) {
  8314. initialRender();
  8315. }
  8316. else if (elementVisible()) {
  8317. // mainly for the public API
  8318. calcSize();
  8319. renderView();
  8320. }
  8321. }
  8322. function initialRender() {
  8323. element.addClass('fc');
  8324. // event delegation for nav links
  8325. element.on('click.fc', 'a[data-goto]', function(ev) {
  8326. var anchorEl = $(this);
  8327. var gotoOptions = anchorEl.data('goto'); // will automatically parse JSON
  8328. var date = t.moment(gotoOptions.date);
  8329. var viewType = gotoOptions.type;
  8330. // property like "navLinkDayClick". might be a string or a function
  8331. var customAction = currentView.opt('navLink' + capitaliseFirstLetter(viewType) + 'Click');
  8332. if (typeof customAction === 'function') {
  8333. customAction(date, ev);
  8334. }
  8335. else {
  8336. if (typeof customAction === 'string') {
  8337. viewType = customAction;
  8338. }
  8339. zoomTo(date, viewType);
  8340. }
  8341. });
  8342. // called immediately, and upon option change
  8343. t.bindOption('theme', function(theme) {
  8344. tm = theme ? 'ui' : 'fc'; // affects a larger scope
  8345. element.toggleClass('ui-widget', theme);
  8346. element.toggleClass('fc-unthemed', !theme);
  8347. });
  8348. // called immediately, and upon option change.
  8349. // HACK: locale often affects isRTL, so we explicitly listen to that too.
  8350. t.bindOptions([ 'isRTL', 'locale' ], function(isRTL) {
  8351. element.toggleClass('fc-ltr', !isRTL);
  8352. element.toggleClass('fc-rtl', isRTL);
  8353. });
  8354. content = $("<div class='fc-view-container'/>").prependTo(element);
  8355. var toolbars = buildToolbars();
  8356. toolbarsManager = new Iterator(toolbars);
  8357. header = t.header = toolbars[0];
  8358. footer = t.footer = toolbars[1];
  8359. renderHeader();
  8360. renderFooter();
  8361. renderView(t.options.defaultView);
  8362. if (t.options.handleWindowResize) {
  8363. windowResizeProxy = debounce(windowResize, t.options.windowResizeDelay); // prevents rapid calls
  8364. $(window).resize(windowResizeProxy);
  8365. }
  8366. }
  8367. function destroy() {
  8368. if (currentView) {
  8369. currentView.removeElement();
  8370. // NOTE: don't null-out currentView/t.view in case API methods are called after destroy.
  8371. // It is still the "current" view, just not rendered.
  8372. }
  8373. toolbarsManager.proxyCall('removeElement');
  8374. content.remove();
  8375. element.removeClass('fc fc-ltr fc-rtl fc-unthemed ui-widget');
  8376. element.off('.fc'); // unbind nav link handlers
  8377. if (windowResizeProxy) {
  8378. $(window).unbind('resize', windowResizeProxy);
  8379. }
  8380. GlobalEmitter.unneeded();
  8381. }
  8382. function elementVisible() {
  8383. return element.is(':visible');
  8384. }
  8385. // View Rendering
  8386. // -----------------------------------------------------------------------------------
  8387. // Renders a view because of a date change, view-type change, or for the first time.
  8388. // If not given a viewType, keep the current view but render different dates.
  8389. // Accepts an optional scroll state to restore to.
  8390. function renderView(viewType, forcedScroll) {
  8391. ignoreWindowResize++;
  8392. var needsClearView = currentView && viewType && currentView.type !== viewType;
  8393. // if viewType is changing, remove the old view's rendering
  8394. if (needsClearView) {
  8395. freezeContentHeight(); // prevent a scroll jump when view element is removed
  8396. clearView();
  8397. }
  8398. // if viewType changed, or the view was never created, create a fresh view
  8399. if (!currentView && viewType) {
  8400. currentView = t.view =
  8401. viewsByType[viewType] ||
  8402. (viewsByType[viewType] = t.instantiateView(viewType));
  8403. currentView.setElement(
  8404. $("<div class='fc-view fc-" + viewType + "-view' />").appendTo(content)
  8405. );
  8406. toolbarsManager.proxyCall('activateButton', viewType);
  8407. }
  8408. if (currentView) {
  8409. // in case the view should render a period of time that is completely hidden
  8410. date = currentView.massageCurrentDate(date);
  8411. // render or rerender the view
  8412. if (
  8413. !currentView.isDateSet ||
  8414. !( // NOT within interval range signals an implicit date window change
  8415. date >= currentView.intervalStart &&
  8416. date < currentView.intervalEnd
  8417. )
  8418. ) {
  8419. if (elementVisible()) {
  8420. if (forcedScroll) {
  8421. currentView.captureInitialScroll(forcedScroll);
  8422. }
  8423. currentView.setDate(date, forcedScroll);
  8424. if (forcedScroll) {
  8425. currentView.releaseScroll();
  8426. }
  8427. // need to do this after View::render, so dates are calculated
  8428. // NOTE: view updates title text proactively
  8429. updateToolbarsTodayButton();
  8430. }
  8431. }
  8432. }
  8433. if (needsClearView) {
  8434. thawContentHeight();
  8435. }
  8436. ignoreWindowResize--;
  8437. inlineLoad();
  8438. $('.fc-scroller').overlayScrollbars({ scrollbars : { autoHide: "leave"}});
  8439. }
  8440. // Unrenders the current view and reflects this change in the Header.
  8441. // Unregsiters the `currentView`, but does not remove from viewByType hash.
  8442. function clearView() {
  8443. toolbarsManager.proxyCall('deactivateButton', currentView.type);
  8444. currentView.removeElement();
  8445. currentView = t.view = null;
  8446. }
  8447. // Destroys the view, including the view object. Then, re-instantiates it and renders it.
  8448. // Maintains the same scroll state.
  8449. // TODO: maintain any other user-manipulated state.
  8450. function reinitView() {
  8451. ignoreWindowResize++;
  8452. freezeContentHeight();
  8453. var viewType = currentView.type;
  8454. var scrollState = currentView.queryScroll();
  8455. clearView();
  8456. calcSize();
  8457. renderView(viewType, scrollState);
  8458. thawContentHeight();
  8459. ignoreWindowResize--;
  8460. }
  8461. // Resizing
  8462. // -----------------------------------------------------------------------------------
  8463. t.getSuggestedViewHeight = function() {
  8464. if (suggestedViewHeight === undefined) {
  8465. calcSize();
  8466. }
  8467. return suggestedViewHeight;
  8468. };
  8469. t.isHeightAuto = function() {
  8470. return t.options.contentHeight === 'auto' || t.options.height === 'auto';
  8471. };
  8472. function updateSize(shouldRecalc) {
  8473. if (elementVisible()) {
  8474. if (shouldRecalc) {
  8475. _calcSize();
  8476. }
  8477. ignoreWindowResize++;
  8478. currentView.updateSize(true); // isResize=true. will poll getSuggestedViewHeight() and isHeightAuto()
  8479. ignoreWindowResize--;
  8480. return true; // signal success
  8481. }
  8482. }
  8483. function calcSize() {
  8484. if (elementVisible()) {
  8485. _calcSize();
  8486. }
  8487. }
  8488. function _calcSize() { // assumes elementVisible
  8489. var contentHeightInput = t.options.contentHeight;
  8490. var heightInput = t.options.height;
  8491. if (typeof contentHeightInput === 'number') { // exists and not 'auto'
  8492. suggestedViewHeight = contentHeightInput;
  8493. }
  8494. else if (typeof contentHeightInput === 'function') { // exists and is a function
  8495. suggestedViewHeight = contentHeightInput();
  8496. }
  8497. else if (typeof heightInput === 'number') { // exists and not 'auto'
  8498. suggestedViewHeight = heightInput - queryToolbarsHeight();
  8499. }
  8500. else if (typeof heightInput === 'function') { // exists and is a function
  8501. suggestedViewHeight = heightInput() - queryToolbarsHeight();
  8502. }
  8503. else if (heightInput === 'parent') { // set to height of parent element
  8504. suggestedViewHeight = element.parent().height() - queryToolbarsHeight();
  8505. }
  8506. else {
  8507. suggestedViewHeight = Math.round(content.width() / Math.max(t.options.aspectRatio, .5));
  8508. }
  8509. }
  8510. function queryToolbarsHeight() {
  8511. return toolbarsManager.items.reduce(function(accumulator, toolbar) {
  8512. var toolbarHeight = toolbar.el ? toolbar.el.outerHeight(true) : 0; // includes margin
  8513. return accumulator + toolbarHeight;
  8514. }, 0);
  8515. }
  8516. function windowResize(ev) {
  8517. if (
  8518. !ignoreWindowResize &&
  8519. ev.target === window && // so we don't process jqui "resize" events that have bubbled up
  8520. currentView.start // view has already been rendered
  8521. ) {
  8522. if (updateSize(true)) {
  8523. currentView.publiclyTrigger('windowResize', _element);
  8524. }
  8525. }
  8526. }
  8527. /* Event Rendering
  8528. -----------------------------------------------------------------------------*/
  8529. function rerenderEvents() { // API method. destroys old events if previously rendered.
  8530. if (elementVisible()) {
  8531. t.reportEventChange(); // will re-trasmit events to the view, causing a rerender
  8532. }
  8533. }
  8534. /* Toolbars
  8535. -----------------------------------------------------------------------------*/
  8536. function buildToolbars() {
  8537. return [
  8538. new Toolbar(t, computeHeaderOptions()),
  8539. new Toolbar(t, computeFooterOptions())
  8540. ];
  8541. }
  8542. function computeHeaderOptions() {
  8543. return {
  8544. extraClasses: 'fc-header-toolbar',
  8545. layout: t.options.header
  8546. };
  8547. }
  8548. function computeFooterOptions() {
  8549. return {
  8550. extraClasses: 'fc-footer-toolbar',
  8551. layout: t.options.footer
  8552. };
  8553. }
  8554. // can be called repeatedly and Header will rerender
  8555. function renderHeader() {
  8556. header.setToolbarOptions(computeHeaderOptions());
  8557. header.render();
  8558. if (header.el) {
  8559. element.prepend(header.el);
  8560. }
  8561. }
  8562. // can be called repeatedly and Footer will rerender
  8563. function renderFooter() {
  8564. footer.setToolbarOptions(computeFooterOptions());
  8565. footer.render();
  8566. if (footer.el) {
  8567. element.append(footer.el);
  8568. }
  8569. }
  8570. t.setToolbarsTitle = function(title) {
  8571. toolbarsManager.proxyCall('updateTitle', title);
  8572. };
  8573. function updateToolbarsTodayButton() {
  8574. var now = t.getNow();
  8575. if (now >= currentView.intervalStart && now < currentView.intervalEnd) {
  8576. toolbarsManager.proxyCall('disableButton', 'today');
  8577. }
  8578. else {
  8579. toolbarsManager.proxyCall('enableButton', 'today');
  8580. }
  8581. }
  8582. /* Selection
  8583. -----------------------------------------------------------------------------*/
  8584. // this public method receives start/end dates in any format, with any timezone
  8585. function select(zonedStartInput, zonedEndInput) {
  8586. currentView.select(
  8587. t.buildSelectSpan.apply(t, arguments)
  8588. );
  8589. }
  8590. function unselect() { // safe to be called before renderView
  8591. if (currentView) {
  8592. currentView.unselect();
  8593. }
  8594. }
  8595. /* Date
  8596. -----------------------------------------------------------------------------*/
  8597. function prev() {
  8598. date = currentView.computePrevDate(date);
  8599. renderView();
  8600. $('.fc-scroller').overlayScrollbars({ scrollbars : { autoHide: "leave"}});
  8601. }
  8602. function next() {
  8603. date = currentView.computeNextDate(date);
  8604. renderView();
  8605. $('.fc-scroller').overlayScrollbars({ scrollbars : { autoHide: "leave"}});
  8606. }
  8607. function prevYear() {
  8608. date.add(-1, 'years');
  8609. renderView();
  8610. }
  8611. function nextYear() {
  8612. date.add(1, 'years');
  8613. renderView();
  8614. }
  8615. function today() {
  8616. date = t.getNow();
  8617. renderView();
  8618. }
  8619. function gotoDate(zonedDateInput) {
  8620. date = t.moment(zonedDateInput).stripZone();
  8621. renderView();
  8622. }
  8623. function incrementDate(delta) {
  8624. date.add(moment.duration(delta));
  8625. renderView();
  8626. }
  8627. // Forces navigation to a view for the given date.
  8628. // `viewType` can be a specific view name or a generic one like "week" or "day".
  8629. function zoomTo(newDate, viewType) {
  8630. var spec;
  8631. viewType = viewType || 'day'; // day is default zoom
  8632. spec = t.getViewSpec(viewType) || t.getUnitViewSpec(viewType);
  8633. date = newDate.clone();
  8634. renderView(spec ? spec.type : null);
  8635. }
  8636. // for external API
  8637. function getDate() {
  8638. return t.applyTimezone(date); // infuse the calendar's timezone
  8639. }
  8640. /* Height "Freezing"
  8641. -----------------------------------------------------------------------------*/
  8642. t.freezeContentHeight = freezeContentHeight;
  8643. t.thawContentHeight = thawContentHeight;
  8644. var freezeContentHeightDepth = 0;
  8645. function freezeContentHeight() {
  8646. if (!(freezeContentHeightDepth++)) {
  8647. content.css({
  8648. width: '100%',
  8649. height: content.height(),
  8650. overflow: 'hidden'
  8651. });
  8652. }
  8653. }
  8654. function thawContentHeight() {
  8655. if (!(--freezeContentHeightDepth)) {
  8656. content.css({
  8657. width: '',
  8658. height: '',
  8659. overflow: ''
  8660. });
  8661. }
  8662. }
  8663. /* Misc
  8664. -----------------------------------------------------------------------------*/
  8665. function getCalendar() {
  8666. return t;
  8667. }
  8668. function getView() {
  8669. return currentView;
  8670. }
  8671. function option(name, value) {
  8672. var newOptionHash;
  8673. if (typeof name === 'string') {
  8674. if (value === undefined) { // getter
  8675. return t.options[name];
  8676. }
  8677. else { // setter for individual option
  8678. newOptionHash = {};
  8679. newOptionHash[name] = value;
  8680. setOptions(newOptionHash);
  8681. }
  8682. }
  8683. else if (typeof name === 'object') { // compound setter with object input
  8684. setOptions(name);
  8685. }
  8686. }
  8687. function setOptions(newOptionHash) {
  8688. var optionCnt = 0;
  8689. var optionName;
  8690. for (optionName in newOptionHash) {
  8691. t.dynamicOverrides[optionName] = newOptionHash[optionName];
  8692. }
  8693. t.viewSpecCache = {}; // the dynamic override invalidates the options in this cache, so just clear it
  8694. t.populateOptionsHash(); // this.options needs to be recomputed after the dynamic override
  8695. // trigger handlers after this.options has been updated
  8696. for (optionName in newOptionHash) {
  8697. t.triggerOptionHandlers(optionName); // recall bindOption/bindOptions
  8698. optionCnt++;
  8699. }
  8700. // special-case handling of single option change.
  8701. // if only one option change, `optionName` will be its name.
  8702. if (optionCnt === 1) {
  8703. if (optionName === 'height' || optionName === 'contentHeight' || optionName === 'aspectRatio') {
  8704. updateSize(true); // true = allow recalculation of height
  8705. return;
  8706. }
  8707. else if (optionName === 'defaultDate') {
  8708. return; // can't change date this way. use gotoDate instead
  8709. }
  8710. else if (optionName === 'businessHours') {
  8711. if (currentView) {
  8712. currentView.unrenderBusinessHours();
  8713. currentView.renderBusinessHours();
  8714. }
  8715. return;
  8716. }
  8717. else if (optionName === 'timezone') {
  8718. t.rezoneArrayEventSources();
  8719. t.refetchEvents();
  8720. return;
  8721. }
  8722. }
  8723. // catch-all. rerender the header and footer and rebuild/rerender the current view
  8724. renderHeader();
  8725. renderFooter();
  8726. viewsByType = {}; // even non-current views will be affected by this option change. do before rerender
  8727. reinitView();
  8728. }
  8729. function publiclyTrigger(name, thisObj) {
  8730. var args = Array.prototype.slice.call(arguments, 2);
  8731. thisObj = thisObj || _element;
  8732. this.triggerWith(name, thisObj, args); // Emitter's method
  8733. if (t.options[name]) {
  8734. return t.options[name].apply(thisObj, args);
  8735. }
  8736. }
  8737. t.initialize();
  8738. }
  8739. ;;
  8740. /*
  8741. Options binding/triggering system.
  8742. */
  8743. Calendar.mixin({
  8744. // A map of option names to arrays of handler objects. Initialized to {} in Calendar.
  8745. // Format for a handler object:
  8746. // {
  8747. // func // callback function to be called upon change
  8748. // names // option names whose values should be given to func
  8749. // }
  8750. optionHandlers: null,
  8751. // Calls handlerFunc immediately, and when the given option has changed.
  8752. // handlerFunc will be given the option value.
  8753. bindOption: function(optionName, handlerFunc) {
  8754. this.bindOptions([ optionName ], handlerFunc);
  8755. },
  8756. // Calls handlerFunc immediately, and when any of the given options change.
  8757. // handlerFunc will be given each option value as ordered function arguments.
  8758. bindOptions: function(optionNames, handlerFunc) {
  8759. var handlerObj = { func: handlerFunc, names: optionNames };
  8760. var i;
  8761. for (i = 0; i < optionNames.length; i++) {
  8762. this.registerOptionHandlerObj(optionNames[i], handlerObj);
  8763. }
  8764. this.triggerOptionHandlerObj(handlerObj);
  8765. },
  8766. // Puts the given handler object into the internal hash
  8767. registerOptionHandlerObj: function(optionName, handlerObj) {
  8768. (this.optionHandlers[optionName] || (this.optionHandlers[optionName] = []))
  8769. .push(handlerObj);
  8770. },
  8771. // Reports that the given option has changed, and calls all appropriate handlers.
  8772. triggerOptionHandlers: function(optionName) {
  8773. var handlerObjs = this.optionHandlers[optionName] || [];
  8774. var i;
  8775. for (i = 0; i < handlerObjs.length; i++) {
  8776. this.triggerOptionHandlerObj(handlerObjs[i]);
  8777. }
  8778. },
  8779. // Calls the callback for a specific handler object, passing in the appropriate arguments.
  8780. triggerOptionHandlerObj: function(handlerObj) {
  8781. var optionNames = handlerObj.names;
  8782. var optionValues = [];
  8783. var i;
  8784. for (i = 0; i < optionNames.length; i++) {
  8785. optionValues.push(this.options[optionNames[i]]);
  8786. }
  8787. handlerObj.func.apply(this, optionValues); // maintain the Calendar's `this` context
  8788. }
  8789. });
  8790. ;;
  8791. Calendar.defaults = {
  8792. titleRangeSeparator: ' \u2013 ', // en dash
  8793. monthYearFormat: 'MMMM YYYY', // required for en. other locales rely on datepicker computable option
  8794. defaultTimedEventDuration: '02:00:00',
  8795. defaultAllDayEventDuration: { days: 1 },
  8796. forceEventDuration: false,
  8797. nextDayThreshold: '09:00:00', // 9am
  8798. // display
  8799. defaultView: 'month',
  8800. aspectRatio: 1.35,
  8801. header: {
  8802. left: 'title',
  8803. center: '',
  8804. right: 'today prev,next'
  8805. },
  8806. weekends: true,
  8807. weekNumbers: false,
  8808. weekNumberTitle: 'W',
  8809. weekNumberCalculation: 'local',
  8810. //editable: false,
  8811. //nowIndicator: false,
  8812. scrollTime: '06:00:00',
  8813. // event ajax
  8814. lazyFetching: true,
  8815. startParam: 'start',
  8816. endParam: 'end',
  8817. timezoneParam: 'timezone',
  8818. timezone: false,
  8819. //allDayDefault: undefined,
  8820. // locale
  8821. isRTL: false,
  8822. buttonText: {
  8823. prev: "prev",
  8824. next: "next",
  8825. prevYear: "prev year",
  8826. nextYear: "next year",
  8827. year: 'year', // TODO: locale files need to specify this
  8828. today: 'today',
  8829. month: 'month',
  8830. week: 'week',
  8831. day: 'day'
  8832. },
  8833. buttonIcons: {
  8834. prev: 'left-single-arrow',
  8835. next: 'right-single-arrow',
  8836. prevYear: 'left-double-arrow',
  8837. nextYear: 'right-double-arrow'
  8838. },
  8839. allDayText: 'all-day',
  8840. // jquery-ui theming
  8841. theme: false,
  8842. themeButtonIcons: {
  8843. prev: 'circle-triangle-w',
  8844. next: 'circle-triangle-e',
  8845. prevYear: 'seek-prev',
  8846. nextYear: 'seek-next'
  8847. },
  8848. //eventResizableFromStart: false,
  8849. dragOpacity: .75,
  8850. dragRevertDuration: 500,
  8851. dragScroll: true,
  8852. //selectable: false,
  8853. unselectAuto: true,
  8854. //selectMinDistance: 0,
  8855. dropAccept: '*',
  8856. eventOrder: 'title',
  8857. //eventRenderWait: null,
  8858. eventLimit: false,
  8859. eventLimitText: 'more',
  8860. eventLimitClick: 'popover',
  8861. dayPopoverFormat: 'LL',
  8862. handleWindowResize: true,
  8863. windowResizeDelay: 100, // milliseconds before an updateSize happens
  8864. longPressDelay: 1000
  8865. };
  8866. Calendar.englishDefaults = { // used by locale.js
  8867. dayPopoverFormat: 'dddd, MMMM D'
  8868. };
  8869. Calendar.rtlDefaults = { // right-to-left defaults
  8870. header: { // TODO: smarter solution (first/center/last ?)
  8871. left: 'next,prev today',
  8872. center: '',
  8873. right: 'title'
  8874. },
  8875. buttonIcons: {
  8876. prev: 'right-single-arrow',
  8877. next: 'left-single-arrow',
  8878. prevYear: 'right-double-arrow',
  8879. nextYear: 'left-double-arrow'
  8880. },
  8881. themeButtonIcons: {
  8882. prev: 'circle-triangle-e',
  8883. next: 'circle-triangle-w',
  8884. nextYear: 'seek-prev',
  8885. prevYear: 'seek-next'
  8886. }
  8887. };
  8888. ;;
  8889. var localeOptionHash = FC.locales = {}; // initialize and expose
  8890. // TODO: document the structure and ordering of a FullCalendar locale file
  8891. // Initialize jQuery UI datepicker translations while using some of the translations
  8892. // Will set this as the default locales for datepicker.
  8893. FC.datepickerLocale = function(localeCode, dpLocaleCode, dpOptions) {
  8894. // get the FullCalendar internal option hash for this locale. create if necessary
  8895. var fcOptions = localeOptionHash[localeCode] || (localeOptionHash[localeCode] = {});
  8896. // transfer some simple options from datepicker to fc
  8897. fcOptions.isRTL = dpOptions.isRTL;
  8898. fcOptions.weekNumberTitle = dpOptions.weekHeader;
  8899. // compute some more complex options from datepicker
  8900. $.each(dpComputableOptions, function(name, func) {
  8901. fcOptions[name] = func(dpOptions);
  8902. });
  8903. // is jQuery UI Datepicker is on the page?
  8904. if ($.datepicker) {
  8905. // Register the locale data.
  8906. // FullCalendar and MomentJS use locale codes like "pt-br" but Datepicker
  8907. // does it like "pt-BR" or if it doesn't have the locale, maybe just "pt".
  8908. // Make an alias so the locale can be referenced either way.
  8909. $.datepicker.regional[dpLocaleCode] =
  8910. $.datepicker.regional[localeCode] = // alias
  8911. dpOptions;
  8912. // Alias 'en' to the default locale data. Do this every time.
  8913. $.datepicker.regional.en = $.datepicker.regional[''];
  8914. // Set as Datepicker's global defaults.
  8915. $.datepicker.setDefaults(dpOptions);
  8916. }
  8917. };
  8918. // Sets FullCalendar-specific translations. Will set the locales as the global default.
  8919. FC.locale = function(localeCode, newFcOptions) {
  8920. var fcOptions;
  8921. var momOptions;
  8922. // get the FullCalendar internal option hash for this locale. create if necessary
  8923. fcOptions = localeOptionHash[localeCode] || (localeOptionHash[localeCode] = {});
  8924. // provided new options for this locales? merge them in
  8925. if (newFcOptions) {
  8926. fcOptions = localeOptionHash[localeCode] = mergeOptions([ fcOptions, newFcOptions ]);
  8927. }
  8928. // compute locale options that weren't defined.
  8929. // always do this. newFcOptions can be undefined when initializing from i18n file,
  8930. // so no way to tell if this is an initialization or a default-setting.
  8931. momOptions = getMomentLocaleData(localeCode); // will fall back to en
  8932. $.each(momComputableOptions, function(name, func) {
  8933. if (fcOptions[name] == null) {
  8934. fcOptions[name] = func(momOptions, fcOptions);
  8935. }
  8936. });
  8937. // set it as the default locale for FullCalendar
  8938. Calendar.defaults.locale = localeCode;
  8939. };
  8940. // NOTE: can't guarantee any of these computations will run because not every locale has datepicker
  8941. // configs, so make sure there are English fallbacks for these in the defaults file.
  8942. var dpComputableOptions = {
  8943. buttonText: function(dpOptions) {
  8944. return {
  8945. // the translations sometimes wrongly contain HTML entities
  8946. prev: stripHtmlEntities(dpOptions.prevText),
  8947. next: stripHtmlEntities(dpOptions.nextText),
  8948. today: stripHtmlEntities(dpOptions.currentText)
  8949. };
  8950. },
  8951. // Produces format strings like "MMMM YYYY" -> "September 2014"
  8952. monthYearFormat: function(dpOptions) {
  8953. return dpOptions.showMonthAfterYear ?
  8954. 'YYYY[' + dpOptions.yearSuffix + '] MMMM' :
  8955. 'MMMM YYYY[' + dpOptions.yearSuffix + ']';
  8956. }
  8957. };
  8958. var momComputableOptions = {
  8959. // Produces format strings like "ddd M/D" -> "Fri 9/15"
  8960. dayOfMonthFormat: function(momOptions, fcOptions) {
  8961. var format = momOptions.longDateFormat('l'); // for the format like "M/D/YYYY"
  8962. // strip the year off the edge, as well as other misc non-whitespace chars
  8963. format = format.replace(/^Y+[^\w\s]*|[^\w\s]*Y+$/g, '');
  8964. if (fcOptions.isRTL) {
  8965. format += ' ddd'; // for RTL, add day-of-week to end
  8966. }
  8967. else {
  8968. format = 'ddd ' + format; // for LTR, add day-of-week to beginning
  8969. }
  8970. return format;
  8971. },
  8972. // Produces format strings like "h:mma" -> "6:00pm"
  8973. mediumTimeFormat: function(momOptions) { // can't be called `timeFormat` because collides with option
  8974. return momOptions.longDateFormat('LT')
  8975. .replace(/\s*a$/i, 'a'); // convert AM/PM/am/pm to lowercase. remove any spaces beforehand
  8976. },
  8977. // Produces format strings like "h(:mm)a" -> "6pm" / "6:30pm"
  8978. smallTimeFormat: function(momOptions) {
  8979. return momOptions.longDateFormat('LT')
  8980. .replace(':mm', '(:mm)')
  8981. .replace(/(\Wmm)$/, '($1)') // like above, but for foreign locales
  8982. .replace(/\s*a$/i, 'a'); // convert AM/PM/am/pm to lowercase. remove any spaces beforehand
  8983. },
  8984. // Produces format strings like "h(:mm)t" -> "6p" / "6:30p"
  8985. extraSmallTimeFormat: function(momOptions) {
  8986. return momOptions.longDateFormat('LT')
  8987. .replace(':mm', '(:mm)')
  8988. .replace(/(\Wmm)$/, '($1)') // like above, but for foreign locales
  8989. .replace(/\s*a$/i, 't'); // convert to AM/PM/am/pm to lowercase one-letter. remove any spaces beforehand
  8990. },
  8991. // Produces format strings like "ha" / "H" -> "6pm" / "18"
  8992. hourFormat: function(momOptions) {
  8993. return momOptions.longDateFormat('LT')
  8994. .replace(':mm', '')
  8995. .replace(/(\Wmm)$/, '') // like above, but for foreign locales
  8996. .replace(/\s*a$/i, 'a'); // convert AM/PM/am/pm to lowercase. remove any spaces beforehand
  8997. },
  8998. // Produces format strings like "h:mm" -> "6:30" (with no AM/PM)
  8999. noMeridiemTimeFormat: function(momOptions) {
  9000. return momOptions.longDateFormat('LT')
  9001. .replace(/\s*a$/i, ''); // remove trailing AM/PM
  9002. }
  9003. };
  9004. // options that should be computed off live calendar options (considers override options)
  9005. // TODO: best place for this? related to locale?
  9006. // TODO: flipping text based on isRTL is a bad idea because the CSS `direction` might want to handle it
  9007. var instanceComputableOptions = {
  9008. // Produces format strings for results like "Mo 16"
  9009. smallDayDateFormat: function(options) {
  9010. return options.isRTL ?
  9011. 'D dd' :
  9012. 'dd D';
  9013. },
  9014. // Produces format strings for results like "Wk 5"
  9015. weekFormat: function(options) {
  9016. return options.isRTL ?
  9017. 'w[ ' + options.weekNumberTitle + ']' :
  9018. '[' + options.weekNumberTitle + ' ]w';
  9019. },
  9020. // Produces format strings for results like "Wk5"
  9021. smallWeekFormat: function(options) {
  9022. return options.isRTL ?
  9023. 'w[' + options.weekNumberTitle + ']' :
  9024. '[' + options.weekNumberTitle + ']w';
  9025. }
  9026. };
  9027. function populateInstanceComputableOptions(options) {
  9028. $.each(instanceComputableOptions, function(name, func) {
  9029. if (options[name] == null) {
  9030. options[name] = func(options);
  9031. }
  9032. });
  9033. }
  9034. // Returns moment's internal locale data. If doesn't exist, returns English.
  9035. function getMomentLocaleData(localeCode) {
  9036. return moment.localeData(localeCode) || moment.localeData('en');
  9037. }
  9038. // Initialize English by forcing computation of moment-derived options.
  9039. // Also, sets it as the default.
  9040. FC.locale('en', Calendar.englishDefaults);
  9041. ;;
  9042. FC.sourceNormalizers = [];
  9043. FC.sourceFetchers = [];
  9044. var ajaxDefaults = {
  9045. dataType: 'json',
  9046. cache: false
  9047. };
  9048. var eventGUID = 1;
  9049. function EventManager() { // assumed to be a calendar
  9050. var t = this;
  9051. // exports
  9052. t.requestEvents = requestEvents;
  9053. t.reportEventChange = reportEventChange;
  9054. t.isFetchNeeded = isFetchNeeded;
  9055. t.fetchEvents = fetchEvents;
  9056. t.fetchEventSources = fetchEventSources;
  9057. t.refetchEvents = refetchEvents;
  9058. t.refetchEventSources = refetchEventSources;
  9059. t.getEventSources = getEventSources;
  9060. t.getEventSourceById = getEventSourceById;
  9061. t.addEventSource = addEventSource;
  9062. t.removeEventSource = removeEventSource;
  9063. t.removeEventSources = removeEventSources;
  9064. t.updateEvent = updateEvent;
  9065. t.updateEvents = updateEvents;
  9066. t.renderEvent = renderEvent;
  9067. t.renderEvents = renderEvents;
  9068. t.removeEvents = removeEvents;
  9069. t.clientEvents = clientEvents;
  9070. t.mutateEvent = mutateEvent;
  9071. t.normalizeEventDates = normalizeEventDates;
  9072. t.normalizeEventTimes = normalizeEventTimes;
  9073. // locals
  9074. var stickySource = { events: [] };
  9075. var sources = [ stickySource ];
  9076. var rangeStart, rangeEnd;
  9077. var pendingSourceCnt = 0; // outstanding fetch requests, max one per source
  9078. var cache = []; // holds events that have already been expanded
  9079. var prunedCache; // like cache, but only events that intersect with rangeStart/rangeEnd
  9080. $.each(
  9081. (t.options.events ? [ t.options.events ] : []).concat(t.options.eventSources || []),
  9082. function(i, sourceInput) {
  9083. var source = buildEventSource(sourceInput);
  9084. if (source) {
  9085. sources.push(source);
  9086. }
  9087. }
  9088. );
  9089. function requestEvents(start, end) {
  9090. if (!t.options.lazyFetching || isFetchNeeded(start, end)) {
  9091. return fetchEvents(start, end);
  9092. }
  9093. else {
  9094. return Promise.resolve(prunedCache);
  9095. }
  9096. }
  9097. function reportEventChange() {
  9098. prunedCache = filterEventsWithinRange(cache);
  9099. t.trigger('eventsReset', prunedCache);
  9100. }
  9101. function filterEventsWithinRange(events) {
  9102. var filteredEvents = [];
  9103. var i, event;
  9104. for (i = 0; i < events.length; i++) {
  9105. event = events[i];
  9106. if (
  9107. event.start.clone().stripZone() < rangeEnd &&
  9108. t.getEventEnd(event).stripZone() > rangeStart
  9109. ) {
  9110. filteredEvents.push(event);
  9111. }
  9112. }
  9113. return filteredEvents;
  9114. }
  9115. t.getEventCache = function() {
  9116. return cache;
  9117. };
  9118. t.getPrunedEventCache = function() {
  9119. return prunedCache;
  9120. };
  9121. /* Fetching
  9122. -----------------------------------------------------------------------------*/
  9123. // start and end are assumed to be unzoned
  9124. function isFetchNeeded(start, end) {
  9125. return !rangeStart || // nothing has been fetched yet?
  9126. start < rangeStart || end > rangeEnd; // is part of the new range outside of the old range?
  9127. }
  9128. function fetchEvents(start, end) {
  9129. rangeStart = start;
  9130. rangeEnd = end;
  9131. return refetchEvents();
  9132. }
  9133. // poorly named. fetches all sources with current `rangeStart` and `rangeEnd`.
  9134. function refetchEvents() {
  9135. return fetchEventSources(sources, 'reset');
  9136. }
  9137. // poorly named. fetches a subset of event sources.
  9138. function refetchEventSources(matchInputs) {
  9139. return fetchEventSources(getEventSourcesByMatchArray(matchInputs));
  9140. }
  9141. // expects an array of event source objects (the originals, not copies)
  9142. // `specialFetchType` is an optimization parameter that affects purging of the event cache.
  9143. function fetchEventSources(specificSources, specialFetchType) {
  9144. var i, source;
  9145. if (specialFetchType === 'reset') {
  9146. cache = [];
  9147. }
  9148. else if (specialFetchType !== 'add') {
  9149. cache = excludeEventsBySources(cache, specificSources);
  9150. }
  9151. for (i = 0; i < specificSources.length; i++) {
  9152. source = specificSources[i];
  9153. // already-pending sources have already been accounted for in pendingSourceCnt
  9154. if (source._status !== 'pending') {
  9155. pendingSourceCnt++;
  9156. }
  9157. source._fetchId = (source._fetchId || 0) + 1;
  9158. source._status = 'pending';
  9159. }
  9160. for (i = 0; i < specificSources.length; i++) {
  9161. source = specificSources[i];
  9162. tryFetchEventSource(source, source._fetchId);
  9163. }
  9164. if (pendingSourceCnt) {
  9165. return new Promise(function(resolve) {
  9166. t.one('eventsReceived', resolve); // will send prunedCache
  9167. });
  9168. }
  9169. else { // executed all synchronously, or no sources at all
  9170. return Promise.resolve(prunedCache);
  9171. }
  9172. }
  9173. // fetches an event source and processes its result ONLY if it is still the current fetch.
  9174. // caller is responsible for incrementing pendingSourceCnt first.
  9175. function tryFetchEventSource(source, fetchId) {
  9176. _fetchEventSource(source, function(eventInputs) {
  9177. var isArraySource = $.isArray(source.events);
  9178. var i, eventInput;
  9179. var abstractEvent;
  9180. if (
  9181. // is this the source's most recent fetch?
  9182. // if not, rely on an upcoming fetch of this source to decrement pendingSourceCnt
  9183. fetchId === source._fetchId &&
  9184. // event source no longer valid?
  9185. source._status !== 'rejected'
  9186. ) {
  9187. source._status = 'resolved';
  9188. if (eventInputs) {
  9189. for (i = 0; i < eventInputs.length; i++) {
  9190. eventInput = eventInputs[i];
  9191. if (isArraySource) { // array sources have already been convert to Event Objects
  9192. abstractEvent = eventInput;
  9193. }
  9194. else {
  9195. abstractEvent = buildEventFromInput(eventInput, source);
  9196. }
  9197. if (abstractEvent) { // not false (an invalid event)
  9198. cache.push.apply( // append
  9199. cache,
  9200. expandEvent(abstractEvent) // add individual expanded events to the cache
  9201. );
  9202. }
  9203. }
  9204. }
  9205. decrementPendingSourceCnt();
  9206. }
  9207. });
  9208. }
  9209. function rejectEventSource(source) {
  9210. var wasPending = source._status === 'pending';
  9211. source._status = 'rejected';
  9212. if (wasPending) {
  9213. decrementPendingSourceCnt();
  9214. }
  9215. }
  9216. function decrementPendingSourceCnt() {
  9217. pendingSourceCnt--;
  9218. if (!pendingSourceCnt) {
  9219. reportEventChange(cache); // updates prunedCache
  9220. t.trigger('eventsReceived', prunedCache);
  9221. }
  9222. }
  9223. function _fetchEventSource(source, callback) {
  9224. var i;
  9225. var fetchers = FC.sourceFetchers;
  9226. var res;
  9227. for (i=0; i<fetchers.length; i++) {
  9228. res = fetchers[i].call(
  9229. t, // this, the Calendar object
  9230. source,
  9231. rangeStart.clone(),
  9232. rangeEnd.clone(),
  9233. t.options.timezone,
  9234. callback
  9235. );
  9236. if (res === true) {
  9237. // the fetcher is in charge. made its own async request
  9238. return;
  9239. }
  9240. else if (typeof res == 'object') {
  9241. // the fetcher returned a new source. process it
  9242. _fetchEventSource(res, callback);
  9243. return;
  9244. }
  9245. }
  9246. var events = source.events;
  9247. if (events) {
  9248. if ($.isFunction(events)) {
  9249. t.pushLoading();
  9250. events.call(
  9251. t, // this, the Calendar object
  9252. rangeStart.clone(),
  9253. rangeEnd.clone(),
  9254. t.options.timezone,
  9255. function(events) {
  9256. callback(events);
  9257. t.popLoading();
  9258. }
  9259. );
  9260. }
  9261. else if ($.isArray(events)) {
  9262. callback(events);
  9263. }
  9264. else {
  9265. callback();
  9266. }
  9267. }else{
  9268. var url = source.url;
  9269. if (url) {
  9270. var success = source.success;
  9271. var error = source.error;
  9272. var complete = source.complete;
  9273. // retrieve any outbound GET/POST $.ajax data from the options
  9274. var customData;
  9275. if ($.isFunction(source.data)) {
  9276. // supplied as a function that returns a key/value object
  9277. customData = source.data();
  9278. }
  9279. else {
  9280. // supplied as a straight key/value object
  9281. customData = source.data;
  9282. }
  9283. // use a copy of the custom data so we can modify the parameters
  9284. // and not affect the passed-in object.
  9285. var data = $.extend({}, customData || {});
  9286. var startParam = firstDefined(source.startParam, t.options.startParam);
  9287. var endParam = firstDefined(source.endParam, t.options.endParam);
  9288. var timezoneParam = firstDefined(source.timezoneParam, t.options.timezoneParam);
  9289. if (startParam) {
  9290. data[startParam] = rangeStart.format();
  9291. }
  9292. if (endParam) {
  9293. data[endParam] = rangeEnd.format();
  9294. }
  9295. if (t.options.timezone && t.options.timezone != 'local') {
  9296. data[timezoneParam] = t.options.timezone;
  9297. }
  9298. t.pushLoading();
  9299. $.ajax($.extend({}, ajaxDefaults, source, {
  9300. data: data,
  9301. success: function(events) {
  9302. events = events || [];
  9303. var res = applyAll(success, this, arguments);
  9304. if ($.isArray(res)) {
  9305. events = res;
  9306. }
  9307. callback(events);
  9308. },
  9309. error: function() {
  9310. applyAll(error, this, arguments);
  9311. callback();
  9312. },
  9313. complete: function() {
  9314. applyAll(complete, this, arguments);
  9315. t.popLoading();
  9316. }
  9317. }));
  9318. }else{
  9319. callback();
  9320. }
  9321. }
  9322. }
  9323. /* Sources
  9324. -----------------------------------------------------------------------------*/
  9325. function addEventSource(sourceInput) {
  9326. var source = buildEventSource(sourceInput);
  9327. if (source) {
  9328. sources.push(source);
  9329. fetchEventSources([ source ], 'add'); // will eventually call reportEventChange
  9330. }
  9331. }
  9332. function buildEventSource(sourceInput) { // will return undefined if invalid source
  9333. var normalizers = FC.sourceNormalizers;
  9334. var source;
  9335. var i;
  9336. if ($.isFunction(sourceInput) || $.isArray(sourceInput)) {
  9337. source = { events: sourceInput };
  9338. }
  9339. else if (typeof sourceInput === 'string') {
  9340. source = { url: sourceInput };
  9341. }
  9342. else if (typeof sourceInput === 'object') {
  9343. source = $.extend({}, sourceInput); // shallow copy
  9344. }
  9345. if (source) {
  9346. // TODO: repeat code, same code for event classNames
  9347. if (source.className) {
  9348. if (typeof source.className === 'string') {
  9349. source.className = source.className.split(/\s+/);
  9350. }
  9351. // otherwise, assumed to be an array
  9352. }
  9353. else {
  9354. source.className = [];
  9355. }
  9356. // for array sources, we convert to standard Event Objects up front
  9357. if ($.isArray(source.events)) {
  9358. source.origArray = source.events; // for removeEventSource
  9359. source.events = $.map(source.events, function(eventInput) {
  9360. return buildEventFromInput(eventInput, source);
  9361. });
  9362. }
  9363. for (i=0; i<normalizers.length; i++) {
  9364. normalizers[i].call(t, source);
  9365. }
  9366. return source;
  9367. }
  9368. }
  9369. function removeEventSource(matchInput) {
  9370. removeSpecificEventSources(
  9371. getEventSourcesByMatch(matchInput)
  9372. );
  9373. }
  9374. // if called with no arguments, removes all.
  9375. function removeEventSources(matchInputs) {
  9376. if (matchInputs == null) {
  9377. removeSpecificEventSources(sources, true); // isAll=true
  9378. }
  9379. else {
  9380. removeSpecificEventSources(
  9381. getEventSourcesByMatchArray(matchInputs)
  9382. );
  9383. }
  9384. }
  9385. function removeSpecificEventSources(targetSources, isAll) {
  9386. var i;
  9387. // cancel pending requests
  9388. for (i = 0; i < targetSources.length; i++) {
  9389. rejectEventSource(targetSources[i]);
  9390. }
  9391. if (isAll) { // an optimization
  9392. sources = [];
  9393. cache = [];
  9394. }
  9395. else {
  9396. // remove from persisted source list
  9397. sources = $.grep(sources, function(source) {
  9398. for (i = 0; i < targetSources.length; i++) {
  9399. if (source === targetSources[i]) {
  9400. return false; // exclude
  9401. }
  9402. }
  9403. return true; // include
  9404. });
  9405. cache = excludeEventsBySources(cache, targetSources);
  9406. }
  9407. reportEventChange();
  9408. }
  9409. function getEventSources() {
  9410. return sources.slice(1); // returns a shallow copy of sources with stickySource removed
  9411. }
  9412. function getEventSourceById(id) {
  9413. return $.grep(sources, function(source) {
  9414. return source.id && source.id === id;
  9415. })[0];
  9416. }
  9417. // like getEventSourcesByMatch, but accepts multple match criteria (like multiple IDs)
  9418. function getEventSourcesByMatchArray(matchInputs) {
  9419. // coerce into an array
  9420. if (!matchInputs) {
  9421. matchInputs = [];
  9422. }
  9423. else if (!$.isArray(matchInputs)) {
  9424. matchInputs = [ matchInputs ];
  9425. }
  9426. var matchingSources = [];
  9427. var i;
  9428. // resolve raw inputs to real event source objects
  9429. for (i = 0; i < matchInputs.length; i++) {
  9430. matchingSources.push.apply( // append
  9431. matchingSources,
  9432. getEventSourcesByMatch(matchInputs[i])
  9433. );
  9434. }
  9435. return matchingSources;
  9436. }
  9437. // matchInput can either by a real event source object, an ID, or the function/URL for the source.
  9438. // returns an array of matching source objects.
  9439. function getEventSourcesByMatch(matchInput) {
  9440. var i, source;
  9441. // given an proper event source object
  9442. for (i = 0; i < sources.length; i++) {
  9443. source = sources[i];
  9444. if (source === matchInput) {
  9445. return [ source ];
  9446. }
  9447. }
  9448. // an ID match
  9449. source = getEventSourceById(matchInput);
  9450. if (source) {
  9451. return [ source ];
  9452. }
  9453. return $.grep(sources, function(source) {
  9454. return isSourcesEquivalent(matchInput, source);
  9455. });
  9456. }
  9457. function isSourcesEquivalent(source1, source2) {
  9458. return source1 && source2 && getSourcePrimitive(source1) == getSourcePrimitive(source2);
  9459. }
  9460. function getSourcePrimitive(source) {
  9461. return (
  9462. (typeof source === 'object') ? // a normalized event source?
  9463. (source.origArray || source.googleCalendarId || source.url || source.events) : // get the primitive
  9464. null
  9465. ) ||
  9466. source; // the given argument *is* the primitive
  9467. }
  9468. // util
  9469. // returns a filtered array without events that are part of any of the given sources
  9470. function excludeEventsBySources(specificEvents, specificSources) {
  9471. return $.grep(specificEvents, function(event) {
  9472. for (var i = 0; i < specificSources.length; i++) {
  9473. if (event.source === specificSources[i]) {
  9474. return false; // exclude
  9475. }
  9476. }
  9477. return true; // keep
  9478. });
  9479. }
  9480. /* Manipulation
  9481. -----------------------------------------------------------------------------*/
  9482. // Only ever called from the externally-facing API
  9483. function updateEvent(event) {
  9484. updateEvents([ event ]);
  9485. }
  9486. // Only ever called from the externally-facing API
  9487. function updateEvents(events) {
  9488. var i, event;
  9489. for (i = 0; i < events.length; i++) {
  9490. event = events[i];
  9491. // massage start/end values, even if date string values
  9492. event.start = t.moment(event.start);
  9493. if (event.end) {
  9494. event.end = t.moment(event.end);
  9495. }
  9496. else {
  9497. event.end = null;
  9498. }
  9499. mutateEvent(event, getMiscEventProps(event)); // will handle start/end/allDay normalization
  9500. }
  9501. reportEventChange(); // reports event modifications (so we can redraw)
  9502. }
  9503. // Returns a hash of misc event properties that should be copied over to related events.
  9504. function getMiscEventProps(event) {
  9505. var props = {};
  9506. $.each(event, function(name, val) {
  9507. if (isMiscEventPropName(name)) {
  9508. if (val !== undefined && isAtomic(val)) { // a defined non-object
  9509. props[name] = val;
  9510. }
  9511. }
  9512. });
  9513. return props;
  9514. }
  9515. // non-date-related, non-id-related, non-secret
  9516. function isMiscEventPropName(name) {
  9517. return !/^_|^(id|allDay|start|end)$/.test(name);
  9518. }
  9519. // returns the expanded events that were created
  9520. function renderEvent(eventInput, stick) {
  9521. return renderEvents([ eventInput ], stick);
  9522. }
  9523. // returns the expanded events that were created
  9524. function renderEvents(eventInputs, stick) {
  9525. var renderedEvents = [];
  9526. var renderableEvents;
  9527. var abstractEvent;
  9528. var i, j, event;
  9529. for (i = 0; i < eventInputs.length; i++) {
  9530. abstractEvent = buildEventFromInput(eventInputs[i]);
  9531. if (abstractEvent) { // not false (a valid input)
  9532. renderableEvents = expandEvent(abstractEvent);
  9533. for (j = 0; j < renderableEvents.length; j++) {
  9534. event = renderableEvents[j];
  9535. if (!event.source) {
  9536. if (stick) {
  9537. stickySource.events.push(event);
  9538. event.source = stickySource;
  9539. }
  9540. cache.push(event);
  9541. }
  9542. }
  9543. renderedEvents = renderedEvents.concat(renderableEvents);
  9544. }
  9545. }
  9546. if (renderedEvents.length) { // any new events rendered?
  9547. reportEventChange();
  9548. }
  9549. return renderedEvents;
  9550. }
  9551. function removeEvents(filter) {
  9552. var eventID;
  9553. var i;
  9554. if (filter == null) { // null or undefined. remove all events
  9555. filter = function() { return true; }; // will always match
  9556. }
  9557. else if (!$.isFunction(filter)) { // an event ID
  9558. eventID = filter + '';
  9559. filter = function(event) {
  9560. return event._id == eventID;
  9561. };
  9562. }
  9563. // Purge event(s) from our local cache
  9564. cache = $.grep(cache, filter, true); // inverse=true
  9565. // Remove events from array sources.
  9566. // This works because they have been converted to official Event Objects up front.
  9567. // (and as a result, event._id has been calculated).
  9568. for (i=0; i<sources.length; i++) {
  9569. if ($.isArray(sources[i].events)) {
  9570. sources[i].events = $.grep(sources[i].events, filter, true);
  9571. }
  9572. }
  9573. reportEventChange();
  9574. }
  9575. function clientEvents(filter) {
  9576. if ($.isFunction(filter)) {
  9577. return $.grep(cache, filter);
  9578. }
  9579. else if (filter != null) { // not null, not undefined. an event ID
  9580. filter += '';
  9581. return $.grep(cache, function(e) {
  9582. return e._id == filter;
  9583. });
  9584. }
  9585. return cache; // else, return all
  9586. }
  9587. // Makes sure all array event sources have their internal event objects
  9588. // converted over to the Calendar's current timezone.
  9589. t.rezoneArrayEventSources = function() {
  9590. var i;
  9591. var events;
  9592. var j;
  9593. for (i = 0; i < sources.length; i++) {
  9594. events = sources[i].events;
  9595. if ($.isArray(events)) {
  9596. for (j = 0; j < events.length; j++) {
  9597. rezoneEventDates(events[j]);
  9598. }
  9599. }
  9600. }
  9601. };
  9602. function rezoneEventDates(event) {
  9603. event.start = t.moment(event.start);
  9604. if (event.end) {
  9605. event.end = t.moment(event.end);
  9606. }
  9607. backupEventDates(event);
  9608. }
  9609. /* Event Normalization
  9610. -----------------------------------------------------------------------------*/
  9611. // Given a raw object with key/value properties, returns an "abstract" Event object.
  9612. // An "abstract" event is an event that, if recurring, will not have been expanded yet.
  9613. // Will return `false` when input is invalid.
  9614. // `source` is optional
  9615. function buildEventFromInput(input, source) {
  9616. var out = {};
  9617. var start, end;
  9618. var allDay;
  9619. if (t.options.eventDataTransform) {
  9620. input = t.options.eventDataTransform(input);
  9621. }
  9622. if (source && source.eventDataTransform) {
  9623. input = source.eventDataTransform(input);
  9624. }
  9625. // Copy all properties over to the resulting object.
  9626. // The special-case properties will be copied over afterwards.
  9627. $.extend(out, input);
  9628. if (source) {
  9629. out.source = source;
  9630. }
  9631. out._id = input._id || (input.id === undefined ? '_fc' + eventGUID++ : input.id + '');
  9632. if (input.className) {
  9633. if (typeof input.className == 'string') {
  9634. out.className = input.className.split(/\s+/);
  9635. }
  9636. else { // assumed to be an array
  9637. out.className = input.className;
  9638. }
  9639. }
  9640. else {
  9641. out.className = [];
  9642. }
  9643. start = input.start || input.date; // "date" is an alias for "start"
  9644. end = input.end;
  9645. // parse as a time (Duration) if applicable
  9646. if (isTimeString(start)) {
  9647. start = moment.duration(start);
  9648. }
  9649. if (isTimeString(end)) {
  9650. end = moment.duration(end);
  9651. }
  9652. if (input.dow || moment.isDuration(start) || moment.isDuration(end)) {
  9653. // the event is "abstract" (recurring) so don't calculate exact start/end dates just yet
  9654. out.start = start ? moment.duration(start) : null; // will be a Duration or null
  9655. out.end = end ? moment.duration(end) : null; // will be a Duration or null
  9656. out._recurring = true; // our internal marker
  9657. }
  9658. else {
  9659. if (start) {
  9660. start = t.moment(start);
  9661. if (!start.isValid()) {
  9662. return false;
  9663. }
  9664. }
  9665. if (end) {
  9666. end = t.moment(end);
  9667. if (!end.isValid()) {
  9668. end = null; // let defaults take over
  9669. }
  9670. }
  9671. allDay = input.allDay;
  9672. if (allDay === undefined) { // still undefined? fallback to default
  9673. allDay = firstDefined(
  9674. source ? source.allDayDefault : undefined,
  9675. t.options.allDayDefault
  9676. );
  9677. // still undefined? normalizeEventDates will calculate it
  9678. }
  9679. assignDatesToEvent(start, end, allDay, out);
  9680. }
  9681. t.normalizeEvent(out); // hook for external use. a prototype method
  9682. return out;
  9683. }
  9684. t.buildEventFromInput = buildEventFromInput;
  9685. // Normalizes and assigns the given dates to the given partially-formed event object.
  9686. // NOTE: mutates the given start/end moments. does not make a copy.
  9687. function assignDatesToEvent(start, end, allDay, event) {
  9688. event.start = start;
  9689. event.end = end;
  9690. event.allDay = allDay;
  9691. normalizeEventDates(event);
  9692. backupEventDates(event);
  9693. }
  9694. // Ensures proper values for allDay/start/end. Accepts an Event object, or a plain object with event-ish properties.
  9695. // NOTE: Will modify the given object.
  9696. function normalizeEventDates(eventProps) {
  9697. normalizeEventTimes(eventProps);
  9698. if (eventProps.end && !eventProps.end.isAfter(eventProps.start)) {
  9699. eventProps.end = null;
  9700. }
  9701. if (!eventProps.end) {
  9702. if (t.options.forceEventDuration) {
  9703. eventProps.end = t.getDefaultEventEnd(eventProps.allDay, eventProps.start);
  9704. }
  9705. else {
  9706. eventProps.end = null;
  9707. }
  9708. }
  9709. }
  9710. // Ensures the allDay property exists and the timeliness of the start/end dates are consistent
  9711. function normalizeEventTimes(eventProps) {
  9712. if (eventProps.allDay == null) {
  9713. eventProps.allDay = !(eventProps.start.hasTime() || (eventProps.end && eventProps.end.hasTime()));
  9714. }
  9715. if (eventProps.allDay) {
  9716. eventProps.start.stripTime();
  9717. if (eventProps.end) {
  9718. // TODO: consider nextDayThreshold here? If so, will require a lot of testing and adjustment
  9719. eventProps.end.stripTime();
  9720. }
  9721. }
  9722. else {
  9723. if (!eventProps.start.hasTime()) {
  9724. eventProps.start = t.applyTimezone(eventProps.start.time(0)); // will assign a 00:00 time
  9725. }
  9726. if (eventProps.end && !eventProps.end.hasTime()) {
  9727. eventProps.end = t.applyTimezone(eventProps.end.time(0)); // will assign a 00:00 time
  9728. }
  9729. }
  9730. }
  9731. // If the given event is a recurring event, break it down into an array of individual instances.
  9732. // If not a recurring event, return an array with the single original event.
  9733. // If given a falsy input (probably because of a failed buildEventFromInput call), returns an empty array.
  9734. // HACK: can override the recurring window by providing custom rangeStart/rangeEnd (for businessHours).
  9735. function expandEvent(abstractEvent, _rangeStart, _rangeEnd) {
  9736. var events = [];
  9737. var dowHash;
  9738. var dow;
  9739. var i;
  9740. var date;
  9741. var startTime, endTime;
  9742. var start, end;
  9743. var event;
  9744. _rangeStart = _rangeStart || rangeStart;
  9745. _rangeEnd = _rangeEnd || rangeEnd;
  9746. if (abstractEvent) {
  9747. if (abstractEvent._recurring) {
  9748. // make a boolean hash as to whether the event occurs on each day-of-week
  9749. if ((dow = abstractEvent.dow)) {
  9750. dowHash = {};
  9751. for (i = 0; i < dow.length; i++) {
  9752. dowHash[dow[i]] = true;
  9753. }
  9754. }
  9755. // iterate through every day in the current range
  9756. date = _rangeStart.clone().stripTime(); // holds the date of the current day
  9757. while (date.isBefore(_rangeEnd)) {
  9758. if (!dowHash || dowHash[date.day()]) { // if everyday, or this particular day-of-week
  9759. startTime = abstractEvent.start; // the stored start and end properties are times (Durations)
  9760. endTime = abstractEvent.end; // "
  9761. start = date.clone();
  9762. end = null;
  9763. if (startTime) {
  9764. start = start.time(startTime);
  9765. }
  9766. if (endTime) {
  9767. end = date.clone().time(endTime);
  9768. }
  9769. event = $.extend({}, abstractEvent); // make a copy of the original
  9770. assignDatesToEvent(
  9771. start, end,
  9772. !startTime && !endTime, // allDay?
  9773. event
  9774. );
  9775. events.push(event);
  9776. }
  9777. date.add(1, 'days');
  9778. }
  9779. }
  9780. else {
  9781. events.push(abstractEvent); // return the original event. will be a one-item array
  9782. }
  9783. }
  9784. return events;
  9785. }
  9786. t.expandEvent = expandEvent;
  9787. /* Event Modification Math
  9788. -----------------------------------------------------------------------------------------*/
  9789. // Modifies an event and all related events by applying the given properties.
  9790. // Special date-diffing logic is used for manipulation of dates.
  9791. // If `props` does not contain start/end dates, the updated values are assumed to be the event's current start/end.
  9792. // All date comparisons are done against the event's pristine _start and _end dates.
  9793. // Returns an object with delta information and a function to undo all operations.
  9794. // For making computations in a granularity greater than day/time, specify largeUnit.
  9795. // NOTE: The given `newProps` might be mutated for normalization purposes.
  9796. function mutateEvent(event, newProps, largeUnit) {
  9797. var miscProps = {};
  9798. var oldProps;
  9799. var clearEnd;
  9800. var startDelta;
  9801. var endDelta;
  9802. var durationDelta;
  9803. var undoFunc;
  9804. // diffs the dates in the appropriate way, returning a duration
  9805. function diffDates(date1, date0) { // date1 - date0
  9806. if (largeUnit) {
  9807. return diffByUnit(date1, date0, largeUnit);
  9808. }
  9809. else if (newProps.allDay) {
  9810. return diffDay(date1, date0);
  9811. }
  9812. else {
  9813. return diffDayTime(date1, date0);
  9814. }
  9815. }
  9816. newProps = newProps || {};
  9817. // normalize new date-related properties
  9818. if (!newProps.start) {
  9819. newProps.start = event.start.clone();
  9820. }
  9821. if (newProps.end === undefined) {
  9822. newProps.end = event.end ? event.end.clone() : null;
  9823. }
  9824. if (newProps.allDay == null) { // is null or undefined?
  9825. newProps.allDay = event.allDay;
  9826. }
  9827. normalizeEventDates(newProps);
  9828. // create normalized versions of the original props to compare against
  9829. // need a real end value, for diffing
  9830. oldProps = {
  9831. start: event._start.clone(),
  9832. end: event._end ? event._end.clone() : t.getDefaultEventEnd(event._allDay, event._start),
  9833. allDay: newProps.allDay // normalize the dates in the same regard as the new properties
  9834. };
  9835. normalizeEventDates(oldProps);
  9836. // need to clear the end date if explicitly changed to null
  9837. clearEnd = event._end !== null && newProps.end === null;
  9838. // compute the delta for moving the start date
  9839. startDelta = diffDates(newProps.start, oldProps.start);
  9840. // compute the delta for moving the end date
  9841. if (newProps.end) {
  9842. endDelta = diffDates(newProps.end, oldProps.end);
  9843. durationDelta = endDelta.subtract(startDelta);
  9844. }
  9845. else {
  9846. durationDelta = null;
  9847. }
  9848. // gather all non-date-related properties
  9849. $.each(newProps, function(name, val) {
  9850. if (isMiscEventPropName(name)) {
  9851. if (val !== undefined) {
  9852. miscProps[name] = val;
  9853. }
  9854. }
  9855. });
  9856. // apply the operations to the event and all related events
  9857. undoFunc = mutateEvents(
  9858. clientEvents(event._id), // get events with this ID
  9859. clearEnd,
  9860. newProps.allDay,
  9861. startDelta,
  9862. durationDelta,
  9863. miscProps
  9864. );
  9865. return {
  9866. dateDelta: startDelta,
  9867. durationDelta: durationDelta,
  9868. undo: undoFunc
  9869. };
  9870. }
  9871. // Modifies an array of events in the following ways (operations are in order):
  9872. // - clear the event's `end`
  9873. // - convert the event to allDay
  9874. // - add `dateDelta` to the start and end
  9875. // - add `durationDelta` to the event's duration
  9876. // - assign `miscProps` to the event
  9877. //
  9878. // Returns a function that can be called to undo all the operations.
  9879. //
  9880. // TODO: don't use so many closures. possible memory issues when lots of events with same ID.
  9881. //
  9882. function mutateEvents(events, clearEnd, allDay, dateDelta, durationDelta, miscProps) {
  9883. var isAmbigTimezone = t.getIsAmbigTimezone();
  9884. var undoFunctions = [];
  9885. // normalize zero-length deltas to be null
  9886. if (dateDelta && !dateDelta.valueOf()) { dateDelta = null; }
  9887. if (durationDelta && !durationDelta.valueOf()) { durationDelta = null; }
  9888. $.each(events, function(i, event) {
  9889. var oldProps;
  9890. var newProps;
  9891. // build an object holding all the old values, both date-related and misc.
  9892. // for the undo function.
  9893. oldProps = {
  9894. start: event.start.clone(),
  9895. end: event.end ? event.end.clone() : null,
  9896. allDay: event.allDay
  9897. };
  9898. $.each(miscProps, function(name) {
  9899. oldProps[name] = event[name];
  9900. });
  9901. // new date-related properties. work off the original date snapshot.
  9902. // ok to use references because they will be thrown away when backupEventDates is called.
  9903. newProps = {
  9904. start: event._start,
  9905. end: event._end,
  9906. allDay: allDay // normalize the dates in the same regard as the new properties
  9907. };
  9908. normalizeEventDates(newProps); // massages start/end/allDay
  9909. // strip or ensure the end date
  9910. if (clearEnd) {
  9911. newProps.end = null;
  9912. }
  9913. else if (durationDelta && !newProps.end) { // the duration translation requires an end date
  9914. newProps.end = t.getDefaultEventEnd(newProps.allDay, newProps.start);
  9915. }
  9916. if (dateDelta) {
  9917. newProps.start.add(dateDelta);
  9918. if (newProps.end) {
  9919. newProps.end.add(dateDelta);
  9920. }
  9921. }
  9922. if (durationDelta) {
  9923. newProps.end.add(durationDelta); // end already ensured above
  9924. }
  9925. // if the dates have changed, and we know it is impossible to recompute the
  9926. // timezone offsets, strip the zone.
  9927. if (
  9928. isAmbigTimezone &&
  9929. !newProps.allDay &&
  9930. (dateDelta || durationDelta)
  9931. ) {
  9932. newProps.start.stripZone();
  9933. if (newProps.end) {
  9934. newProps.end.stripZone();
  9935. }
  9936. }
  9937. $.extend(event, miscProps, newProps); // copy over misc props, then date-related props
  9938. backupEventDates(event); // regenerate internal _start/_end/_allDay
  9939. undoFunctions.push(function() {
  9940. $.extend(event, oldProps);
  9941. backupEventDates(event); // regenerate internal _start/_end/_allDay
  9942. });
  9943. });
  9944. return function() {
  9945. for (var i = 0; i < undoFunctions.length; i++) {
  9946. undoFunctions[i]();
  9947. }
  9948. };
  9949. }
  9950. }
  9951. // returns an undo function
  9952. Calendar.prototype.mutateSeg = function(seg, newProps) {
  9953. return this.mutateEvent(seg.event, newProps);
  9954. };
  9955. // hook for external libs to manipulate event properties upon creation.
  9956. // should manipulate the event in-place.
  9957. Calendar.prototype.normalizeEvent = function(event) {
  9958. };
  9959. // Does the given span (start, end, and other location information)
  9960. // fully contain the other?
  9961. Calendar.prototype.spanContainsSpan = function(outerSpan, innerSpan) {
  9962. var eventStart = outerSpan.start.clone().stripZone();
  9963. var eventEnd = this.getEventEnd(outerSpan).stripZone();
  9964. return innerSpan.start >= eventStart && innerSpan.end <= eventEnd;
  9965. };
  9966. // Returns a list of events that the given event should be compared against when being considered for a move to
  9967. // the specified span. Attached to the Calendar's prototype because EventManager is a mixin for a Calendar.
  9968. Calendar.prototype.getPeerEvents = function(span, event) {
  9969. var cache = this.getEventCache();
  9970. var peerEvents = [];
  9971. var i, otherEvent;
  9972. for (i = 0; i < cache.length; i++) {
  9973. otherEvent = cache[i];
  9974. if (
  9975. !event ||
  9976. event._id !== otherEvent._id // don't compare the event to itself or other related [repeating] events
  9977. ) {
  9978. peerEvents.push(otherEvent);
  9979. }
  9980. }
  9981. return peerEvents;
  9982. };
  9983. // updates the "backup" properties, which are preserved in order to compute diffs later on.
  9984. function backupEventDates(event) {
  9985. event._allDay = event.allDay;
  9986. event._start = event.start.clone();
  9987. event._end = event.end ? event.end.clone() : null;
  9988. }
  9989. /* Overlapping / Constraining
  9990. -----------------------------------------------------------------------------------------*/
  9991. // Determines if the given event can be relocated to the given span (unzoned start/end with other misc data)
  9992. Calendar.prototype.isEventSpanAllowed = function(span, event) {
  9993. var source = event.source || {};
  9994. var constraint = firstDefined(
  9995. event.constraint,
  9996. source.constraint,
  9997. this.options.eventConstraint
  9998. );
  9999. var overlap = firstDefined(
  10000. event.overlap,
  10001. source.overlap,
  10002. this.options.eventOverlap
  10003. );
  10004. return this.isSpanAllowed(span, constraint, overlap, event) &&
  10005. (!this.options.eventAllow || this.options.eventAllow(span, event) !== false);
  10006. };
  10007. // Determines if an external event can be relocated to the given span (unzoned start/end with other misc data)
  10008. Calendar.prototype.isExternalSpanAllowed = function(eventSpan, eventLocation, eventProps) {
  10009. var eventInput;
  10010. var event;
  10011. // note: very similar logic is in View's reportExternalDrop
  10012. if (eventProps) {
  10013. eventInput = $.extend({}, eventProps, eventLocation);
  10014. event = this.expandEvent(
  10015. this.buildEventFromInput(eventInput)
  10016. )[0];
  10017. }
  10018. if (event) {
  10019. return this.isEventSpanAllowed(eventSpan, event);
  10020. }
  10021. else { // treat it as a selection
  10022. return this.isSelectionSpanAllowed(eventSpan);
  10023. }
  10024. };
  10025. // Determines the given span (unzoned start/end with other misc data) can be selected.
  10026. Calendar.prototype.isSelectionSpanAllowed = function(span) {
  10027. return this.isSpanAllowed(span, this.options.selectConstraint, this.options.selectOverlap) &&
  10028. (!this.options.selectAllow || this.options.selectAllow(span) !== false);
  10029. };
  10030. // Returns true if the given span (caused by an event drop/resize or a selection) is allowed to exist
  10031. // according to the constraint/overlap settings.
  10032. // `event` is not required if checking a selection.
  10033. Calendar.prototype.isSpanAllowed = function(span, constraint, overlap, event) {
  10034. var constraintEvents;
  10035. var anyContainment;
  10036. var peerEvents;
  10037. var i, peerEvent;
  10038. var peerOverlap;
  10039. // the range must be fully contained by at least one of produced constraint events
  10040. if (constraint != null) {
  10041. // not treated as an event! intermediate data structure
  10042. // TODO: use ranges in the future
  10043. constraintEvents = this.constraintToEvents(constraint);
  10044. if (constraintEvents) { // not invalid
  10045. anyContainment = false;
  10046. for (i = 0; i < constraintEvents.length; i++) {
  10047. if (this.spanContainsSpan(constraintEvents[i], span)) {
  10048. anyContainment = true;
  10049. break;
  10050. }
  10051. }
  10052. if (!anyContainment) {
  10053. return false;
  10054. }
  10055. }
  10056. }
  10057. peerEvents = this.getPeerEvents(span, event);
  10058. for (i = 0; i < peerEvents.length; i++) {
  10059. peerEvent = peerEvents[i];
  10060. // there needs to be an actual intersection before disallowing anything
  10061. if (this.eventIntersectsRange(peerEvent, span)) {
  10062. // evaluate overlap for the given range and short-circuit if necessary
  10063. if (overlap === false) {
  10064. return false;
  10065. }
  10066. // if the event's overlap is a test function, pass the peer event in question as the first param
  10067. else if (typeof overlap === 'function' && !overlap(peerEvent, event)) {
  10068. return false;
  10069. }
  10070. // if we are computing if the given range is allowable for an event, consider the other event's
  10071. // EventObject-specific or Source-specific `overlap` property
  10072. if (event) {
  10073. peerOverlap = firstDefined(
  10074. peerEvent.overlap,
  10075. (peerEvent.source || {}).overlap
  10076. // we already considered the global `eventOverlap`
  10077. );
  10078. if (peerOverlap === false) {
  10079. return false;
  10080. }
  10081. // if the peer event's overlap is a test function, pass the subject event as the first param
  10082. if (typeof peerOverlap === 'function' && !peerOverlap(event, peerEvent)) {
  10083. return false;
  10084. }
  10085. }
  10086. }
  10087. }
  10088. return true;
  10089. };
  10090. // Given an event input from the API, produces an array of event objects. Possible event inputs:
  10091. // 'businessHours'
  10092. // An event ID (number or string)
  10093. // An object with specific start/end dates or a recurring event (like what businessHours accepts)
  10094. Calendar.prototype.constraintToEvents = function(constraintInput) {
  10095. if (constraintInput === 'businessHours') {
  10096. return this.getCurrentBusinessHourEvents();
  10097. }
  10098. if (typeof constraintInput === 'object') {
  10099. if (constraintInput.start != null) { // needs to be event-like input
  10100. return this.expandEvent(this.buildEventFromInput(constraintInput));
  10101. }
  10102. else {
  10103. return null; // invalid
  10104. }
  10105. }
  10106. return this.clientEvents(constraintInput); // probably an ID
  10107. };
  10108. // Does the event's date range intersect with the given range?
  10109. // start/end already assumed to have stripped zones :(
  10110. Calendar.prototype.eventIntersectsRange = function(event, range) {
  10111. var eventStart = event.start.clone().stripZone();
  10112. var eventEnd = this.getEventEnd(event).stripZone();
  10113. return range.start < eventEnd && range.end > eventStart;
  10114. };
  10115. /* Business Hours
  10116. -----------------------------------------------------------------------------------------*/
  10117. var BUSINESS_HOUR_EVENT_DEFAULTS = {
  10118. id: '_fcBusinessHours', // will relate events from different calls to expandEvent
  10119. start: '09:00',
  10120. end: '17:00',
  10121. dow: [ 1, 2, 3, 4, 5 ], // monday - friday
  10122. rendering: 'inverse-background'
  10123. // classNames are defined in businessHoursSegClasses
  10124. };
  10125. // Return events objects for business hours within the current view.
  10126. // Abuse of our event system :(
  10127. Calendar.prototype.getCurrentBusinessHourEvents = function(wholeDay) {
  10128. return this.computeBusinessHourEvents(wholeDay, this.options.businessHours);
  10129. };
  10130. // Given a raw input value from options, return events objects for business hours within the current view.
  10131. Calendar.prototype.computeBusinessHourEvents = function(wholeDay, input) {
  10132. if (input === true) {
  10133. return this.expandBusinessHourEvents(wholeDay, [ {} ]);
  10134. }
  10135. else if ($.isPlainObject(input)) {
  10136. return this.expandBusinessHourEvents(wholeDay, [ input ]);
  10137. }
  10138. else if ($.isArray(input)) {
  10139. return this.expandBusinessHourEvents(wholeDay, input, true);
  10140. }
  10141. else {
  10142. return [];
  10143. }
  10144. };
  10145. // inputs expected to be an array of objects.
  10146. // if ignoreNoDow is true, will ignore entries that don't specify a day-of-week (dow) key.
  10147. Calendar.prototype.expandBusinessHourEvents = function(wholeDay, inputs, ignoreNoDow) {
  10148. var view = this.getView();
  10149. var events = [];
  10150. var i, input;
  10151. for (i = 0; i < inputs.length; i++) {
  10152. input = inputs[i];
  10153. if (ignoreNoDow && !input.dow) {
  10154. continue;
  10155. }
  10156. // give defaults. will make a copy
  10157. input = $.extend({}, BUSINESS_HOUR_EVENT_DEFAULTS, input);
  10158. // if a whole-day series is requested, clear the start/end times
  10159. if (wholeDay) {
  10160. input.start = null;
  10161. input.end = null;
  10162. }
  10163. events.push.apply(events, // append
  10164. this.expandEvent(
  10165. this.buildEventFromInput(input),
  10166. view.start,
  10167. view.end
  10168. )
  10169. );
  10170. }
  10171. return events;
  10172. };
  10173. ;;
  10174. /* An abstract class for the "basic" views, as well as month view. Renders one or more rows of day cells.
  10175. ----------------------------------------------------------------------------------------------------------------------*/
  10176. // It is a manager for a DayGrid subcomponent, which does most of the heavy lifting.
  10177. // It is responsible for managing width/height.
  10178. var BasicView = FC.BasicView = View.extend({
  10179. scroller: null,
  10180. dayGridClass: DayGrid, // class the dayGrid will be instantiated from (overridable by subclasses)
  10181. dayGrid: null, // the main subcomponent that does most of the heavy lifting
  10182. dayNumbersVisible: false, // display day numbers on each day cell?
  10183. colWeekNumbersVisible: false, // display week numbers along the side?
  10184. cellWeekNumbersVisible: false, // display week numbers in day cell?
  10185. weekNumberWidth: null, // width of all the week-number cells running down the side
  10186. headContainerEl: null, // div that hold's the dayGrid's rendered date header
  10187. headRowEl: null, // the fake row element of the day-of-week header
  10188. initialize: function() {
  10189. this.dayGrid = this.instantiateDayGrid();
  10190. this.scroller = new Scroller({
  10191. overflowX: 'hidden',
  10192. overflowY: 'auto'
  10193. });
  10194. },
  10195. // Generates the DayGrid object this view needs. Draws from this.dayGridClass
  10196. instantiateDayGrid: function() {
  10197. // generate a subclass on the fly with BasicView-specific behavior
  10198. // TODO: cache this subclass
  10199. var subclass = this.dayGridClass.extend(basicDayGridMethods);
  10200. return new subclass(this);
  10201. },
  10202. // Sets the display range and computes all necessary dates
  10203. setRange: function(range) {
  10204. View.prototype.setRange.call(this, range); // call the super-method
  10205. this.dayGrid.breakOnWeeks = /year|month|week/.test(this.intervalUnit); // do before setRange
  10206. this.dayGrid.setRange(range);
  10207. },
  10208. // Compute the value to feed into setRange. Overrides superclass.
  10209. computeRange: function(date) {
  10210. var range = View.prototype.computeRange.call(this, date); // get value from the super-method
  10211. // year and month views should be aligned with weeks. this is already done for week
  10212. if (/year|month/.test(range.intervalUnit)) {
  10213. range.start.startOf('week');
  10214. range.start = this.skipHiddenDays(range.start);
  10215. // make end-of-week if not already
  10216. if (range.end.weekday()) {
  10217. range.end.add(1, 'week').startOf('week');
  10218. range.end = this.skipHiddenDays(range.end, -1, true); // exclusively move backwards
  10219. }
  10220. }
  10221. return range;
  10222. },
  10223. // Renders the view into `this.el`, which should already be assigned
  10224. renderDates: function() {
  10225. this.dayNumbersVisible = this.dayGrid.rowCnt > 1; // TODO: make grid responsible
  10226. if (this.opt('weekNumbers')) {
  10227. if (this.opt('weekNumbersWithinDays')) {
  10228. this.cellWeekNumbersVisible = true;
  10229. this.colWeekNumbersVisible = false;
  10230. }
  10231. else {
  10232. this.cellWeekNumbersVisible = false;
  10233. this.colWeekNumbersVisible = true;
  10234. };
  10235. }
  10236. this.dayGrid.numbersVisible = this.dayNumbersVisible ||
  10237. this.cellWeekNumbersVisible || this.colWeekNumbersVisible;
  10238. this.el.addClass('fc-basic-view').html(this.renderSkeletonHtml());
  10239. this.renderHead();
  10240. this.scroller.render();
  10241. var dayGridContainerEl = this.scroller.el.addClass('fc-day-grid-container');
  10242. var dayGridEl = $('<div class="fc-day-grid" />').appendTo(dayGridContainerEl);
  10243. this.el.find('.fc-body > tr > td').append(dayGridContainerEl);
  10244. this.dayGrid.setElement(dayGridEl);
  10245. this.dayGrid.renderDates(this.hasRigidRows());
  10246. },
  10247. // render the day-of-week headers
  10248. renderHead: function() {
  10249. this.headContainerEl =
  10250. this.el.find('.fc-head-container')
  10251. .html(this.dayGrid.renderHeadHtml());
  10252. this.headRowEl = this.headContainerEl.find('.fc-row');
  10253. },
  10254. // Unrenders the content of the view. Since we haven't separated skeleton rendering from date rendering,
  10255. // always completely kill the dayGrid's rendering.
  10256. unrenderDates: function() {
  10257. this.dayGrid.unrenderDates();
  10258. this.dayGrid.removeElement();
  10259. this.scroller.destroy();
  10260. },
  10261. renderBusinessHours: function() {
  10262. this.dayGrid.renderBusinessHours();
  10263. },
  10264. unrenderBusinessHours: function() {
  10265. this.dayGrid.unrenderBusinessHours();
  10266. },
  10267. // Builds the HTML skeleton for the view.
  10268. // The day-grid component will render inside of a container defined by this HTML.
  10269. renderSkeletonHtml: function() {
  10270. return '' +
  10271. '<table>' +
  10272. '<thead class="fc-head">' +
  10273. '<tr>' +
  10274. '<td class="fc-head-container ' + this.widgetHeaderClass + '"></td>' +
  10275. '</tr>' +
  10276. '</thead>' +
  10277. '<tbody class="fc-body">' +
  10278. '<tr>' +
  10279. '<td class="' + this.widgetContentClass + '"></td>' +
  10280. '</tr>' +
  10281. '</tbody>' +
  10282. '</table>';
  10283. },
  10284. // Generates an HTML attribute string for setting the width of the week number column, if it is known
  10285. weekNumberStyleAttr: function() {
  10286. if (this.weekNumberWidth !== null) {
  10287. return 'style="width:' + this.weekNumberWidth + 'px"';
  10288. }
  10289. return '';
  10290. },
  10291. // Determines whether each row should have a constant height
  10292. hasRigidRows: function() {
  10293. var eventLimit = this.opt('eventLimit');
  10294. return eventLimit && typeof eventLimit !== 'number';
  10295. },
  10296. /* Dimensions
  10297. ------------------------------------------------------------------------------------------------------------------*/
  10298. // Refreshes the horizontal dimensions of the view
  10299. updateWidth: function() {
  10300. if (this.colWeekNumbersVisible) {
  10301. // Make sure all week number cells running down the side have the same width.
  10302. // Record the width for cells created later.
  10303. this.weekNumberWidth = matchCellWidths(
  10304. this.el.find('.fc-week-number')
  10305. );
  10306. }
  10307. },
  10308. // Adjusts the vertical dimensions of the view to the specified values
  10309. setHeight: function(totalHeight, isAuto) {
  10310. var eventLimit = this.opt('eventLimit');
  10311. var scrollerHeight;
  10312. var scrollbarWidths;
  10313. // reset all heights to be natural
  10314. this.scroller.clear();
  10315. uncompensateScroll(this.headRowEl);
  10316. this.dayGrid.removeSegPopover(); // kill the "more" popover if displayed
  10317. // is the event limit a constant level number?
  10318. if (eventLimit && typeof eventLimit === 'number') {
  10319. this.dayGrid.limitRows(eventLimit); // limit the levels first so the height can redistribute after
  10320. }
  10321. // distribute the height to the rows
  10322. // (totalHeight is a "recommended" value if isAuto)
  10323. scrollerHeight = this.computeScrollerHeight(totalHeight);
  10324. this.setGridHeight(scrollerHeight, isAuto);
  10325. // is the event limit dynamically calculated?
  10326. if (eventLimit && typeof eventLimit !== 'number') {
  10327. this.dayGrid.limitRows(eventLimit); // limit the levels after the grid's row heights have been set
  10328. }
  10329. if (!isAuto) { // should we force dimensions of the scroll container?
  10330. this.scroller.setHeight(scrollerHeight);
  10331. scrollbarWidths = this.scroller.getScrollbarWidths();
  10332. if (scrollbarWidths.left || scrollbarWidths.right) { // using scrollbars?
  10333. compensateScroll(this.headRowEl, scrollbarWidths);
  10334. // doing the scrollbar compensation might have created text overflow which created more height. redo
  10335. scrollerHeight = this.computeScrollerHeight(totalHeight);
  10336. this.scroller.setHeight(scrollerHeight);
  10337. }
  10338. // guarantees the same scrollbar widths
  10339. this.scroller.lockOverflow(scrollbarWidths);
  10340. }
  10341. },
  10342. // given a desired total height of the view, returns what the height of the scroller should be
  10343. computeScrollerHeight: function(totalHeight) {
  10344. return totalHeight -
  10345. subtractInnerElHeight(this.el, this.scroller.el); // everything that's NOT the scroller
  10346. },
  10347. // Sets the height of just the DayGrid component in this view
  10348. setGridHeight: function(height, isAuto) {
  10349. if (isAuto) {
  10350. undistributeHeight(this.dayGrid.rowEls); // let the rows be their natural height with no expanding
  10351. }
  10352. else {
  10353. distributeHeight(this.dayGrid.rowEls, height, true); // true = compensate for height-hogging rows
  10354. }
  10355. },
  10356. /* Scroll
  10357. ------------------------------------------------------------------------------------------------------------------*/
  10358. computeInitialScroll: function() {
  10359. return { top: 0 };
  10360. },
  10361. queryScroll: function() {
  10362. return { top: this.scroller.getScrollTop() };
  10363. },
  10364. setScroll: function(scroll) {
  10365. this.scroller.setScrollTop(scroll.top);
  10366. },
  10367. /* Hit Areas
  10368. ------------------------------------------------------------------------------------------------------------------*/
  10369. // forward all hit-related method calls to dayGrid
  10370. hitsNeeded: function() {
  10371. this.dayGrid.hitsNeeded();
  10372. },
  10373. hitsNotNeeded: function() {
  10374. this.dayGrid.hitsNotNeeded();
  10375. },
  10376. prepareHits: function() {
  10377. this.dayGrid.prepareHits();
  10378. },
  10379. releaseHits: function() {
  10380. this.dayGrid.releaseHits();
  10381. },
  10382. queryHit: function(left, top) {
  10383. return this.dayGrid.queryHit(left, top);
  10384. },
  10385. getHitSpan: function(hit) {
  10386. return this.dayGrid.getHitSpan(hit);
  10387. },
  10388. getHitEl: function(hit) {
  10389. return this.dayGrid.getHitEl(hit);
  10390. },
  10391. /* Events
  10392. ------------------------------------------------------------------------------------------------------------------*/
  10393. // Renders the given events onto the view and populates the segments array
  10394. renderEvents: function(events) {
  10395. this.dayGrid.renderEvents(events);
  10396. this.updateHeight(); // must compensate for events that overflow the row
  10397. },
  10398. // Retrieves all segment objects that are rendered in the view
  10399. getEventSegs: function() {
  10400. return this.dayGrid.getEventSegs();
  10401. },
  10402. // Unrenders all event elements and clears internal segment data
  10403. unrenderEvents: function() {
  10404. this.dayGrid.unrenderEvents();
  10405. // we DON'T need to call updateHeight() because
  10406. // a renderEvents() call always happens after this, which will eventually call updateHeight()
  10407. },
  10408. /* Dragging (for both events and external elements)
  10409. ------------------------------------------------------------------------------------------------------------------*/
  10410. // A returned value of `true` signals that a mock "helper" event has been rendered.
  10411. renderDrag: function(dropLocation, seg) {
  10412. return this.dayGrid.renderDrag(dropLocation, seg);
  10413. },
  10414. unrenderDrag: function() {
  10415. this.dayGrid.unrenderDrag();
  10416. },
  10417. /* Selection
  10418. ------------------------------------------------------------------------------------------------------------------*/
  10419. // Renders a visual indication of a selection
  10420. renderSelection: function(span) {
  10421. this.dayGrid.renderSelection(span);
  10422. },
  10423. // Unrenders a visual indications of a selection
  10424. unrenderSelection: function() {
  10425. this.dayGrid.unrenderSelection();
  10426. }
  10427. });
  10428. // Methods that will customize the rendering behavior of the BasicView's dayGrid
  10429. var basicDayGridMethods = {
  10430. // Generates the HTML that will go before the day-of week header cells
  10431. renderHeadIntroHtml: function() {
  10432. var view = this.view;
  10433. if (view.colWeekNumbersVisible) {
  10434. return '' +
  10435. '<th class="fc-week-number ' + view.widgetHeaderClass + '" ' + view.weekNumberStyleAttr() + '>' +
  10436. '<span>' + // needed for matchCellWidths
  10437. htmlEscape(view.opt('weekNumberTitle')) +
  10438. '</span>' +
  10439. '</th>';
  10440. }
  10441. return '';
  10442. },
  10443. // Generates the HTML that will go before content-skeleton cells that display the day/week numbers
  10444. renderNumberIntroHtml: function(row) {
  10445. var view = this.view;
  10446. var weekStart = this.getCellDate(row, 0);
  10447. if (view.colWeekNumbersVisible) {
  10448. return '' +
  10449. '<td class="fc-week-number" ' + view.weekNumberStyleAttr() + '>' +
  10450. view.buildGotoAnchorHtml( // aside from link, important for matchCellWidths
  10451. { date: weekStart, type: 'week', forceOff: this.colCnt === 1 },
  10452. weekStart.format('w') // inner HTML
  10453. ) +
  10454. '</td>';
  10455. }
  10456. return '';
  10457. },
  10458. // Generates the HTML that goes before the day bg cells for each day-row
  10459. renderBgIntroHtml: function() {
  10460. var view = this.view;
  10461. if (view.colWeekNumbersVisible) {
  10462. return '<td class="fc-week-number ' + view.widgetContentClass + '" ' +
  10463. view.weekNumberStyleAttr() + '></td>';
  10464. }
  10465. return '';
  10466. },
  10467. // Generates the HTML that goes before every other type of row generated by DayGrid.
  10468. // Affects helper-skeleton and highlight-skeleton rows.
  10469. renderIntroHtml: function() {
  10470. var view = this.view;
  10471. if (view.colWeekNumbersVisible) {
  10472. return '<td class="fc-week-number" ' + view.weekNumberStyleAttr() + '></td>';
  10473. }
  10474. return '';
  10475. }
  10476. };
  10477. ;;
  10478. /* A month view with day cells running in rows (one-per-week) and columns
  10479. ----------------------------------------------------------------------------------------------------------------------*/
  10480. var MonthView = FC.MonthView = BasicView.extend({
  10481. // Produces information about what range to display
  10482. computeRange: function(date) {
  10483. var range = BasicView.prototype.computeRange.call(this, date); // get value from super-method
  10484. var rowCnt;
  10485. // ensure 6 weeks
  10486. if (this.isFixedWeeks()) {
  10487. rowCnt = Math.ceil(range.end.diff(range.start, 'weeks', true)); // could be partial weeks due to hiddenDays
  10488. range.end.add(6 - rowCnt, 'weeks');
  10489. }
  10490. return range;
  10491. },
  10492. // Overrides the default BasicView behavior to have special multi-week auto-height logic
  10493. setGridHeight: function(height, isAuto) {
  10494. // if auto, make the height of each row the height that it would be if there were 6 weeks
  10495. if (isAuto) {
  10496. height *= this.rowCnt / 6;
  10497. }
  10498. distributeHeight(this.dayGrid.rowEls, height, !isAuto); // if auto, don't compensate for height-hogging rows
  10499. },
  10500. isFixedWeeks: function() {
  10501. return this.opt('fixedWeekCount');
  10502. }
  10503. });
  10504. ;;
  10505. fcViews.basic = {
  10506. 'class': BasicView
  10507. };
  10508. fcViews.basicDay = {
  10509. type: 'basic',
  10510. duration: { days: 1 }
  10511. };
  10512. fcViews.basicWeek = {
  10513. type: 'basic',
  10514. duration: { weeks: 1 }
  10515. };
  10516. fcViews.month = {
  10517. 'class': MonthView,
  10518. duration: { months: 1 }, // important for prev/next
  10519. defaults: {
  10520. fixedWeekCount: true
  10521. }
  10522. };
  10523. ;;
  10524. /* An abstract class for all agenda-related views. Displays one more columns with time slots running vertically.
  10525. ----------------------------------------------------------------------------------------------------------------------*/
  10526. // Is a manager for the TimeGrid subcomponent and possibly the DayGrid subcomponent (if allDaySlot is on).
  10527. // Responsible for managing width/height.
  10528. var AgendaView = FC.AgendaView = View.extend({
  10529. scroller: null,
  10530. timeGridClass: TimeGrid, // class used to instantiate the timeGrid. subclasses can override
  10531. timeGrid: null, // the main time-grid subcomponent of this view
  10532. dayGridClass: DayGrid, // class used to instantiate the dayGrid. subclasses can override
  10533. dayGrid: null, // the "all-day" subcomponent. if all-day is turned off, this will be null
  10534. axisWidth: null, // the width of the time axis running down the side
  10535. headContainerEl: null, // div that hold's the timeGrid's rendered date header
  10536. noScrollRowEls: null, // set of fake row elements that must compensate when scroller has scrollbars
  10537. // when the time-grid isn't tall enough to occupy the given height, we render an <hr> underneath
  10538. bottomRuleEl: null,
  10539. initialize: function() {
  10540. this.timeGrid = this.instantiateTimeGrid();
  10541. if (this.opt('allDaySlot')) { // should we display the "all-day" area?
  10542. this.dayGrid = this.instantiateDayGrid(); // the all-day subcomponent of this view
  10543. }
  10544. this.scroller = new Scroller({
  10545. overflowX: 'hidden',
  10546. overflowY: 'auto'
  10547. });
  10548. },
  10549. // Instantiates the TimeGrid object this view needs. Draws from this.timeGridClass
  10550. instantiateTimeGrid: function() {
  10551. var subclass = this.timeGridClass.extend(agendaTimeGridMethods);
  10552. return new subclass(this);
  10553. },
  10554. // Instantiates the DayGrid object this view might need. Draws from this.dayGridClass
  10555. instantiateDayGrid: function() {
  10556. var subclass = this.dayGridClass.extend(agendaDayGridMethods);
  10557. return new subclass(this);
  10558. },
  10559. /* Rendering
  10560. ------------------------------------------------------------------------------------------------------------------*/
  10561. // Sets the display range and computes all necessary dates
  10562. setRange: function(range) {
  10563. View.prototype.setRange.call(this, range); // call the super-method
  10564. this.timeGrid.setRange(range);
  10565. if (this.dayGrid) {
  10566. this.dayGrid.setRange(range);
  10567. }
  10568. },
  10569. // Renders the view into `this.el`, which has already been assigned
  10570. renderDates: function() {
  10571. this.el.addClass('fc-agenda-view').html(this.renderSkeletonHtml());
  10572. this.renderHead();
  10573. this.scroller.render();
  10574. var timeGridWrapEl = this.scroller.el.addClass('fc-time-grid-container');
  10575. var timeGridEl = $('<div class="fc-time-grid" />').appendTo(timeGridWrapEl);
  10576. this.el.find('.fc-body > tr > td').append(timeGridWrapEl);
  10577. this.timeGrid.setElement(timeGridEl);
  10578. this.timeGrid.renderDates();
  10579. // the <hr> that sometimes displays under the time-grid
  10580. this.bottomRuleEl = $('<hr class="fc-divider ' + this.widgetHeaderClass + '"/>')
  10581. .appendTo(this.timeGrid.el); // inject it into the time-grid
  10582. if (this.dayGrid) {
  10583. this.dayGrid.setElement(this.el.find('.fc-day-grid'));
  10584. this.dayGrid.renderDates();
  10585. // have the day-grid extend it's coordinate area over the <hr> dividing the two grids
  10586. this.dayGrid.bottomCoordPadding = this.dayGrid.el.next('hr').outerHeight();
  10587. }
  10588. this.noScrollRowEls = this.el.find('.fc-row:not(.fc-scroller *)'); // fake rows not within the scroller
  10589. },
  10590. // render the day-of-week headers
  10591. renderHead: function() {
  10592. this.headContainerEl =
  10593. this.el.find('.fc-head-container')
  10594. .html(this.timeGrid.renderHeadHtml());
  10595. },
  10596. // Unrenders the content of the view. Since we haven't separated skeleton rendering from date rendering,
  10597. // always completely kill each grid's rendering.
  10598. unrenderDates: function() {
  10599. this.timeGrid.unrenderDates();
  10600. this.timeGrid.removeElement();
  10601. if (this.dayGrid) {
  10602. this.dayGrid.unrenderDates();
  10603. this.dayGrid.removeElement();
  10604. }
  10605. this.scroller.destroy();
  10606. },
  10607. // Builds the HTML skeleton for the view.
  10608. // The day-grid and time-grid components will render inside containers defined by this HTML.
  10609. renderSkeletonHtml: function() {
  10610. return '' +
  10611. '<table>' +
  10612. '<thead class="fc-head">' +
  10613. '<tr>' +
  10614. '<td class="fc-head-container ' + this.widgetHeaderClass + '"></td>' +
  10615. '</tr>' +
  10616. '</thead>' +
  10617. '<tbody class="fc-body">' +
  10618. '<tr>' +
  10619. '<td class="' + this.widgetContentClass + '">' +
  10620. (this.dayGrid ?
  10621. '<div class="fc-day-grid"/>' +
  10622. '<hr class="fc-divider ' + this.widgetHeaderClass + '"/>' :
  10623. ''
  10624. ) +
  10625. '</td>' +
  10626. '</tr>' +
  10627. '</tbody>' +
  10628. '</table>';
  10629. },
  10630. // Generates an HTML attribute string for setting the width of the axis, if it is known
  10631. axisStyleAttr: function() {
  10632. if (this.axisWidth !== null) {
  10633. return 'style="width:' + this.axisWidth + 'px"';
  10634. }
  10635. return '';
  10636. },
  10637. /* Business Hours
  10638. ------------------------------------------------------------------------------------------------------------------*/
  10639. renderBusinessHours: function() {
  10640. this.timeGrid.renderBusinessHours();
  10641. if (this.dayGrid) {
  10642. this.dayGrid.renderBusinessHours();
  10643. }
  10644. },
  10645. unrenderBusinessHours: function() {
  10646. this.timeGrid.unrenderBusinessHours();
  10647. if (this.dayGrid) {
  10648. this.dayGrid.unrenderBusinessHours();
  10649. }
  10650. },
  10651. /* Now Indicator
  10652. ------------------------------------------------------------------------------------------------------------------*/
  10653. getNowIndicatorUnit: function() {
  10654. return this.timeGrid.getNowIndicatorUnit();
  10655. },
  10656. renderNowIndicator: function(date) {
  10657. this.timeGrid.renderNowIndicator(date);
  10658. },
  10659. unrenderNowIndicator: function() {
  10660. this.timeGrid.unrenderNowIndicator();
  10661. },
  10662. /* Dimensions
  10663. ------------------------------------------------------------------------------------------------------------------*/
  10664. updateSize: function(isResize) {
  10665. this.timeGrid.updateSize(isResize);
  10666. View.prototype.updateSize.call(this, isResize); // call the super-method
  10667. },
  10668. // Refreshes the horizontal dimensions of the view
  10669. updateWidth: function() {
  10670. // make all axis cells line up, and record the width so newly created axis cells will have it
  10671. this.axisWidth = matchCellWidths(this.el.find('.fc-axis'));
  10672. },
  10673. // Adjusts the vertical dimensions of the view to the specified values
  10674. setHeight: function(totalHeight, isAuto) {
  10675. var eventLimit;
  10676. var scrollerHeight;
  10677. var scrollbarWidths;
  10678. // reset all dimensions back to the original state
  10679. this.bottomRuleEl.hide(); // .show() will be called later if this <hr> is necessary
  10680. this.scroller.clear(); // sets height to 'auto' and clears overflow
  10681. uncompensateScroll(this.noScrollRowEls);
  10682. // limit number of events in the all-day area
  10683. if (this.dayGrid) {
  10684. this.dayGrid.removeSegPopover(); // kill the "more" popover if displayed
  10685. eventLimit = this.opt('eventLimit');
  10686. if (eventLimit && typeof eventLimit !== 'number') {
  10687. eventLimit = AGENDA_ALL_DAY_EVENT_LIMIT; // make sure "auto" goes to a real number
  10688. }
  10689. if (eventLimit) {
  10690. this.dayGrid.limitRows(eventLimit);
  10691. }
  10692. }
  10693. if (!isAuto) { // should we force dimensions of the scroll container?
  10694. scrollerHeight = this.computeScrollerHeight(totalHeight);
  10695. this.scroller.setHeight(scrollerHeight);
  10696. scrollbarWidths = this.scroller.getScrollbarWidths();
  10697. if (scrollbarWidths.left || scrollbarWidths.right) { // using scrollbars?
  10698. // make the all-day and header rows lines up
  10699. compensateScroll(this.noScrollRowEls, scrollbarWidths);
  10700. // the scrollbar compensation might have changed text flow, which might affect height, so recalculate
  10701. // and reapply the desired height to the scroller.
  10702. scrollerHeight = this.computeScrollerHeight(totalHeight);
  10703. this.scroller.setHeight(scrollerHeight);
  10704. }
  10705. // guarantees the same scrollbar widths
  10706. this.scroller.lockOverflow(scrollbarWidths);
  10707. // if there's any space below the slats, show the horizontal rule.
  10708. // this won't cause any new overflow, because lockOverflow already called.
  10709. if (this.timeGrid.getTotalSlatHeight() < scrollerHeight) {
  10710. this.bottomRuleEl.show();
  10711. }
  10712. }
  10713. },
  10714. // given a desired total height of the view, returns what the height of the scroller should be
  10715. computeScrollerHeight: function(totalHeight) {
  10716. return totalHeight -
  10717. subtractInnerElHeight(this.el, this.scroller.el); // everything that's NOT the scroller
  10718. },
  10719. /* Scroll
  10720. ------------------------------------------------------------------------------------------------------------------*/
  10721. // Computes the initial pre-configured scroll state prior to allowing the user to change it
  10722. computeInitialScroll: function() {
  10723. var scrollTime = moment.duration(this.opt('scrollTime'));
  10724. var top = this.timeGrid.computeTimeTop(scrollTime);
  10725. // zoom can give weird floating-point values. rather scroll a little bit further
  10726. top = Math.ceil(top);
  10727. if (top) {
  10728. top++; // to overcome top border that slots beyond the first have. looks better
  10729. }
  10730. return { top: top };
  10731. },
  10732. queryScroll: function() {
  10733. return { top: this.scroller.getScrollTop() };
  10734. },
  10735. setScroll: function(scroll) {
  10736. this.scroller.setScrollTop(scroll.top);
  10737. },
  10738. /* Hit Areas
  10739. ------------------------------------------------------------------------------------------------------------------*/
  10740. // forward all hit-related method calls to the grids (dayGrid might not be defined)
  10741. hitsNeeded: function() {
  10742. this.timeGrid.hitsNeeded();
  10743. if (this.dayGrid) {
  10744. this.dayGrid.hitsNeeded();
  10745. }
  10746. },
  10747. hitsNotNeeded: function() {
  10748. this.timeGrid.hitsNotNeeded();
  10749. if (this.dayGrid) {
  10750. this.dayGrid.hitsNotNeeded();
  10751. }
  10752. },
  10753. prepareHits: function() {
  10754. this.timeGrid.prepareHits();
  10755. if (this.dayGrid) {
  10756. this.dayGrid.prepareHits();
  10757. }
  10758. },
  10759. releaseHits: function() {
  10760. this.timeGrid.releaseHits();
  10761. if (this.dayGrid) {
  10762. this.dayGrid.releaseHits();
  10763. }
  10764. },
  10765. queryHit: function(left, top) {
  10766. var hit = this.timeGrid.queryHit(left, top);
  10767. if (!hit && this.dayGrid) {
  10768. hit = this.dayGrid.queryHit(left, top);
  10769. }
  10770. return hit;
  10771. },
  10772. getHitSpan: function(hit) {
  10773. // TODO: hit.component is set as a hack to identify where the hit came from
  10774. return hit.component.getHitSpan(hit);
  10775. },
  10776. getHitEl: function(hit) {
  10777. // TODO: hit.component is set as a hack to identify where the hit came from
  10778. return hit.component.getHitEl(hit);
  10779. },
  10780. /* Events
  10781. ------------------------------------------------------------------------------------------------------------------*/
  10782. // Renders events onto the view and populates the View's segment array
  10783. renderEvents: function(events) {
  10784. var dayEvents = [];
  10785. var timedEvents = [];
  10786. var daySegs = [];
  10787. var timedSegs;
  10788. var i;
  10789. // separate the events into all-day and timed
  10790. for (i = 0; i < events.length; i++) {
  10791. if (events[i].allDay) {
  10792. dayEvents.push(events[i]);
  10793. }
  10794. else {
  10795. timedEvents.push(events[i]);
  10796. }
  10797. }
  10798. // render the events in the subcomponents
  10799. timedSegs = this.timeGrid.renderEvents(timedEvents);
  10800. if (this.dayGrid) {
  10801. daySegs = this.dayGrid.renderEvents(dayEvents);
  10802. }
  10803. // the all-day area is flexible and might have a lot of events, so shift the height
  10804. this.updateHeight();
  10805. },
  10806. // Retrieves all segment objects that are rendered in the view
  10807. getEventSegs: function() {
  10808. return this.timeGrid.getEventSegs().concat(
  10809. this.dayGrid ? this.dayGrid.getEventSegs() : []
  10810. );
  10811. },
  10812. // Unrenders all event elements and clears internal segment data
  10813. unrenderEvents: function() {
  10814. // unrender the events in the subcomponents
  10815. this.timeGrid.unrenderEvents();
  10816. if (this.dayGrid) {
  10817. this.dayGrid.unrenderEvents();
  10818. }
  10819. // we DON'T need to call updateHeight() because
  10820. // a renderEvents() call always happens after this, which will eventually call updateHeight()
  10821. },
  10822. /* Dragging (for events and external elements)
  10823. ------------------------------------------------------------------------------------------------------------------*/
  10824. // A returned value of `true` signals that a mock "helper" event has been rendered.
  10825. renderDrag: function(dropLocation, seg) {
  10826. if (dropLocation.start.hasTime()) {
  10827. return this.timeGrid.renderDrag(dropLocation, seg);
  10828. }
  10829. else if (this.dayGrid) {
  10830. return this.dayGrid.renderDrag(dropLocation, seg);
  10831. }
  10832. },
  10833. unrenderDrag: function() {
  10834. this.timeGrid.unrenderDrag();
  10835. if (this.dayGrid) {
  10836. this.dayGrid.unrenderDrag();
  10837. }
  10838. },
  10839. /* Selection
  10840. ------------------------------------------------------------------------------------------------------------------*/
  10841. // Renders a visual indication of a selection
  10842. renderSelection: function(span) {
  10843. if (span.start.hasTime() || span.end.hasTime()) {
  10844. this.timeGrid.renderSelection(span);
  10845. }
  10846. else if (this.dayGrid) {
  10847. this.dayGrid.renderSelection(span);
  10848. }
  10849. },
  10850. // Unrenders a visual indications of a selection
  10851. unrenderSelection: function() {
  10852. this.timeGrid.unrenderSelection();
  10853. if (this.dayGrid) {
  10854. this.dayGrid.unrenderSelection();
  10855. }
  10856. }
  10857. });
  10858. // Methods that will customize the rendering behavior of the AgendaView's timeGrid
  10859. // TODO: move into TimeGrid
  10860. var agendaTimeGridMethods = {
  10861. // Generates the HTML that will go before the day-of week header cells
  10862. renderHeadIntroHtml: function() {
  10863. var view = this.view;
  10864. var weekText;
  10865. if (view.opt('weekNumbers')) {
  10866. weekText = this.start.format(view.opt('smallWeekFormat'));
  10867. return '' +
  10868. '<th class="fc-axis fc-week-number ' + view.widgetHeaderClass + '" ' + view.axisStyleAttr() + '>' +
  10869. view.buildGotoAnchorHtml( // aside from link, important for matchCellWidths
  10870. { date: this.start, type: 'week', forceOff: this.colCnt > 1 },
  10871. htmlEscape(weekText) // inner HTML
  10872. ) +
  10873. '</th>';
  10874. }
  10875. else {
  10876. return '<th class="fc-axis ' + view.widgetHeaderClass + '" ' + view.axisStyleAttr() + '></th>';
  10877. }
  10878. },
  10879. // Generates the HTML that goes before the bg of the TimeGrid slot area. Long vertical column.
  10880. renderBgIntroHtml: function() {
  10881. var view = this.view;
  10882. return '<td class="fc-axis ' + view.widgetContentClass + '" ' + view.axisStyleAttr() + '></td>';
  10883. },
  10884. // Generates the HTML that goes before all other types of cells.
  10885. // Affects content-skeleton, helper-skeleton, highlight-skeleton for both the time-grid and day-grid.
  10886. renderIntroHtml: function() {
  10887. var view = this.view;
  10888. return '<td class="fc-axis" ' + view.axisStyleAttr() + '></td>';
  10889. }
  10890. };
  10891. // Methods that will customize the rendering behavior of the AgendaView's dayGrid
  10892. var agendaDayGridMethods = {
  10893. // Generates the HTML that goes before the all-day cells
  10894. renderBgIntroHtml: function() {
  10895. var view = this.view;
  10896. return '' +
  10897. '<td class="fc-axis ' + view.widgetContentClass + '" ' + view.axisStyleAttr() + '>' +
  10898. '<span>' + // needed for matchCellWidths
  10899. view.getAllDayHtml() +
  10900. '</span>' +
  10901. '</td>';
  10902. },
  10903. // Generates the HTML that goes before all other types of cells.
  10904. // Affects content-skeleton, helper-skeleton, highlight-skeleton for both the time-grid and day-grid.
  10905. renderIntroHtml: function() {
  10906. var view = this.view;
  10907. return '<td class="fc-axis" ' + view.axisStyleAttr() + '></td>';
  10908. }
  10909. };
  10910. ;;
  10911. var AGENDA_ALL_DAY_EVENT_LIMIT = 5;
  10912. // potential nice values for the slot-duration and interval-duration
  10913. // from largest to smallest
  10914. var AGENDA_STOCK_SUB_DURATIONS = [
  10915. { hours: 1 },
  10916. { minutes: 30 },
  10917. { minutes: 15 },
  10918. { seconds: 30 },
  10919. { seconds: 15 }
  10920. ];
  10921. fcViews.agenda = {
  10922. 'class': AgendaView,
  10923. defaults: {
  10924. allDaySlot: true,
  10925. slotDuration: '00:30:00',
  10926. minTime: '00:00:00',
  10927. maxTime: '24:00:00',
  10928. slotEventOverlap: true // a bad name. confused with overlap/constraint system
  10929. }
  10930. };
  10931. fcViews.agendaDay = {
  10932. type: 'agenda',
  10933. duration: { days: 1 }
  10934. };
  10935. fcViews.agendaWeek = {
  10936. type: 'agenda',
  10937. duration: { weeks: 1 }
  10938. };
  10939. ;;
  10940. /*
  10941. Responsible for the scroller, and forwarding event-related actions into the "grid"
  10942. */
  10943. var ListView = View.extend({
  10944. grid: null,
  10945. scroller: null,
  10946. initialize: function() {
  10947. this.grid = new ListViewGrid(this);
  10948. this.scroller = new Scroller({
  10949. overflowX: 'hidden',
  10950. overflowY: 'auto'
  10951. });
  10952. },
  10953. setRange: function(range) {
  10954. View.prototype.setRange.call(this, range); // super
  10955. this.grid.setRange(range); // needs to process range-related options
  10956. },
  10957. renderSkeleton: function() {
  10958. this.el.addClass(
  10959. 'fc-list-view ' +
  10960. this.widgetContentClass
  10961. );
  10962. this.scroller.render();
  10963. this.scroller.el.appendTo(this.el);
  10964. this.grid.setElement(this.scroller.scrollEl);
  10965. },
  10966. unrenderSkeleton: function() {
  10967. this.scroller.destroy(); // will remove the Grid too
  10968. },
  10969. setHeight: function(totalHeight, isAuto) {
  10970. this.scroller.setHeight(this.computeScrollerHeight(totalHeight));
  10971. },
  10972. computeScrollerHeight: function(totalHeight) {
  10973. return totalHeight -
  10974. subtractInnerElHeight(this.el, this.scroller.el); // everything that's NOT the scroller
  10975. },
  10976. renderEvents: function(events) {
  10977. this.grid.renderEvents(events);
  10978. },
  10979. unrenderEvents: function() {
  10980. this.grid.unrenderEvents();
  10981. },
  10982. isEventResizable: function(event) {
  10983. return false;
  10984. },
  10985. isEventDraggable: function(event) {
  10986. return false;
  10987. }
  10988. });
  10989. /*
  10990. Responsible for event rendering and user-interaction.
  10991. Its "el" is the inner-content of the above view's scroller.
  10992. */
  10993. var ListViewGrid = Grid.extend({
  10994. segSelector: '.fc-list-item', // which elements accept event actions
  10995. hasDayInteractions: false, // no day selection or day clicking
  10996. // slices by day
  10997. spanToSegs: function(span) {
  10998. var view = this.view;
  10999. var dayStart = view.start.clone().time(0); // timed, so segs get times!
  11000. var dayIndex = 0;
  11001. var seg;
  11002. var segs = [];
  11003. while (dayStart < view.end) {
  11004. seg = intersectRanges(span, {
  11005. start: dayStart,
  11006. end: dayStart.clone().add(1, 'day')
  11007. });
  11008. if (seg) {
  11009. seg.dayIndex = dayIndex;
  11010. segs.push(seg);
  11011. }
  11012. dayStart.add(1, 'day');
  11013. dayIndex++;
  11014. // detect when span won't go fully into the next day,
  11015. // and mutate the latest seg to the be the end.
  11016. if (
  11017. seg && !seg.isEnd && span.end.hasTime() &&
  11018. span.end < dayStart.clone().add(this.view.nextDayThreshold)
  11019. ) {
  11020. seg.end = span.end.clone();
  11021. seg.isEnd = true;
  11022. break;
  11023. }
  11024. }
  11025. return segs;
  11026. },
  11027. // like "4:00am"
  11028. computeEventTimeFormat: function() {
  11029. return this.view.opt('mediumTimeFormat');
  11030. },
  11031. // for events with a url, the whole <tr> should be clickable,
  11032. // but it's impossible to wrap with an <a> tag. simulate this.
  11033. handleSegClick: function(seg, ev) {
  11034. var url;
  11035. Grid.prototype.handleSegClick.apply(this, arguments); // super. might prevent the default action
  11036. // not clicking on or within an <a> with an href
  11037. if (!$(ev.target).closest('a[href]').length) {
  11038. url = seg.event.url;
  11039. if (url && !ev.isDefaultPrevented()) { // jsEvent not cancelled in handler
  11040. window.location.href = url; // simulate link click
  11041. }
  11042. }
  11043. },
  11044. // returns list of foreground segs that were actually rendered
  11045. renderFgSegs: function(segs) {
  11046. segs = this.renderFgSegEls(segs); // might filter away hidden events
  11047. if (!segs.length) {
  11048. this.renderEmptyMessage();
  11049. }
  11050. else {
  11051. this.renderSegList(segs);
  11052. }
  11053. return segs;
  11054. },
  11055. renderEmptyMessage: function() {
  11056. this.el.html(
  11057. '<div class="fc-list-empty-wrap2">' + // TODO: try less wraps
  11058. '<div class="fc-list-empty-wrap1">' +
  11059. '<div class="fc-list-empty">' +
  11060. htmlEscape(this.view.opt('noEventsMessage')) +
  11061. '</div>' +
  11062. '</div>' +
  11063. '</div>'
  11064. );
  11065. },
  11066. // render the event segments in the view
  11067. renderSegList: function(allSegs) {
  11068. var segsByDay = this.groupSegsByDay(allSegs); // sparse array
  11069. var dayIndex;
  11070. var daySegs;
  11071. var i;
  11072. var tableEl = $('<table class="fc-list-table"><tbody/></table>');
  11073. var tbodyEl = tableEl.find('tbody');
  11074. for (dayIndex = 0; dayIndex < segsByDay.length; dayIndex++) {
  11075. daySegs = segsByDay[dayIndex];
  11076. if (daySegs) { // sparse array, so might be undefined
  11077. // append a day header
  11078. tbodyEl.append(this.dayHeaderHtml(
  11079. this.view.start.clone().add(dayIndex, 'days')
  11080. ));
  11081. this.sortEventSegs(daySegs);
  11082. for (i = 0; i < daySegs.length; i++) {
  11083. tbodyEl.append(daySegs[i].el); // append event row
  11084. }
  11085. }
  11086. }
  11087. this.el.empty().append(tableEl);
  11088. },
  11089. // Returns a sparse array of arrays, segs grouped by their dayIndex
  11090. groupSegsByDay: function(segs) {
  11091. var segsByDay = []; // sparse array
  11092. var i, seg;
  11093. for (i = 0; i < segs.length; i++) {
  11094. seg = segs[i];
  11095. (segsByDay[seg.dayIndex] || (segsByDay[seg.dayIndex] = []))
  11096. .push(seg);
  11097. }
  11098. return segsByDay;
  11099. },
  11100. // generates the HTML for the day headers that live amongst the event rows
  11101. dayHeaderHtml: function(dayDate) {
  11102. var view = this.view;
  11103. var mainFormat = view.opt('listDayFormat');
  11104. var altFormat = view.opt('listDayAltFormat');
  11105. return '<tr class="fc-list-heading" data-date="' + dayDate.format('YYYY-MM-DD') + ' ">' +
  11106. '<th class="fc-list-header ' + view.widgetHeaderClass + '" colspan="3">' +
  11107. (mainFormat ?
  11108. view.buildGotoAnchorHtml(
  11109. dayDate,
  11110. { 'class': 'fc-list-heading-main' },
  11111. htmlEscape(dayDate.format(mainFormat)) // inner HTML
  11112. ) :
  11113. '') +
  11114. (altFormat ?
  11115. view.buildGotoAnchorHtml(
  11116. dayDate,
  11117. { 'class': 'fc-list-heading-alt' },
  11118. htmlEscape(dayDate.format(altFormat)) // inner HTML
  11119. ) :
  11120. '') +
  11121. '</th>' +
  11122. '</tr>';
  11123. },
  11124. // generates the HTML for a single event row
  11125. fgSegHtml: function(seg, disableResizing) {
  11126. var view = this.view;
  11127. var event = seg.event;
  11128. var isDraggable = view.isEventDraggable(event);
  11129. var isResizableFromStart = !disableResizing && event.allDay &&
  11130. seg.isStart && view.isEventResizableFromStart(event);
  11131. var isResizableFromEnd = !disableResizing && event.allDay &&
  11132. seg.isEnd && view.isEventResizableFromEnd(event);
  11133. var classes = this.getSegClasses(seg, isDraggable, isResizableFromStart || isResizableFromEnd);
  11134. var skinCss = cssToStr(this.getSegSkinCss(seg));
  11135. var timeHtml = '';
  11136. var timeText;
  11137. var titleHtml;
  11138. var urlMeta = event.id ? htmlEscape(event.id) : 'none';
  11139. var metadata = '<div id="'+urlMeta+'" class="white-popup mfp-with-anim mfp-hide"><div class="col-md-8 col-md-offset-2 '+urlMeta+'-metadata-info"></div></div>';
  11140. var detailsJSON = JSON.stringify(event.details);
  11141. classes.unshift('fc-day-grid-event', 'fc-h-event');
  11142. // Only display a timed events time if it is the starting segment
  11143. if (seg.isStart) {
  11144. timeText = this.getEventTimeText(event);
  11145. if (timeText) {
  11146. timeHtml = '<span class="fc-time '+(htmlEscape(event.imagetype || '') || '&nbsp;')+'">' + htmlEscape(timeText) + '</span><br/>';
  11147. }else{
  11148. timeHtml = '<br/>';
  11149. }
  11150. }
  11151. titleHtml =
  11152. '<span class="fc-title">' +
  11153. (htmlEscape(event.title || '') || '&nbsp;') + // we always want one line of height
  11154. '</span>';
  11155. switch(event.imagetypeFilter){
  11156. case 'tv':
  11157. titleHtml = titleHtml + '<br/><small class="fc-title m-l-5">' +
  11158. (htmlEscape(event.details.bottomTitle || '') || '&nbsp;') + // we always want one line of height
  11159. '</small>';
  11160. break;
  11161. case 'music':
  11162. titleHtml = titleHtml + '<br/><small class="fc-title m-l-5">' +
  11163. (htmlEscape(event.details.topTitle || '') || '&nbsp;') + // we always want one line of height
  11164. '</small>';
  11165. break;
  11166. case 'film':
  11167. titleHtml = titleHtml + '<br/><small class="fc-title m-l-5">' +
  11168. (htmlEscape(event.details.studio || '') || '&nbsp;') + // we always want one line of height
  11169. '</small>';
  11170. break;
  11171. default:
  11172. titleHtml = titleHtml + '<br/><small class="fc-title m-l-5">' +
  11173. (htmlEscape('' || '') || '&nbsp;') + // we always want one line of height
  11174. '</small>';
  11175. }
  11176. imageHtml =
  11177. '<span class="fc-status '+ event.bgColor +'"></span><span class="fc-image"><i class="fa fa-' +
  11178. (htmlEscape(event.imagetype || '') || '&nbsp;') + // we always want one line of height
  11179. '"></i></span>';
  11180. return '<a class=" ' + classes.join(' ') + '"' +
  11181. (event.id ?
  11182. ' data-effect="mfp-zoom-out" data-target="'+ htmlEscape(event.id) +'" data-details="'+htmlEscape(detailsJSON) +'" data-mfp-src="#' + htmlEscape(event.id) + '"' :
  11183. ''
  11184. ) +
  11185. (skinCss ?
  11186. ' style="' + skinCss + '"' :
  11187. ''
  11188. ) +
  11189. '>' +
  11190. '<div class="fc-content">' +
  11191. (this.isRTL ?
  11192. titleHtml + ' ' + timeHtml : // put a natural space in between
  11193. imageHtml + ' ' + timeHtml + ' ' + titleHtml //
  11194. ) +
  11195. '</div>' +
  11196. (isResizableFromStart ?
  11197. '<div class="fc-resizer fc-start-resizer" />' :
  11198. ''
  11199. ) +
  11200. (isResizableFromEnd ?
  11201. '<div class="fc-resizer fc-end-resizer" />' :
  11202. ''
  11203. ) +metadata+
  11204. '</a>';
  11205. }
  11206. });
  11207. ;;
  11208. fcViews.list = {
  11209. 'class': ListView,
  11210. buttonTextKey: 'list', // what to lookup in locale files
  11211. defaults: {
  11212. buttonText: 'list', // text to display for English
  11213. listDayFormat: 'LL', // like "January 1, 2016"
  11214. noEventsMessage: 'No events to display'
  11215. }
  11216. };
  11217. fcViews.listDay = {
  11218. type: 'list',
  11219. duration: { days: 1 },
  11220. defaults: {
  11221. listDayFormat: 'dddd' // day-of-week is all we need. full date is probably in header
  11222. }
  11223. };
  11224. fcViews.listWeek = {
  11225. type: 'list',
  11226. duration: { weeks: 1 },
  11227. defaults: {
  11228. listDayFormat: 'dddd', // day-of-week is more important
  11229. listDayAltFormat: 'LL'
  11230. }
  11231. };
  11232. fcViews.listMonth = {
  11233. type: 'list',
  11234. duration: { month: 1 },
  11235. defaults: {
  11236. listDayAltFormat: 'dddd' // day-of-week is nice-to-have
  11237. }
  11238. };
  11239. fcViews.listYear = {
  11240. type: 'list',
  11241. duration: { year: 1 },
  11242. defaults: {
  11243. listDayAltFormat: 'dddd' // day-of-week is nice-to-have
  11244. }
  11245. };
  11246. ;;
  11247. return FC; // export for Node/CommonJS
  11248. });