fullcalendar.js 395 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599
  1. /*!
  2. * FullCalendar v3.2.0
  3. * Docs & License: https://fullcalendar.io/
  4. * (c) 2017 Adam Shaw
  5. */
  6. (function(factory) {
  7. if (typeof define === 'function' && define.amd) {
  8. define([ 'jquery', 'moment' ], factory);
  9. }
  10. else if (typeof exports === 'object') { // Node/CommonJS
  11. module.exports = factory(require('jquery'), require('moment'));
  12. }
  13. else {
  14. factory(jQuery, moment);
  15. }
  16. })(function($, moment) {
  17. ;;
  18. var FC = $.fullCalendar = {
  19. version: "3.2.0",
  20. // When introducing internal API incompatibilities (where fullcalendar plugins would break),
  21. // the minor version of the calendar should be upped (ex: 2.7.2 -> 2.8.0)
  22. // and the below integer should be incremented.
  23. internalApiVersion: 8
  24. };
  25. var fcViews = FC.views = {};
  26. $.fn.fullCalendar = function(options) {
  27. var args = Array.prototype.slice.call(arguments, 1); // for a possible method call
  28. var res = this; // what this function will return (this jQuery object by default)
  29. this.each(function(i, _element) { // loop each DOM element involved
  30. var element = $(_element);
  31. var calendar = element.data('fullCalendar'); // get the existing calendar object (if any)
  32. var singleRes; // the returned value of this single method call
  33. // a method call
  34. if (typeof options === 'string') {
  35. if (calendar && $.isFunction(calendar[options])) {
  36. singleRes = calendar[options].apply(calendar, args);
  37. if (!i) {
  38. res = singleRes; // record the first method call result
  39. }
  40. if (options === 'destroy') { // for the destroy method, must remove Calendar object data
  41. element.removeData('fullCalendar');
  42. }
  43. }
  44. }
  45. // a new calendar initialization
  46. else if (!calendar) { // don't initialize twice
  47. calendar = new Calendar(element, options);
  48. element.data('fullCalendar', calendar);
  49. calendar.render();
  50. }
  51. });
  52. return res;
  53. };
  54. var complexOptions = [ // names of options that are objects whose properties should be combined
  55. 'header',
  56. 'footer',
  57. 'buttonText',
  58. 'buttonIcons',
  59. 'themeButtonIcons'
  60. ];
  61. // Merges an array of option objects into a single object
  62. function mergeOptions(optionObjs) {
  63. return mergeProps(optionObjs, complexOptions);
  64. }
  65. ;;
  66. // exports
  67. FC.intersectRanges = intersectRanges;
  68. FC.applyAll = applyAll;
  69. FC.debounce = debounce;
  70. FC.isInt = isInt;
  71. FC.htmlEscape = htmlEscape;
  72. FC.cssToStr = cssToStr;
  73. FC.proxy = proxy;
  74. FC.capitaliseFirstLetter = capitaliseFirstLetter;
  75. /* FullCalendar-specific DOM Utilities
  76. ----------------------------------------------------------------------------------------------------------------------*/
  77. // Given the scrollbar widths of some other container, create borders/margins on rowEls in order to match the left
  78. // and right space that was offset by the scrollbars. A 1-pixel border first, then margin beyond that.
  79. function compensateScroll(rowEls, scrollbarWidths) {
  80. if (scrollbarWidths.left) {
  81. rowEls.css({
  82. 'border-left-width': 1,
  83. 'margin-left': scrollbarWidths.left - 1
  84. });
  85. }
  86. if (scrollbarWidths.right) {
  87. rowEls.css({
  88. 'border-right-width': 1,
  89. 'margin-right': scrollbarWidths.right - 1
  90. });
  91. }
  92. }
  93. // Undoes compensateScroll and restores all borders/margins
  94. function uncompensateScroll(rowEls) {
  95. rowEls.css({
  96. 'margin-left': '',
  97. 'margin-right': '',
  98. 'border-left-width': '',
  99. 'border-right-width': ''
  100. });
  101. }
  102. // Make the mouse cursor express that an event is not allowed in the current area
  103. function disableCursor() {
  104. $('body').addClass('fc-not-allowed');
  105. }
  106. // Returns the mouse cursor to its original look
  107. function enableCursor() {
  108. $('body').removeClass('fc-not-allowed');
  109. }
  110. // Given a total available height to fill, have `els` (essentially child rows) expand to accomodate.
  111. // By default, all elements that are shorter than the recommended height are expanded uniformly, not considering
  112. // any other els that are already too tall. if `shouldRedistribute` is on, it considers these tall rows and
  113. // reduces the available height.
  114. function distributeHeight(els, availableHeight, shouldRedistribute) {
  115. // *FLOORING NOTE*: we floor in certain places because zoom can give inaccurate floating-point dimensions,
  116. // and it is better to be shorter than taller, to avoid creating unnecessary scrollbars.
  117. var minOffset1 = Math.floor(availableHeight / els.length); // for non-last element
  118. var minOffset2 = Math.floor(availableHeight - minOffset1 * (els.length - 1)); // for last element *FLOORING NOTE*
  119. var flexEls = []; // elements that are allowed to expand. array of DOM nodes
  120. var flexOffsets = []; // amount of vertical space it takes up
  121. var flexHeights = []; // actual css height
  122. var usedHeight = 0;
  123. undistributeHeight(els); // give all elements their natural height
  124. // find elements that are below the recommended height (expandable).
  125. // important to query for heights in a single first pass (to avoid reflow oscillation).
  126. els.each(function(i, el) {
  127. var minOffset = i === els.length - 1 ? minOffset2 : minOffset1;
  128. var naturalOffset = $(el).outerHeight(true);
  129. if (naturalOffset < minOffset) {
  130. flexEls.push(el);
  131. flexOffsets.push(naturalOffset);
  132. flexHeights.push($(el).height());
  133. }
  134. else {
  135. // this element stretches past recommended height (non-expandable). mark the space as occupied.
  136. usedHeight += naturalOffset;
  137. }
  138. });
  139. // readjust the recommended height to only consider the height available to non-maxed-out rows.
  140. if (shouldRedistribute) {
  141. availableHeight -= usedHeight;
  142. minOffset1 = Math.floor(availableHeight / flexEls.length);
  143. minOffset2 = Math.floor(availableHeight - minOffset1 * (flexEls.length - 1)); // *FLOORING NOTE*
  144. }
  145. // assign heights to all expandable elements
  146. $(flexEls).each(function(i, el) {
  147. var minOffset = i === flexEls.length - 1 ? minOffset2 : minOffset1;
  148. var naturalOffset = flexOffsets[i];
  149. var naturalHeight = flexHeights[i];
  150. var newHeight = minOffset - (naturalOffset - naturalHeight); // subtract the margin/padding
  151. if (naturalOffset < minOffset) { // we check this again because redistribution might have changed things
  152. $(el).height(newHeight);
  153. }
  154. });
  155. }
  156. // Undoes distrubuteHeight, restoring all els to their natural height
  157. function undistributeHeight(els) {
  158. els.height('');
  159. }
  160. // Given `els`, a jQuery set of <td> cells, find the cell with the largest natural width and set the widths of all the
  161. // cells to be that width.
  162. // PREREQUISITE: if you want a cell to take up width, it needs to have a single inner element w/ display:inline
  163. function matchCellWidths(els) {
  164. var maxInnerWidth = 0;
  165. els.find('> *').each(function(i, innerEl) {
  166. var innerWidth = $(innerEl).outerWidth();
  167. if (innerWidth > maxInnerWidth) {
  168. maxInnerWidth = innerWidth;
  169. }
  170. });
  171. maxInnerWidth++; // sometimes not accurate of width the text needs to stay on one line. insurance
  172. els.width(maxInnerWidth);
  173. return maxInnerWidth;
  174. }
  175. // Given one element that resides inside another,
  176. // Subtracts the height of the inner element from the outer element.
  177. function subtractInnerElHeight(outerEl, innerEl) {
  178. var both = outerEl.add(innerEl);
  179. var diff;
  180. // effin' IE8/9/10/11 sometimes returns 0 for dimensions. this weird hack was the only thing that worked
  181. both.css({
  182. position: 'relative', // cause a reflow, which will force fresh dimension recalculation
  183. left: -1 // ensure reflow in case the el was already relative. negative is less likely to cause new scroll
  184. });
  185. diff = outerEl.outerHeight() - innerEl.outerHeight(); // grab the dimensions
  186. both.css({ position: '', left: '' }); // undo hack
  187. return diff;
  188. }
  189. /* Element Geom Utilities
  190. ----------------------------------------------------------------------------------------------------------------------*/
  191. FC.getOuterRect = getOuterRect;
  192. FC.getClientRect = getClientRect;
  193. FC.getContentRect = getContentRect;
  194. FC.getScrollbarWidths = getScrollbarWidths;
  195. // borrowed from https://github.com/jquery/jquery-ui/blob/1.11.0/ui/core.js#L51
  196. function getScrollParent(el) {
  197. var position = el.css('position'),
  198. scrollParent = el.parents().filter(function() {
  199. var parent = $(this);
  200. return (/(auto|scroll)/).test(
  201. parent.css('overflow') + parent.css('overflow-y') + parent.css('overflow-x')
  202. );
  203. }).eq(0);
  204. return position === 'fixed' || !scrollParent.length ? $(el[0].ownerDocument || document) : scrollParent;
  205. }
  206. // Queries the outer bounding area of a jQuery element.
  207. // Returns a rectangle with absolute coordinates: left, right (exclusive), top, bottom (exclusive).
  208. // Origin is optional.
  209. function getOuterRect(el, origin) {
  210. var offset = el.offset();
  211. var left = offset.left - (origin ? origin.left : 0);
  212. var top = offset.top - (origin ? origin.top : 0);
  213. return {
  214. left: left,
  215. right: left + el.outerWidth(),
  216. top: top,
  217. bottom: top + el.outerHeight()
  218. };
  219. }
  220. // Queries the area within the margin/border/scrollbars of a jQuery element. Does not go within the padding.
  221. // Returns a rectangle with absolute coordinates: left, right (exclusive), top, bottom (exclusive).
  222. // Origin is optional.
  223. // NOTE: should use clientLeft/clientTop, but very unreliable cross-browser.
  224. function getClientRect(el, origin) {
  225. var offset = el.offset();
  226. var scrollbarWidths = getScrollbarWidths(el);
  227. var left = offset.left + getCssFloat(el, 'border-left-width') + scrollbarWidths.left - (origin ? origin.left : 0);
  228. var top = offset.top + getCssFloat(el, 'border-top-width') + scrollbarWidths.top - (origin ? origin.top : 0);
  229. return {
  230. left: left,
  231. right: left + el[0].clientWidth, // clientWidth includes padding but NOT scrollbars
  232. top: top,
  233. bottom: top + el[0].clientHeight // clientHeight includes padding but NOT scrollbars
  234. };
  235. }
  236. // Queries the area within the margin/border/padding of a jQuery element. Assumed not to have scrollbars.
  237. // Returns a rectangle with absolute coordinates: left, right (exclusive), top, bottom (exclusive).
  238. // Origin is optional.
  239. function getContentRect(el, origin) {
  240. var offset = el.offset(); // just outside of border, margin not included
  241. var left = offset.left + getCssFloat(el, 'border-left-width') + getCssFloat(el, 'padding-left') -
  242. (origin ? origin.left : 0);
  243. var top = offset.top + getCssFloat(el, 'border-top-width') + getCssFloat(el, 'padding-top') -
  244. (origin ? origin.top : 0);
  245. return {
  246. left: left,
  247. right: left + el.width(),
  248. top: top,
  249. bottom: top + el.height()
  250. };
  251. }
  252. // Returns the computed left/right/top/bottom scrollbar widths for the given jQuery element.
  253. // NOTE: should use clientLeft/clientTop, but very unreliable cross-browser.
  254. function getScrollbarWidths(el) {
  255. var leftRightWidth = el.innerWidth() - el[0].clientWidth; // the paddings cancel out, leaving the scrollbars
  256. var bottomWidth = el.innerHeight() - el[0].clientHeight; // "
  257. var widths;
  258. leftRightWidth = sanitizeScrollbarWidth(leftRightWidth);
  259. bottomWidth = sanitizeScrollbarWidth(bottomWidth);
  260. widths = { left: 0, right: 0, top: 0, bottom: bottomWidth };
  261. if (getIsLeftRtlScrollbars() && el.css('direction') == 'rtl') { // is the scrollbar on the left side?
  262. widths.left = leftRightWidth;
  263. }
  264. else {
  265. widths.right = leftRightWidth;
  266. }
  267. return widths;
  268. }
  269. // The scrollbar width computations in getScrollbarWidths are sometimes flawed when it comes to
  270. // retina displays, rounding, and IE11. Massage them into a usable value.
  271. function sanitizeScrollbarWidth(width) {
  272. width = Math.max(0, width); // no negatives
  273. width = Math.round(width);
  274. return width;
  275. }
  276. // Logic for determining if, when the element is right-to-left, the scrollbar appears on the left side
  277. var _isLeftRtlScrollbars = null;
  278. function getIsLeftRtlScrollbars() { // responsible for caching the computation
  279. if (_isLeftRtlScrollbars === null) {
  280. _isLeftRtlScrollbars = computeIsLeftRtlScrollbars();
  281. }
  282. return _isLeftRtlScrollbars;
  283. }
  284. function computeIsLeftRtlScrollbars() { // creates an offscreen test element, then removes it
  285. var el = $('<div><div/></div>')
  286. .css({
  287. position: 'absolute',
  288. top: -1000,
  289. left: 0,
  290. border: 0,
  291. padding: 0,
  292. overflow: 'scroll',
  293. direction: 'rtl'
  294. })
  295. .appendTo('body');
  296. var innerEl = el.children();
  297. var res = innerEl.offset().left > el.offset().left; // is the inner div shifted to accommodate a left scrollbar?
  298. el.remove();
  299. return res;
  300. }
  301. // Retrieves a jQuery element's computed CSS value as a floating-point number.
  302. // If the queried value is non-numeric (ex: IE can return "medium" for border width), will just return zero.
  303. function getCssFloat(el, prop) {
  304. return parseFloat(el.css(prop)) || 0;
  305. }
  306. /* Mouse / Touch Utilities
  307. ----------------------------------------------------------------------------------------------------------------------*/
  308. FC.preventDefault = preventDefault;
  309. // Returns a boolean whether this was a left mouse click and no ctrl key (which means right click on Mac)
  310. function isPrimaryMouseButton(ev) {
  311. return ev.which == 1 && !ev.ctrlKey;
  312. }
  313. function getEvX(ev) {
  314. var touches = ev.originalEvent.touches;
  315. // on mobile FF, pageX for touch events is present, but incorrect,
  316. // so, look at touch coordinates first.
  317. if (touches && touches.length) {
  318. return touches[0].pageX;
  319. }
  320. return ev.pageX;
  321. }
  322. function getEvY(ev) {
  323. var touches = ev.originalEvent.touches;
  324. // on mobile FF, pageX for touch events is present, but incorrect,
  325. // so, look at touch coordinates first.
  326. if (touches && touches.length) {
  327. return touches[0].pageY;
  328. }
  329. return ev.pageY;
  330. }
  331. function getEvIsTouch(ev) {
  332. return /^touch/.test(ev.type);
  333. }
  334. function preventSelection(el) {
  335. el.addClass('fc-unselectable')
  336. .on('selectstart', preventDefault);
  337. }
  338. function allowSelection(el) {
  339. el.removeClass('fc-unselectable')
  340. .off('selectstart', preventDefault);
  341. }
  342. // Stops a mouse/touch event from doing it's native browser action
  343. function preventDefault(ev) {
  344. ev.preventDefault();
  345. }
  346. /* General Geometry Utils
  347. ----------------------------------------------------------------------------------------------------------------------*/
  348. FC.intersectRects = intersectRects;
  349. // Returns a new rectangle that is the intersection of the two rectangles. If they don't intersect, returns false
  350. function intersectRects(rect1, rect2) {
  351. var res = {
  352. left: Math.max(rect1.left, rect2.left),
  353. right: Math.min(rect1.right, rect2.right),
  354. top: Math.max(rect1.top, rect2.top),
  355. bottom: Math.min(rect1.bottom, rect2.bottom)
  356. };
  357. if (res.left < res.right && res.top < res.bottom) {
  358. return res;
  359. }
  360. return false;
  361. }
  362. // Returns a new point that will have been moved to reside within the given rectangle
  363. function constrainPoint(point, rect) {
  364. return {
  365. left: Math.min(Math.max(point.left, rect.left), rect.right),
  366. top: Math.min(Math.max(point.top, rect.top), rect.bottom)
  367. };
  368. }
  369. // Returns a point that is the center of the given rectangle
  370. function getRectCenter(rect) {
  371. return {
  372. left: (rect.left + rect.right) / 2,
  373. top: (rect.top + rect.bottom) / 2
  374. };
  375. }
  376. // Subtracts point2's coordinates from point1's coordinates, returning a delta
  377. function diffPoints(point1, point2) {
  378. return {
  379. left: point1.left - point2.left,
  380. top: point1.top - point2.top
  381. };
  382. }
  383. /* Object Ordering by Field
  384. ----------------------------------------------------------------------------------------------------------------------*/
  385. FC.parseFieldSpecs = parseFieldSpecs;
  386. FC.compareByFieldSpecs = compareByFieldSpecs;
  387. FC.compareByFieldSpec = compareByFieldSpec;
  388. FC.flexibleCompare = flexibleCompare;
  389. function parseFieldSpecs(input) {
  390. var specs = [];
  391. var tokens = [];
  392. var i, token;
  393. if (typeof input === 'string') {
  394. tokens = input.split(/\s*,\s*/);
  395. }
  396. else if (typeof input === 'function') {
  397. tokens = [ input ];
  398. }
  399. else if ($.isArray(input)) {
  400. tokens = input;
  401. }
  402. for (i = 0; i < tokens.length; i++) {
  403. token = tokens[i];
  404. if (typeof token === 'string') {
  405. specs.push(
  406. token.charAt(0) == '-' ?
  407. { field: token.substring(1), order: -1 } :
  408. { field: token, order: 1 }
  409. );
  410. }
  411. else if (typeof token === 'function') {
  412. specs.push({ func: token });
  413. }
  414. }
  415. return specs;
  416. }
  417. function compareByFieldSpecs(obj1, obj2, fieldSpecs) {
  418. var i;
  419. var cmp;
  420. for (i = 0; i < fieldSpecs.length; i++) {
  421. cmp = compareByFieldSpec(obj1, obj2, fieldSpecs[i]);
  422. if (cmp) {
  423. return cmp;
  424. }
  425. }
  426. return 0;
  427. }
  428. function compareByFieldSpec(obj1, obj2, fieldSpec) {
  429. if (fieldSpec.func) {
  430. return fieldSpec.func(obj1, obj2);
  431. }
  432. return flexibleCompare(obj1[fieldSpec.field], obj2[fieldSpec.field]) *
  433. (fieldSpec.order || 1);
  434. }
  435. function flexibleCompare(a, b) {
  436. if (!a && !b) {
  437. return 0;
  438. }
  439. if (b == null) {
  440. return -1;
  441. }
  442. if (a == null) {
  443. return 1;
  444. }
  445. if ($.type(a) === 'string' || $.type(b) === 'string') {
  446. return String(a).localeCompare(String(b));
  447. }
  448. return a - b;
  449. }
  450. /* FullCalendar-specific Misc Utilities
  451. ----------------------------------------------------------------------------------------------------------------------*/
  452. // Computes the intersection of the two ranges. Will return fresh date clones in a range.
  453. // Returns undefined if no intersection.
  454. // Expects all dates to be normalized to the same timezone beforehand.
  455. // TODO: move to date section?
  456. function intersectRanges(subjectRange, constraintRange) {
  457. var subjectStart = subjectRange.start;
  458. var subjectEnd = subjectRange.end;
  459. var constraintStart = constraintRange.start;
  460. var constraintEnd = constraintRange.end;
  461. var segStart, segEnd;
  462. var isStart, isEnd;
  463. if (subjectEnd > constraintStart && subjectStart < constraintEnd) { // in bounds at all?
  464. if (subjectStart >= constraintStart) {
  465. segStart = subjectStart.clone();
  466. isStart = true;
  467. }
  468. else {
  469. segStart = constraintStart.clone();
  470. isStart = false;
  471. }
  472. if (subjectEnd <= constraintEnd) {
  473. segEnd = subjectEnd.clone();
  474. isEnd = true;
  475. }
  476. else {
  477. segEnd = constraintEnd.clone();
  478. isEnd = false;
  479. }
  480. return {
  481. start: segStart,
  482. end: segEnd,
  483. isStart: isStart,
  484. isEnd: isEnd
  485. };
  486. }
  487. }
  488. /* Date Utilities
  489. ----------------------------------------------------------------------------------------------------------------------*/
  490. FC.computeIntervalUnit = computeIntervalUnit;
  491. FC.divideRangeByDuration = divideRangeByDuration;
  492. FC.divideDurationByDuration = divideDurationByDuration;
  493. FC.multiplyDuration = multiplyDuration;
  494. FC.durationHasTime = durationHasTime;
  495. var dayIDs = [ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ];
  496. var intervalUnits = [ 'year', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond' ];
  497. // Diffs the two moments into a Duration where full-days are recorded first, then the remaining time.
  498. // Moments will have their timezones normalized.
  499. function diffDayTime(a, b) {
  500. return moment.duration({
  501. days: a.clone().stripTime().diff(b.clone().stripTime(), 'days'),
  502. ms: a.time() - b.time() // time-of-day from day start. disregards timezone
  503. });
  504. }
  505. // Diffs the two moments via their start-of-day (regardless of timezone). Produces whole-day durations.
  506. function diffDay(a, b) {
  507. return moment.duration({
  508. days: a.clone().stripTime().diff(b.clone().stripTime(), 'days')
  509. });
  510. }
  511. // Diffs two moments, producing a duration, made of a whole-unit-increment of the given unit. Uses rounding.
  512. function diffByUnit(a, b, unit) {
  513. return moment.duration(
  514. Math.round(a.diff(b, unit, true)), // returnFloat=true
  515. unit
  516. );
  517. }
  518. // Computes the unit name of the largest whole-unit period of time.
  519. // For example, 48 hours will be "days" whereas 49 hours will be "hours".
  520. // Accepts start/end, a range object, or an original duration object.
  521. function computeIntervalUnit(start, end) {
  522. var i, unit;
  523. var val;
  524. for (i = 0; i < intervalUnits.length; i++) {
  525. unit = intervalUnits[i];
  526. val = computeRangeAs(unit, start, end);
  527. if (val >= 1 && isInt(val)) {
  528. break;
  529. }
  530. }
  531. return unit; // will be "milliseconds" if nothing else matches
  532. }
  533. // Computes the number of units (like "hours") in the given range.
  534. // Range can be a {start,end} object, separate start/end args, or a Duration.
  535. // Results are based on Moment's .as() and .diff() methods, so results can depend on internal handling
  536. // of month-diffing logic (which tends to vary from version to version).
  537. function computeRangeAs(unit, start, end) {
  538. if (end != null) { // given start, end
  539. return end.diff(start, unit, true);
  540. }
  541. else if (moment.isDuration(start)) { // given duration
  542. return start.as(unit);
  543. }
  544. else { // given { start, end } range object
  545. return start.end.diff(start.start, unit, true);
  546. }
  547. }
  548. // Intelligently divides a range (specified by a start/end params) by a duration
  549. function divideRangeByDuration(start, end, dur) {
  550. var months;
  551. if (durationHasTime(dur)) {
  552. return (end - start) / dur;
  553. }
  554. months = dur.asMonths();
  555. if (Math.abs(months) >= 1 && isInt(months)) {
  556. return end.diff(start, 'months', true) / months;
  557. }
  558. return end.diff(start, 'days', true) / dur.asDays();
  559. }
  560. // Intelligently divides one duration by another
  561. function divideDurationByDuration(dur1, dur2) {
  562. var months1, months2;
  563. if (durationHasTime(dur1) || durationHasTime(dur2)) {
  564. return dur1 / dur2;
  565. }
  566. months1 = dur1.asMonths();
  567. months2 = dur2.asMonths();
  568. if (
  569. Math.abs(months1) >= 1 && isInt(months1) &&
  570. Math.abs(months2) >= 1 && isInt(months2)
  571. ) {
  572. return months1 / months2;
  573. }
  574. return dur1.asDays() / dur2.asDays();
  575. }
  576. // Intelligently multiplies a duration by a number
  577. function multiplyDuration(dur, n) {
  578. var months;
  579. if (durationHasTime(dur)) {
  580. return moment.duration(dur * n);
  581. }
  582. months = dur.asMonths();
  583. if (Math.abs(months) >= 1 && isInt(months)) {
  584. return moment.duration({ months: months * n });
  585. }
  586. return moment.duration({ days: dur.asDays() * n });
  587. }
  588. // Returns a boolean about whether the given duration has any time parts (hours/minutes/seconds/ms)
  589. function durationHasTime(dur) {
  590. return Boolean(dur.hours() || dur.minutes() || dur.seconds() || dur.milliseconds());
  591. }
  592. function isNativeDate(input) {
  593. return Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date;
  594. }
  595. // Returns a boolean about whether the given input is a time string, like "06:40:00" or "06:00"
  596. function isTimeString(str) {
  597. return /^\d+\:\d+(?:\:\d+\.?(?:\d{3})?)?$/.test(str);
  598. }
  599. /* Logging and Debug
  600. ----------------------------------------------------------------------------------------------------------------------*/
  601. FC.log = function() {
  602. var console = window.console;
  603. if (console && console.log) {
  604. return console.log.apply(console, arguments);
  605. }
  606. };
  607. FC.warn = function() {
  608. var console = window.console;
  609. if (console && console.warn) {
  610. return console.warn.apply(console, arguments);
  611. }
  612. else {
  613. return FC.log.apply(FC, arguments);
  614. }
  615. };
  616. /* General Utilities
  617. ----------------------------------------------------------------------------------------------------------------------*/
  618. var hasOwnPropMethod = {}.hasOwnProperty;
  619. // Merges an array of objects into a single object.
  620. // The second argument allows for an array of property names who's object values will be merged together.
  621. function mergeProps(propObjs, complexProps) {
  622. var dest = {};
  623. var i, name;
  624. var complexObjs;
  625. var j, val;
  626. var props;
  627. if (complexProps) {
  628. for (i = 0; i < complexProps.length; i++) {
  629. name = complexProps[i];
  630. complexObjs = [];
  631. // collect the trailing object values, stopping when a non-object is discovered
  632. for (j = propObjs.length - 1; j >= 0; j--) {
  633. val = propObjs[j][name];
  634. if (typeof val === 'object') {
  635. complexObjs.unshift(val);
  636. }
  637. else if (val !== undefined) {
  638. dest[name] = val; // if there were no objects, this value will be used
  639. break;
  640. }
  641. }
  642. // if the trailing values were objects, use the merged value
  643. if (complexObjs.length) {
  644. dest[name] = mergeProps(complexObjs);
  645. }
  646. }
  647. }
  648. // copy values into the destination, going from last to first
  649. for (i = propObjs.length - 1; i >= 0; i--) {
  650. props = propObjs[i];
  651. for (name in props) {
  652. if (!(name in dest)) { // if already assigned by previous props or complex props, don't reassign
  653. dest[name] = props[name];
  654. }
  655. }
  656. }
  657. return dest;
  658. }
  659. // Create an object that has the given prototype. Just like Object.create
  660. function createObject(proto) {
  661. var f = function() {};
  662. f.prototype = proto;
  663. return new f();
  664. }
  665. FC.createObject = createObject;
  666. function copyOwnProps(src, dest) {
  667. for (var name in src) {
  668. if (hasOwnProp(src, name)) {
  669. dest[name] = src[name];
  670. }
  671. }
  672. }
  673. function hasOwnProp(obj, name) {
  674. return hasOwnPropMethod.call(obj, name);
  675. }
  676. // Is the given value a non-object non-function value?
  677. function isAtomic(val) {
  678. return /undefined|null|boolean|number|string/.test($.type(val));
  679. }
  680. function applyAll(functions, thisObj, args) {
  681. if ($.isFunction(functions)) {
  682. functions = [ functions ];
  683. }
  684. if (functions) {
  685. var i;
  686. var ret;
  687. for (i=0; i<functions.length; i++) {
  688. ret = functions[i].apply(thisObj, args) || ret;
  689. }
  690. return ret;
  691. }
  692. }
  693. function firstDefined() {
  694. for (var i=0; i<arguments.length; i++) {
  695. if (arguments[i] !== undefined) {
  696. return arguments[i];
  697. }
  698. }
  699. }
  700. function htmlEscape(s) {
  701. return (s + '').replace(/&/g, '&amp;')
  702. .replace(/</g, '&lt;')
  703. .replace(/>/g, '&gt;')
  704. .replace(/'/g, '&#039;')
  705. .replace(/"/g, '&quot;')
  706. .replace(/\n/g, '<br />');
  707. }
  708. function stripHtmlEntities(text) {
  709. return text.replace(/&.*?;/g, '');
  710. }
  711. // Given a hash of CSS properties, returns a string of CSS.
  712. // Uses property names as-is (no camel-case conversion). Will not make statements for null/undefined values.
  713. function cssToStr(cssProps) {
  714. var statements = [];
  715. $.each(cssProps, function(name, val) {
  716. if (val != null) {
  717. statements.push(name + ':' + val);
  718. }
  719. });
  720. return statements.join(';');
  721. }
  722. // Given an object hash of HTML attribute names to values,
  723. // generates a string that can be injected between < > in HTML
  724. function attrsToStr(attrs) {
  725. var parts = [];
  726. $.each(attrs, function(name, val) {
  727. if (val != null) {
  728. parts.push(name + '="' + htmlEscape(val) + '"');
  729. }
  730. });
  731. return parts.join(' ');
  732. }
  733. function capitaliseFirstLetter(str) {
  734. return str.charAt(0).toUpperCase() + str.slice(1);
  735. }
  736. function compareNumbers(a, b) { // for .sort()
  737. return a - b;
  738. }
  739. function isInt(n) {
  740. return n % 1 === 0;
  741. }
  742. // Returns a method bound to the given object context.
  743. // Just like one of the jQuery.proxy signatures, but without the undesired behavior of treating the same method with
  744. // different contexts as identical when binding/unbinding events.
  745. function proxy(obj, methodName) {
  746. var method = obj[methodName];
  747. return function() {
  748. return method.apply(obj, arguments);
  749. };
  750. }
  751. // Returns a function, that, as long as it continues to be invoked, will not
  752. // be triggered. The function will be called after it stops being called for
  753. // N milliseconds. If `immediate` is passed, trigger the function on the
  754. // leading edge, instead of the trailing.
  755. // https://github.com/jashkenas/underscore/blob/1.6.0/underscore.js#L714
  756. function debounce(func, wait, immediate) {
  757. var timeout, args, context, timestamp, result;
  758. var later = function() {
  759. var last = +new Date() - timestamp;
  760. if (last < wait) {
  761. timeout = setTimeout(later, wait - last);
  762. }
  763. else {
  764. timeout = null;
  765. if (!immediate) {
  766. result = func.apply(context, args);
  767. context = args = null;
  768. }
  769. }
  770. };
  771. return function() {
  772. context = this;
  773. args = arguments;
  774. timestamp = +new Date();
  775. var callNow = immediate && !timeout;
  776. if (!timeout) {
  777. timeout = setTimeout(later, wait);
  778. }
  779. if (callNow) {
  780. result = func.apply(context, args);
  781. context = args = null;
  782. }
  783. return result;
  784. };
  785. }
  786. ;;
  787. /*
  788. GENERAL NOTE on moments throughout the *entire rest* of the codebase:
  789. All moments are assumed to be ambiguously-zoned unless otherwise noted,
  790. with the NOTABLE EXCEOPTION of start/end dates that live on *Event Objects*.
  791. Ambiguously-TIMED moments are assumed to be ambiguously-zoned by nature.
  792. */
  793. var ambigDateOfMonthRegex = /^\s*\d{4}-\d\d$/;
  794. var ambigTimeOrZoneRegex =
  795. /^\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+)?)?)?)?)?$/;
  796. var newMomentProto = moment.fn; // where we will attach our new methods
  797. var oldMomentProto = $.extend({}, newMomentProto); // copy of original moment methods
  798. // tell momentjs to transfer these properties upon clone
  799. var momentProperties = moment.momentProperties;
  800. momentProperties.push('_fullCalendar');
  801. momentProperties.push('_ambigTime');
  802. momentProperties.push('_ambigZone');
  803. // Creating
  804. // -------------------------------------------------------------------------------------------------
  805. // Creates a new moment, similar to the vanilla moment(...) constructor, but with
  806. // extra features (ambiguous time, enhanced formatting). When given an existing moment,
  807. // it will function as a clone (and retain the zone of the moment). Anything else will
  808. // result in a moment in the local zone.
  809. FC.moment = function() {
  810. return makeMoment(arguments);
  811. };
  812. // Sames as FC.moment, but forces the resulting moment to be in the UTC timezone.
  813. FC.moment.utc = function() {
  814. var mom = makeMoment(arguments, true);
  815. // Force it into UTC because makeMoment doesn't guarantee it
  816. // (if given a pre-existing moment for example)
  817. if (mom.hasTime()) { // don't give ambiguously-timed moments a UTC zone
  818. mom.utc();
  819. }
  820. return mom;
  821. };
  822. // Same as FC.moment, but when given an ISO8601 string, the timezone offset is preserved.
  823. // ISO8601 strings with no timezone offset will become ambiguously zoned.
  824. FC.moment.parseZone = function() {
  825. return makeMoment(arguments, true, true);
  826. };
  827. // Builds an enhanced moment from args. When given an existing moment, it clones. When given a
  828. // native Date, or called with no arguments (the current time), the resulting moment will be local.
  829. // Anything else needs to be "parsed" (a string or an array), and will be affected by:
  830. // parseAsUTC - if there is no zone information, should we parse the input in UTC?
  831. // parseZone - if there is zone information, should we force the zone of the moment?
  832. function makeMoment(args, parseAsUTC, parseZone) {
  833. var input = args[0];
  834. var isSingleString = args.length == 1 && typeof input === 'string';
  835. var isAmbigTime;
  836. var isAmbigZone;
  837. var ambigMatch;
  838. var mom;
  839. if (moment.isMoment(input) || isNativeDate(input) || input === undefined) {
  840. mom = moment.apply(null, args);
  841. }
  842. else { // "parsing" is required
  843. isAmbigTime = false;
  844. isAmbigZone = false;
  845. if (isSingleString) {
  846. if (ambigDateOfMonthRegex.test(input)) {
  847. // accept strings like '2014-05', but convert to the first of the month
  848. input += '-01';
  849. args = [ input ]; // for when we pass it on to moment's constructor
  850. isAmbigTime = true;
  851. isAmbigZone = true;
  852. }
  853. else if ((ambigMatch = ambigTimeOrZoneRegex.exec(input))) {
  854. isAmbigTime = !ambigMatch[5]; // no time part?
  855. isAmbigZone = true;
  856. }
  857. }
  858. else if ($.isArray(input)) {
  859. // arrays have no timezone information, so assume ambiguous zone
  860. isAmbigZone = true;
  861. }
  862. // otherwise, probably a string with a format
  863. if (parseAsUTC || isAmbigTime) {
  864. mom = moment.utc.apply(moment, args);
  865. }
  866. else {
  867. mom = moment.apply(null, args);
  868. }
  869. if (isAmbigTime) {
  870. mom._ambigTime = true;
  871. mom._ambigZone = true; // ambiguous time always means ambiguous zone
  872. }
  873. else if (parseZone) { // let's record the inputted zone somehow
  874. if (isAmbigZone) {
  875. mom._ambigZone = true;
  876. }
  877. else if (isSingleString) {
  878. mom.utcOffset(input); // if not a valid zone, will assign UTC
  879. }
  880. }
  881. }
  882. mom._fullCalendar = true; // flag for extended functionality
  883. return mom;
  884. }
  885. // Week Number
  886. // -------------------------------------------------------------------------------------------------
  887. // Returns the week number, considering the locale's custom week number calcuation
  888. // `weeks` is an alias for `week`
  889. newMomentProto.week = newMomentProto.weeks = function(input) {
  890. var weekCalc = this._locale._fullCalendar_weekCalc;
  891. if (input == null && typeof weekCalc === 'function') { // custom function only works for getter
  892. return weekCalc(this);
  893. }
  894. else if (weekCalc === 'ISO') {
  895. return oldMomentProto.isoWeek.apply(this, arguments); // ISO getter/setter
  896. }
  897. return oldMomentProto.week.apply(this, arguments); // local getter/setter
  898. };
  899. // Time-of-day
  900. // -------------------------------------------------------------------------------------------------
  901. // GETTER
  902. // Returns a Duration with the hours/minutes/seconds/ms values of the moment.
  903. // If the moment has an ambiguous time, a duration of 00:00 will be returned.
  904. //
  905. // SETTER
  906. // You can supply a Duration, a Moment, or a Duration-like argument.
  907. // When setting the time, and the moment has an ambiguous time, it then becomes unambiguous.
  908. newMomentProto.time = function(time) {
  909. // Fallback to the original method (if there is one) if this moment wasn't created via FullCalendar.
  910. // `time` is a generic enough method name where this precaution is necessary to avoid collisions w/ other plugins.
  911. if (!this._fullCalendar) {
  912. return oldMomentProto.time.apply(this, arguments);
  913. }
  914. if (time == null) { // getter
  915. return moment.duration({
  916. hours: this.hours(),
  917. minutes: this.minutes(),
  918. seconds: this.seconds(),
  919. milliseconds: this.milliseconds()
  920. });
  921. }
  922. else { // setter
  923. this._ambigTime = false; // mark that the moment now has a time
  924. if (!moment.isDuration(time) && !moment.isMoment(time)) {
  925. time = moment.duration(time);
  926. }
  927. // The day value should cause overflow (so 24 hours becomes 00:00:00 of next day).
  928. // Only for Duration times, not Moment times.
  929. var dayHours = 0;
  930. if (moment.isDuration(time)) {
  931. dayHours = Math.floor(time.asDays()) * 24;
  932. }
  933. // We need to set the individual fields.
  934. // Can't use startOf('day') then add duration. In case of DST at start of day.
  935. return this.hours(dayHours + time.hours())
  936. .minutes(time.minutes())
  937. .seconds(time.seconds())
  938. .milliseconds(time.milliseconds());
  939. }
  940. };
  941. // Converts the moment to UTC, stripping out its time-of-day and timezone offset,
  942. // but preserving its YMD. A moment with a stripped time will display no time
  943. // nor timezone offset when .format() is called.
  944. newMomentProto.stripTime = function() {
  945. if (!this._ambigTime) {
  946. this.utc(true); // keepLocalTime=true (for keeping *date* value)
  947. // set time to zero
  948. this.set({
  949. hours: 0,
  950. minutes: 0,
  951. seconds: 0,
  952. ms: 0
  953. });
  954. // Mark the time as ambiguous. This needs to happen after the .utc() call, which might call .utcOffset(),
  955. // which clears all ambig flags.
  956. this._ambigTime = true;
  957. this._ambigZone = true; // if ambiguous time, also ambiguous timezone offset
  958. }
  959. return this; // for chaining
  960. };
  961. // Returns if the moment has a non-ambiguous time (boolean)
  962. newMomentProto.hasTime = function() {
  963. return !this._ambigTime;
  964. };
  965. // Timezone
  966. // -------------------------------------------------------------------------------------------------
  967. // Converts the moment to UTC, stripping out its timezone offset, but preserving its
  968. // YMD and time-of-day. A moment with a stripped timezone offset will display no
  969. // timezone offset when .format() is called.
  970. newMomentProto.stripZone = function() {
  971. var wasAmbigTime;
  972. if (!this._ambigZone) {
  973. wasAmbigTime = this._ambigTime;
  974. this.utc(true); // keepLocalTime=true (for keeping date and time values)
  975. // the above call to .utc()/.utcOffset() unfortunately might clear the ambig flags, so restore
  976. this._ambigTime = wasAmbigTime || false;
  977. // Mark the zone as ambiguous. This needs to happen after the .utc() call, which might call .utcOffset(),
  978. // which clears the ambig flags.
  979. this._ambigZone = true;
  980. }
  981. return this; // for chaining
  982. };
  983. // Returns of the moment has a non-ambiguous timezone offset (boolean)
  984. newMomentProto.hasZone = function() {
  985. return !this._ambigZone;
  986. };
  987. // implicitly marks a zone
  988. newMomentProto.local = function(keepLocalTime) {
  989. // for when converting from ambiguously-zoned to local,
  990. // keep the time values when converting from UTC -> local
  991. oldMomentProto.local.call(this, this._ambigZone || keepLocalTime);
  992. // ensure non-ambiguous
  993. // this probably already happened via local() -> utcOffset(), but don't rely on Moment's internals
  994. this._ambigTime = false;
  995. this._ambigZone = false;
  996. return this; // for chaining
  997. };
  998. // implicitly marks a zone
  999. newMomentProto.utc = function(keepLocalTime) {
  1000. oldMomentProto.utc.call(this, keepLocalTime);
  1001. // ensure non-ambiguous
  1002. // this probably already happened via utc() -> utcOffset(), but don't rely on Moment's internals
  1003. this._ambigTime = false;
  1004. this._ambigZone = false;
  1005. return this;
  1006. };
  1007. // implicitly marks a zone (will probably get called upon .utc() and .local())
  1008. newMomentProto.utcOffset = function(tzo) {
  1009. if (tzo != null) { // setter
  1010. // these assignments needs to happen before the original zone method is called.
  1011. // I forget why, something to do with a browser crash.
  1012. this._ambigTime = false;
  1013. this._ambigZone = false;
  1014. }
  1015. return oldMomentProto.utcOffset.apply(this, arguments);
  1016. };
  1017. // Formatting
  1018. // -------------------------------------------------------------------------------------------------
  1019. newMomentProto.format = function() {
  1020. if (this._fullCalendar && arguments[0]) { // an enhanced moment? and a format string provided?
  1021. return formatDate(this, arguments[0]); // our extended formatting
  1022. }
  1023. if (this._ambigTime) {
  1024. return oldMomentFormat(this, 'YYYY-MM-DD');
  1025. }
  1026. if (this._ambigZone) {
  1027. return oldMomentFormat(this, 'YYYY-MM-DD[T]HH:mm:ss');
  1028. }
  1029. return oldMomentProto.format.apply(this, arguments);
  1030. };
  1031. newMomentProto.toISOString = function() {
  1032. if (this._ambigTime) {
  1033. return oldMomentFormat(this, 'YYYY-MM-DD');
  1034. }
  1035. if (this._ambigZone) {
  1036. return oldMomentFormat(this, 'YYYY-MM-DD[T]HH:mm:ss');
  1037. }
  1038. return oldMomentProto.toISOString.apply(this, arguments);
  1039. };
  1040. ;;
  1041. (function() {
  1042. // exports
  1043. FC.formatDate = formatDate;
  1044. FC.formatRange = formatRange;
  1045. FC.oldMomentFormat = oldMomentFormat;
  1046. FC.queryMostGranularFormatUnit = queryMostGranularFormatUnit;
  1047. // Config
  1048. // ---------------------------------------------------------------------------------------------------------------------
  1049. /*
  1050. Inserted between chunks in the fake ("intermediate") formatting string.
  1051. Important that it passes as whitespace (\s) because moment often identifies non-standalone months
  1052. via a regexp with an \s.
  1053. */
  1054. var PART_SEPARATOR = '\u000b'; // vertical tab
  1055. /*
  1056. Inserted as the first character of a literal-text chunk to indicate that the literal text is not actually literal text,
  1057. but rather, a "special" token that has custom rendering (see specialTokens map).
  1058. */
  1059. var SPECIAL_TOKEN_MARKER = '\u001f'; // information separator 1
  1060. /*
  1061. Inserted at the beginning and end of a span of text that must have non-zero numeric characters.
  1062. Handling of these markers is done in a post-processing step at the very end of text rendering.
  1063. */
  1064. var MAYBE_MARKER = '\u001e'; // information separator 2
  1065. var MAYBE_REGEXP = new RegExp(MAYBE_MARKER + '([^' + MAYBE_MARKER + ']*)' + MAYBE_MARKER, 'g'); // must be global
  1066. /*
  1067. Addition formatting tokens we want recognized
  1068. */
  1069. var specialTokens = {
  1070. t: function(date) { // "a" or "p"
  1071. return oldMomentFormat(date, 'a').charAt(0);
  1072. },
  1073. T: function(date) { // "A" or "P"
  1074. return oldMomentFormat(date, 'A').charAt(0);
  1075. }
  1076. };
  1077. /*
  1078. The first characters of formatting tokens for units that are 1 day or larger.
  1079. `value` is for ranking relative size (lower means bigger).
  1080. `unit` is a normalized unit, used for comparing moments.
  1081. */
  1082. var largeTokenMap = {
  1083. Y: { value: 1, unit: 'year' },
  1084. M: { value: 2, unit: 'month' },
  1085. W: { value: 3, unit: 'week' }, // ISO week
  1086. w: { value: 3, unit: 'week' }, // local week
  1087. D: { value: 4, unit: 'day' }, // day of month
  1088. d: { value: 4, unit: 'day' } // day of week
  1089. };
  1090. // Single Date Formatting
  1091. // ---------------------------------------------------------------------------------------------------------------------
  1092. /*
  1093. Formats `date` with a Moment formatting string, but allow our non-zero areas and special token
  1094. */
  1095. function formatDate(date, formatStr) {
  1096. return renderFakeFormatString(
  1097. getParsedFormatString(formatStr).fakeFormatString,
  1098. date
  1099. );
  1100. }
  1101. /*
  1102. Call this if you want Moment's original format method to be used
  1103. */
  1104. function oldMomentFormat(mom, formatStr) {
  1105. return oldMomentProto.format.call(mom, formatStr); // oldMomentProto defined in moment-ext.js
  1106. }
  1107. // Date Range Formatting
  1108. // -------------------------------------------------------------------------------------------------
  1109. // TODO: make it work with timezone offset
  1110. /*
  1111. Using a formatting string meant for a single date, generate a range string, like
  1112. "Sep 2 - 9 2013", that intelligently inserts a separator where the dates differ.
  1113. If the dates are the same as far as the format string is concerned, just return a single
  1114. rendering of one date, without any separator.
  1115. */
  1116. function formatRange(date1, date2, formatStr, separator, isRTL) {
  1117. var localeData;
  1118. date1 = FC.moment.parseZone(date1);
  1119. date2 = FC.moment.parseZone(date2);
  1120. localeData = date1.localeData();
  1121. // Expand localized format strings, like "LL" -> "MMMM D YYYY".
  1122. // BTW, this is not important for `formatDate` because it is impossible to put custom tokens
  1123. // or non-zero areas in Moment's localized format strings.
  1124. formatStr = localeData.longDateFormat(formatStr) || formatStr;
  1125. return renderParsedFormat(
  1126. getParsedFormatString(formatStr),
  1127. date1,
  1128. date2,
  1129. separator || ' - ',
  1130. isRTL
  1131. );
  1132. }
  1133. /*
  1134. Renders a range with an already-parsed format string.
  1135. */
  1136. function renderParsedFormat(parsedFormat, date1, date2, separator, isRTL) {
  1137. var sameUnits = parsedFormat.sameUnits;
  1138. var unzonedDate1 = date1.clone().stripZone(); // for same-unit comparisons
  1139. var unzonedDate2 = date2.clone().stripZone(); // "
  1140. var renderedParts1 = renderFakeFormatStringParts(parsedFormat.fakeFormatString, date1);
  1141. var renderedParts2 = renderFakeFormatStringParts(parsedFormat.fakeFormatString, date2);
  1142. var leftI;
  1143. var leftStr = '';
  1144. var rightI;
  1145. var rightStr = '';
  1146. var middleI;
  1147. var middleStr1 = '';
  1148. var middleStr2 = '';
  1149. var middleStr = '';
  1150. // Start at the leftmost side of the formatting string and continue until you hit a token
  1151. // that is not the same between dates.
  1152. for (
  1153. leftI = 0;
  1154. leftI < sameUnits.length && (!sameUnits[leftI] || unzonedDate1.isSame(unzonedDate2, sameUnits[leftI]));
  1155. leftI++
  1156. ) {
  1157. leftStr += renderedParts1[leftI];
  1158. }
  1159. // Similarly, start at the rightmost side of the formatting string and move left
  1160. for (
  1161. rightI = sameUnits.length - 1;
  1162. rightI > leftI && (!sameUnits[rightI] || unzonedDate1.isSame(unzonedDate2, sameUnits[rightI]));
  1163. rightI--
  1164. ) {
  1165. // If current chunk is on the boundary of unique date-content, and is a special-case
  1166. // date-formatting postfix character, then don't consume it. Consider it unique date-content.
  1167. // TODO: make configurable
  1168. if (rightI - 1 === leftI && renderedParts1[rightI] === '.') {
  1169. break;
  1170. }
  1171. rightStr = renderedParts1[rightI] + rightStr;
  1172. }
  1173. // The area in the middle is different for both of the dates.
  1174. // Collect them distinctly so we can jam them together later.
  1175. for (middleI = leftI; middleI <= rightI; middleI++) {
  1176. middleStr1 += renderedParts1[middleI];
  1177. middleStr2 += renderedParts2[middleI];
  1178. }
  1179. if (middleStr1 || middleStr2) {
  1180. if (isRTL) {
  1181. middleStr = middleStr2 + separator + middleStr1;
  1182. }
  1183. else {
  1184. middleStr = middleStr1 + separator + middleStr2;
  1185. }
  1186. }
  1187. return processMaybeMarkers(
  1188. leftStr + middleStr + rightStr
  1189. );
  1190. }
  1191. // Format String Parsing
  1192. // ---------------------------------------------------------------------------------------------------------------------
  1193. var parsedFormatStrCache = {};
  1194. /*
  1195. Returns a parsed format string, leveraging a cache.
  1196. */
  1197. function getParsedFormatString(formatStr) {
  1198. return parsedFormatStrCache[formatStr] ||
  1199. (parsedFormatStrCache[formatStr] = parseFormatString(formatStr));
  1200. }
  1201. /*
  1202. Parses a format string into the following:
  1203. - fakeFormatString: a momentJS formatting string, littered with special control characters that get post-processed.
  1204. - sameUnits: for every part in fakeFormatString, if the part is a token, the value will be a unit string (like "day"),
  1205. that indicates how similar a range's start & end must be in order to share the same formatted text.
  1206. If not a token, then the value is null.
  1207. Always a flat array (not nested liked "chunks").
  1208. */
  1209. function parseFormatString(formatStr) {
  1210. var chunks = chunkFormatString(formatStr);
  1211. return {
  1212. fakeFormatString: buildFakeFormatString(chunks),
  1213. sameUnits: buildSameUnits(chunks)
  1214. };
  1215. }
  1216. /*
  1217. Break the formatting string into an array of chunks.
  1218. A 'maybe' chunk will have nested chunks.
  1219. */
  1220. function chunkFormatString(formatStr) {
  1221. var chunks = [];
  1222. var match;
  1223. // TODO: more descrimination
  1224. // \4 is a backreference to the first character of a multi-character set.
  1225. var chunker = /\[([^\]]*)\]|\(([^\)]*)\)|(LTS|LT|(\w)\4*o?)|([^\w\[\(]+)/g;
  1226. while ((match = chunker.exec(formatStr))) {
  1227. if (match[1]) { // a literal string inside [ ... ]
  1228. chunks.push.apply(chunks, // append
  1229. splitStringLiteral(match[1])
  1230. );
  1231. }
  1232. else if (match[2]) { // non-zero formatting inside ( ... )
  1233. chunks.push({ maybe: chunkFormatString(match[2]) });
  1234. }
  1235. else if (match[3]) { // a formatting token
  1236. chunks.push({ token: match[3] });
  1237. }
  1238. else if (match[5]) { // an unenclosed literal string
  1239. chunks.push.apply(chunks, // append
  1240. splitStringLiteral(match[5])
  1241. );
  1242. }
  1243. }
  1244. return chunks;
  1245. }
  1246. /*
  1247. Potentially splits a literal-text string into multiple parts. For special cases.
  1248. */
  1249. function splitStringLiteral(s) {
  1250. if (s === '. ') {
  1251. return [ '.', ' ' ]; // for locales with periods bound to the end of each year/month/date
  1252. }
  1253. else {
  1254. return [ s ];
  1255. }
  1256. }
  1257. /*
  1258. Given chunks parsed from a real format string, generate a fake (aka "intermediate") format string with special control
  1259. characters that will eventually be given to moment for formatting, and then post-processed.
  1260. */
  1261. function buildFakeFormatString(chunks) {
  1262. var parts = [];
  1263. var i, chunk;
  1264. for (i = 0; i < chunks.length; i++) {
  1265. chunk = chunks[i];
  1266. if (typeof chunk === 'string') {
  1267. parts.push('[' + chunk + ']');
  1268. }
  1269. else if (chunk.token) {
  1270. if (chunk.token in specialTokens) {
  1271. parts.push(
  1272. SPECIAL_TOKEN_MARKER + // useful during post-processing
  1273. '[' + chunk.token + ']' // preserve as literal text
  1274. );
  1275. }
  1276. else {
  1277. parts.push(chunk.token); // unprotected text implies a format string
  1278. }
  1279. }
  1280. else if (chunk.maybe) {
  1281. parts.push(
  1282. MAYBE_MARKER + // useful during post-processing
  1283. buildFakeFormatString(chunk.maybe) +
  1284. MAYBE_MARKER
  1285. );
  1286. }
  1287. }
  1288. return parts.join(PART_SEPARATOR);
  1289. }
  1290. /*
  1291. Given parsed chunks from a real formatting string, generates an array of unit strings (like "day") that indicate
  1292. in which regard two dates must be similar in order to share range formatting text.
  1293. The `chunks` can be nested (because of "maybe" chunks), however, the returned array will be flat.
  1294. */
  1295. function buildSameUnits(chunks) {
  1296. var units = [];
  1297. var i, chunk;
  1298. var tokenInfo;
  1299. for (i = 0; i < chunks.length; i++) {
  1300. chunk = chunks[i];
  1301. if (chunk.token) {
  1302. tokenInfo = largeTokenMap[chunk.token.charAt(0)];
  1303. units.push(tokenInfo ? tokenInfo.unit : 'second'); // default to a very strict same-second
  1304. }
  1305. else if (chunk.maybe) {
  1306. units.push.apply(units, // append
  1307. buildSameUnits(chunk.maybe)
  1308. );
  1309. }
  1310. else {
  1311. units.push(null);
  1312. }
  1313. }
  1314. return units;
  1315. }
  1316. // Rendering to text
  1317. // ---------------------------------------------------------------------------------------------------------------------
  1318. /*
  1319. Formats a date with a fake format string, post-processes the control characters, then returns.
  1320. */
  1321. function renderFakeFormatString(fakeFormatString, date) {
  1322. return processMaybeMarkers(
  1323. renderFakeFormatStringParts(fakeFormatString, date).join('')
  1324. );
  1325. }
  1326. /*
  1327. Formats a date into parts that will have been post-processed, EXCEPT for the "maybe" markers.
  1328. */
  1329. function renderFakeFormatStringParts(fakeFormatString, date) {
  1330. var parts = [];
  1331. var fakeRender = oldMomentFormat(date, fakeFormatString);
  1332. var fakeParts = fakeRender.split(PART_SEPARATOR);
  1333. var i, fakePart;
  1334. for (i = 0; i < fakeParts.length; i++) {
  1335. fakePart = fakeParts[i];
  1336. if (fakePart.charAt(0) === SPECIAL_TOKEN_MARKER) {
  1337. parts.push(
  1338. // the literal string IS the token's name.
  1339. // call special token's registered function.
  1340. specialTokens[fakePart.substring(1)](date)
  1341. );
  1342. }
  1343. else {
  1344. parts.push(fakePart);
  1345. }
  1346. }
  1347. return parts;
  1348. }
  1349. /*
  1350. Accepts an almost-finally-formatted string and processes the "maybe" control characters, returning a new string.
  1351. */
  1352. function processMaybeMarkers(s) {
  1353. return s.replace(MAYBE_REGEXP, function(m0, m1) { // regex assumed to have 'g' flag
  1354. if (m1.match(/[1-9]/)) { // any non-zero numeric characters?
  1355. return m1;
  1356. }
  1357. else {
  1358. return '';
  1359. }
  1360. });
  1361. }
  1362. // Misc Utils
  1363. // -------------------------------------------------------------------------------------------------
  1364. /*
  1365. Returns a unit string, either 'year', 'month', 'day', or null for the most granular formatting token in the string.
  1366. */
  1367. function queryMostGranularFormatUnit(formatStr) {
  1368. var chunks = chunkFormatString(formatStr);
  1369. var i, chunk;
  1370. var candidate;
  1371. var best;
  1372. for (i = 0; i < chunks.length; i++) {
  1373. chunk = chunks[i];
  1374. if (chunk.token) {
  1375. candidate = largeTokenMap[chunk.token.charAt(0)];
  1376. if (candidate) {
  1377. if (!best || candidate.value > best.value) {
  1378. best = candidate;
  1379. }
  1380. }
  1381. }
  1382. }
  1383. if (best) {
  1384. return best.unit;
  1385. }
  1386. return null;
  1387. };
  1388. })();
  1389. // quick local references
  1390. var formatDate = FC.formatDate;
  1391. var formatRange = FC.formatRange;
  1392. var oldMomentFormat = FC.oldMomentFormat;
  1393. ;;
  1394. FC.Class = Class; // export
  1395. // Class that all other classes will inherit from
  1396. function Class() { }
  1397. // Called on a class to create a subclass.
  1398. // Last argument contains instance methods. Any argument before the last are considered mixins.
  1399. Class.extend = function() {
  1400. var len = arguments.length;
  1401. var i;
  1402. var members;
  1403. for (i = 0; i < len; i++) {
  1404. members = arguments[i];
  1405. if (i < len - 1) { // not the last argument?
  1406. mixIntoClass(this, members);
  1407. }
  1408. }
  1409. return extendClass(this, members || {}); // members will be undefined if no arguments
  1410. };
  1411. // Adds new member variables/methods to the class's prototype.
  1412. // Can be called with another class, or a plain object hash containing new members.
  1413. Class.mixin = function(members) {
  1414. mixIntoClass(this, members);
  1415. };
  1416. function extendClass(superClass, members) {
  1417. var subClass;
  1418. // ensure a constructor for the subclass, forwarding all arguments to the super-constructor if it doesn't exist
  1419. if (hasOwnProp(members, 'constructor')) {
  1420. subClass = members.constructor;
  1421. }
  1422. if (typeof subClass !== 'function') {
  1423. subClass = members.constructor = function() {
  1424. superClass.apply(this, arguments);
  1425. };
  1426. }
  1427. // build the base prototype for the subclass, which is an new object chained to the superclass's prototype
  1428. subClass.prototype = createObject(superClass.prototype);
  1429. // copy each member variable/method onto the the subclass's prototype
  1430. copyOwnProps(members, subClass.prototype);
  1431. // copy over all class variables/methods to the subclass, such as `extend` and `mixin`
  1432. copyOwnProps(superClass, subClass);
  1433. return subClass;
  1434. }
  1435. function mixIntoClass(theClass, members) {
  1436. copyOwnProps(members, theClass.prototype);
  1437. }
  1438. ;;
  1439. /*
  1440. Wrap jQuery's Deferred Promise object to be slightly more Promise/A+ compliant.
  1441. With the added non-standard feature of synchronously executing handlers on resolved promises,
  1442. which doesn't always happen otherwise (esp with nested .then handlers!?),
  1443. so, this makes things a lot easier, esp because jQuery 3 changed the synchronicity for Deferred objects.
  1444. TODO: write tests and more comments
  1445. */
  1446. function Promise(executor) {
  1447. var deferred = $.Deferred();
  1448. var promise = deferred.promise();
  1449. if (typeof executor === 'function') {
  1450. executor(
  1451. function(value) { // resolve
  1452. if (Promise.immediate) {
  1453. promise._value = value;
  1454. }
  1455. deferred.resolve(value);
  1456. },
  1457. function() { // reject
  1458. deferred.reject();
  1459. }
  1460. );
  1461. }
  1462. if (Promise.immediate) {
  1463. var origThen = promise.then;
  1464. promise.then = function(onFulfilled, onRejected) {
  1465. var state = promise.state();
  1466. if (state === 'resolved') {
  1467. if (typeof onFulfilled === 'function') {
  1468. return Promise.resolve(onFulfilled(promise._value));
  1469. }
  1470. }
  1471. else if (state === 'rejected') {
  1472. if (typeof onRejected === 'function') {
  1473. onRejected();
  1474. return promise; // already rejected
  1475. }
  1476. }
  1477. return origThen.call(promise, onFulfilled, onRejected);
  1478. };
  1479. }
  1480. return promise; // instanceof Promise will break :( TODO: make Promise a real class
  1481. }
  1482. FC.Promise = Promise;
  1483. Promise.immediate = true;
  1484. Promise.resolve = function(value) {
  1485. if (value && typeof value.resolve === 'function') {
  1486. return value.promise();
  1487. }
  1488. if (value && typeof value.then === 'function') {
  1489. return value;
  1490. }
  1491. else {
  1492. var deferred = $.Deferred().resolve(value);
  1493. var promise = deferred.promise();
  1494. if (Promise.immediate) {
  1495. var origThen = promise.then;
  1496. promise._value = value;
  1497. promise.then = function(onFulfilled, onRejected) {
  1498. if (typeof onFulfilled === 'function') {
  1499. return Promise.resolve(onFulfilled(value));
  1500. }
  1501. return origThen.call(promise, onFulfilled, onRejected);
  1502. };
  1503. }
  1504. return promise;
  1505. }
  1506. };
  1507. Promise.reject = function() {
  1508. return $.Deferred().reject().promise();
  1509. };
  1510. Promise.all = function(inputs) {
  1511. var hasAllValues = false;
  1512. var values;
  1513. var i, input;
  1514. if (Promise.immediate) {
  1515. hasAllValues = true;
  1516. values = [];
  1517. for (i = 0; i < inputs.length; i++) {
  1518. input = inputs[i];
  1519. if (input && typeof input.state === 'function' && input.state() === 'resolved' && ('_value' in input)) {
  1520. values.push(input._value);
  1521. }
  1522. else if (input && typeof input.then === 'function') {
  1523. hasAllValues = false;
  1524. break;
  1525. }
  1526. else {
  1527. values.push(input);
  1528. }
  1529. }
  1530. }
  1531. if (hasAllValues) {
  1532. return Promise.resolve(values);
  1533. }
  1534. else {
  1535. return $.when.apply($.when, inputs).then(function() {
  1536. return $.when($.makeArray(arguments));
  1537. });
  1538. }
  1539. };
  1540. ;;
  1541. // TODO: write tests and clean up code
  1542. function TaskQueue(debounceWait) {
  1543. var q = []; // array of runFuncs
  1544. function addTask(taskFunc) {
  1545. return new Promise(function(resolve) {
  1546. // should run this function when it's taskFunc's turn to run.
  1547. // responsible for popping itself off the queue.
  1548. var runFunc = function() {
  1549. Promise.resolve(taskFunc()) // result might be async, coerce to promise
  1550. .then(resolve) // resolve TaskQueue::push's promise, for the caller. will receive result of taskFunc.
  1551. .then(function() {
  1552. q.shift(); // pop itself off
  1553. // run the next task, if any
  1554. if (q.length) {
  1555. q[0]();
  1556. }
  1557. });
  1558. };
  1559. // always put the task at the end of the queue, BEFORE running the task
  1560. q.push(runFunc);
  1561. // if it's the only task in the queue, run immediately
  1562. if (q.length === 1) {
  1563. runFunc();
  1564. }
  1565. });
  1566. }
  1567. this.add = // potentially debounce, for the public method
  1568. typeof debounceWait === 'number' ?
  1569. debounce(addTask, debounceWait) :
  1570. addTask; // if not a number (null/undefined/false), no debounce at all
  1571. this.addQuickly = addTask; // guaranteed no debounce
  1572. }
  1573. FC.TaskQueue = TaskQueue;
  1574. /*
  1575. q = new TaskQueue();
  1576. function work(i) {
  1577. return q.push(function() {
  1578. trigger();
  1579. console.log('work' + i);
  1580. });
  1581. }
  1582. var cnt = 0;
  1583. function trigger() {
  1584. if (cnt < 5) {
  1585. cnt++;
  1586. work(cnt);
  1587. }
  1588. }
  1589. work(9);
  1590. */
  1591. ;;
  1592. var EmitterMixin = FC.EmitterMixin = {
  1593. // jQuery-ification via $(this) allows a non-DOM object to have
  1594. // the same event handling capabilities (including namespaces).
  1595. on: function(types, handler) {
  1596. $(this).on(types, this._prepareIntercept(handler));
  1597. return this; // for chaining
  1598. },
  1599. one: function(types, handler) {
  1600. $(this).one(types, this._prepareIntercept(handler));
  1601. return this; // for chaining
  1602. },
  1603. _prepareIntercept: function(handler) {
  1604. // handlers are always called with an "event" object as their first param.
  1605. // sneak the `this` context and arguments into the extra parameter object
  1606. // and forward them on to the original handler.
  1607. var intercept = function(ev, extra) {
  1608. return handler.apply(
  1609. extra.context || this,
  1610. extra.args || []
  1611. );
  1612. };
  1613. // mimick jQuery's internal "proxy" system (risky, I know)
  1614. // causing all functions with the same .guid to appear to be the same.
  1615. // https://github.com/jquery/jquery/blob/2.2.4/src/core.js#L448
  1616. // this is needed for calling .off with the original non-intercept handler.
  1617. if (!handler.guid) {
  1618. handler.guid = $.guid++;
  1619. }
  1620. intercept.guid = handler.guid;
  1621. return intercept;
  1622. },
  1623. off: function(types, handler) {
  1624. $(this).off(types, handler);
  1625. return this; // for chaining
  1626. },
  1627. trigger: function(types) {
  1628. var args = Array.prototype.slice.call(arguments, 1); // arguments after the first
  1629. // pass in "extra" info to the intercept
  1630. $(this).triggerHandler(types, { args: args });
  1631. return this; // for chaining
  1632. },
  1633. triggerWith: function(types, context, args) {
  1634. // `triggerHandler` is less reliant on the DOM compared to `trigger`.
  1635. // pass in "extra" info to the intercept.
  1636. $(this).triggerHandler(types, { context: context, args: args });
  1637. return this; // for chaining
  1638. }
  1639. };
  1640. ;;
  1641. /*
  1642. Utility methods for easily listening to events on another object,
  1643. and more importantly, easily unlistening from them.
  1644. */
  1645. var ListenerMixin = FC.ListenerMixin = (function() {
  1646. var guid = 0;
  1647. var ListenerMixin = {
  1648. listenerId: null,
  1649. /*
  1650. Given an `other` object that has on/off methods, bind the given `callback` to an event by the given name.
  1651. The `callback` will be called with the `this` context of the object that .listenTo is being called on.
  1652. Can be called:
  1653. .listenTo(other, eventName, callback)
  1654. OR
  1655. .listenTo(other, {
  1656. eventName1: callback1,
  1657. eventName2: callback2
  1658. })
  1659. */
  1660. listenTo: function(other, arg, callback) {
  1661. if (typeof arg === 'object') { // given dictionary of callbacks
  1662. for (var eventName in arg) {
  1663. if (arg.hasOwnProperty(eventName)) {
  1664. this.listenTo(other, eventName, arg[eventName]);
  1665. }
  1666. }
  1667. }
  1668. else if (typeof arg === 'string') {
  1669. other.on(
  1670. arg + '.' + this.getListenerNamespace(), // use event namespacing to identify this object
  1671. $.proxy(callback, this) // always use `this` context
  1672. // the usually-undesired jQuery guid behavior doesn't matter,
  1673. // because we always unbind via namespace
  1674. );
  1675. }
  1676. },
  1677. /*
  1678. Causes the current object to stop listening to events on the `other` object.
  1679. `eventName` is optional. If omitted, will stop listening to ALL events on `other`.
  1680. */
  1681. stopListeningTo: function(other, eventName) {
  1682. other.off((eventName || '') + '.' + this.getListenerNamespace());
  1683. },
  1684. /*
  1685. Returns a string, unique to this object, to be used for event namespacing
  1686. */
  1687. getListenerNamespace: function() {
  1688. if (this.listenerId == null) {
  1689. this.listenerId = guid++;
  1690. }
  1691. return '_listener' + this.listenerId;
  1692. }
  1693. };
  1694. return ListenerMixin;
  1695. })();
  1696. ;;
  1697. /* A rectangular panel that is absolutely positioned over other content
  1698. ------------------------------------------------------------------------------------------------------------------------
  1699. Options:
  1700. - className (string)
  1701. - content (HTML string or jQuery element set)
  1702. - parentEl
  1703. - top
  1704. - left
  1705. - right (the x coord of where the right edge should be. not a "CSS" right)
  1706. - autoHide (boolean)
  1707. - show (callback)
  1708. - hide (callback)
  1709. */
  1710. var Popover = Class.extend(ListenerMixin, {
  1711. isHidden: true,
  1712. options: null,
  1713. el: null, // the container element for the popover. generated by this object
  1714. margin: 10, // the space required between the popover and the edges of the scroll container
  1715. constructor: function(options) {
  1716. this.options = options || {};
  1717. },
  1718. // Shows the popover on the specified position. Renders it if not already
  1719. show: function() {
  1720. if (this.isHidden) {
  1721. if (!this.el) {
  1722. this.render();
  1723. }
  1724. this.el.show();
  1725. this.position();
  1726. this.isHidden = false;
  1727. this.trigger('show');
  1728. }
  1729. },
  1730. // Hides the popover, through CSS, but does not remove it from the DOM
  1731. hide: function() {
  1732. if (!this.isHidden) {
  1733. this.el.hide();
  1734. this.isHidden = true;
  1735. this.trigger('hide');
  1736. }
  1737. },
  1738. // Creates `this.el` and renders content inside of it
  1739. render: function() {
  1740. var _this = this;
  1741. var options = this.options;
  1742. this.el = $('<div class="fc-popover"/>')
  1743. .addClass(options.className || '')
  1744. .css({
  1745. // position initially to the top left to avoid creating scrollbars
  1746. top: 0,
  1747. left: 0
  1748. })
  1749. .append(options.content)
  1750. .appendTo(options.parentEl);
  1751. // when a click happens on anything inside with a 'fc-close' className, hide the popover
  1752. this.el.on('click', '.fc-close', function() {
  1753. _this.hide();
  1754. });
  1755. if (options.autoHide) {
  1756. this.listenTo($(document), 'mousedown', this.documentMousedown);
  1757. }
  1758. },
  1759. // Triggered when the user clicks *anywhere* in the document, for the autoHide feature
  1760. documentMousedown: function(ev) {
  1761. // only hide the popover if the click happened outside the popover
  1762. if (this.el && !$(ev.target).closest(this.el).length) {
  1763. this.hide();
  1764. }
  1765. },
  1766. // Hides and unregisters any handlers
  1767. removeElement: function() {
  1768. this.hide();
  1769. if (this.el) {
  1770. this.el.remove();
  1771. this.el = null;
  1772. }
  1773. this.stopListeningTo($(document), 'mousedown');
  1774. },
  1775. // Positions the popover optimally, using the top/left/right options
  1776. position: function() {
  1777. var options = this.options;
  1778. var origin = this.el.offsetParent().offset();
  1779. var width = this.el.outerWidth();
  1780. var height = this.el.outerHeight();
  1781. var windowEl = $(window);
  1782. var viewportEl = getScrollParent(this.el);
  1783. var viewportTop;
  1784. var viewportLeft;
  1785. var viewportOffset;
  1786. var top; // the "position" (not "offset") values for the popover
  1787. var left; //
  1788. // compute top and left
  1789. top = options.top || 0;
  1790. if (options.left !== undefined) {
  1791. left = options.left;
  1792. }
  1793. else if (options.right !== undefined) {
  1794. left = options.right - width; // derive the left value from the right value
  1795. }
  1796. else {
  1797. left = 0;
  1798. }
  1799. if (viewportEl.is(window) || viewportEl.is(document)) { // normalize getScrollParent's result
  1800. viewportEl = windowEl;
  1801. viewportTop = 0; // the window is always at the top left
  1802. viewportLeft = 0; // (and .offset() won't work if called here)
  1803. }
  1804. else {
  1805. viewportOffset = viewportEl.offset();
  1806. viewportTop = viewportOffset.top;
  1807. viewportLeft = viewportOffset.left;
  1808. }
  1809. // if the window is scrolled, it causes the visible area to be further down
  1810. viewportTop += windowEl.scrollTop();
  1811. viewportLeft += windowEl.scrollLeft();
  1812. // constrain to the view port. if constrained by two edges, give precedence to top/left
  1813. if (options.viewportConstrain !== false) {
  1814. top = Math.min(top, viewportTop + viewportEl.outerHeight() - height - this.margin);
  1815. top = Math.max(top, viewportTop + this.margin);
  1816. left = Math.min(left, viewportLeft + viewportEl.outerWidth() - width - this.margin);
  1817. left = Math.max(left, viewportLeft + this.margin);
  1818. }
  1819. this.el.css({
  1820. top: top - origin.top,
  1821. left: left - origin.left
  1822. });
  1823. },
  1824. // Triggers a callback. Calls a function in the option hash of the same name.
  1825. // Arguments beyond the first `name` are forwarded on.
  1826. // TODO: better code reuse for this. Repeat code
  1827. trigger: function(name) {
  1828. if (this.options[name]) {
  1829. this.options[name].apply(this, Array.prototype.slice.call(arguments, 1));
  1830. }
  1831. }
  1832. });
  1833. ;;
  1834. /*
  1835. A cache for the left/right/top/bottom/width/height values for one or more elements.
  1836. Works with both offset (from topleft document) and position (from offsetParent).
  1837. options:
  1838. - els
  1839. - isHorizontal
  1840. - isVertical
  1841. */
  1842. var CoordCache = FC.CoordCache = Class.extend({
  1843. els: null, // jQuery set (assumed to be siblings)
  1844. forcedOffsetParentEl: null, // options can override the natural offsetParent
  1845. origin: null, // {left,top} position of offsetParent of els
  1846. boundingRect: null, // constrain cordinates to this rectangle. {left,right,top,bottom} or null
  1847. isHorizontal: false, // whether to query for left/right/width
  1848. isVertical: false, // whether to query for top/bottom/height
  1849. // arrays of coordinates (offsets from topleft of document)
  1850. lefts: null,
  1851. rights: null,
  1852. tops: null,
  1853. bottoms: null,
  1854. constructor: function(options) {
  1855. this.els = $(options.els);
  1856. this.isHorizontal = options.isHorizontal;
  1857. this.isVertical = options.isVertical;
  1858. this.forcedOffsetParentEl = options.offsetParent ? $(options.offsetParent) : null;
  1859. },
  1860. // Queries the els for coordinates and stores them.
  1861. // Call this method before using and of the get* methods below.
  1862. build: function() {
  1863. var offsetParentEl = this.forcedOffsetParentEl;
  1864. if (!offsetParentEl && this.els.length > 0) {
  1865. offsetParentEl = this.els.eq(0).offsetParent();
  1866. }
  1867. this.origin = offsetParentEl ?
  1868. offsetParentEl.offset() :
  1869. null;
  1870. this.boundingRect = this.queryBoundingRect();
  1871. if (this.isHorizontal) {
  1872. this.buildElHorizontals();
  1873. }
  1874. if (this.isVertical) {
  1875. this.buildElVerticals();
  1876. }
  1877. },
  1878. // Destroys all internal data about coordinates, freeing memory
  1879. clear: function() {
  1880. this.origin = null;
  1881. this.boundingRect = null;
  1882. this.lefts = null;
  1883. this.rights = null;
  1884. this.tops = null;
  1885. this.bottoms = null;
  1886. },
  1887. // When called, if coord caches aren't built, builds them
  1888. ensureBuilt: function() {
  1889. if (!this.origin) {
  1890. this.build();
  1891. }
  1892. },
  1893. // Populates the left/right internal coordinate arrays
  1894. buildElHorizontals: function() {
  1895. var lefts = [];
  1896. var rights = [];
  1897. this.els.each(function(i, node) {
  1898. var el = $(node);
  1899. var left = el.offset().left;
  1900. var width = el.outerWidth();
  1901. lefts.push(left);
  1902. rights.push(left + width);
  1903. });
  1904. this.lefts = lefts;
  1905. this.rights = rights;
  1906. },
  1907. // Populates the top/bottom internal coordinate arrays
  1908. buildElVerticals: function() {
  1909. var tops = [];
  1910. var bottoms = [];
  1911. this.els.each(function(i, node) {
  1912. var el = $(node);
  1913. var top = el.offset().top;
  1914. var height = el.outerHeight();
  1915. tops.push(top);
  1916. bottoms.push(top + height);
  1917. });
  1918. this.tops = tops;
  1919. this.bottoms = bottoms;
  1920. },
  1921. // Given a left offset (from document left), returns the index of the el that it horizontally intersects.
  1922. // If no intersection is made, returns undefined.
  1923. getHorizontalIndex: function(leftOffset) {
  1924. this.ensureBuilt();
  1925. var lefts = this.lefts;
  1926. var rights = this.rights;
  1927. var len = lefts.length;
  1928. var i;
  1929. for (i = 0; i < len; i++) {
  1930. if (leftOffset >= lefts[i] && leftOffset < rights[i]) {
  1931. return i;
  1932. }
  1933. }
  1934. },
  1935. // Given a top offset (from document top), returns the index of the el that it vertically intersects.
  1936. // If no intersection is made, returns undefined.
  1937. getVerticalIndex: function(topOffset) {
  1938. this.ensureBuilt();
  1939. var tops = this.tops;
  1940. var bottoms = this.bottoms;
  1941. var len = tops.length;
  1942. var i;
  1943. for (i = 0; i < len; i++) {
  1944. if (topOffset >= tops[i] && topOffset < bottoms[i]) {
  1945. return i;
  1946. }
  1947. }
  1948. },
  1949. // Gets the left offset (from document left) of the element at the given index
  1950. getLeftOffset: function(leftIndex) {
  1951. this.ensureBuilt();
  1952. return this.lefts[leftIndex];
  1953. },
  1954. // Gets the left position (from offsetParent left) of the element at the given index
  1955. getLeftPosition: function(leftIndex) {
  1956. this.ensureBuilt();
  1957. return this.lefts[leftIndex] - this.origin.left;
  1958. },
  1959. // Gets the right offset (from document left) of the element at the given index.
  1960. // This value is NOT relative to the document's right edge, like the CSS concept of "right" would be.
  1961. getRightOffset: function(leftIndex) {
  1962. this.ensureBuilt();
  1963. return this.rights[leftIndex];
  1964. },
  1965. // Gets the right position (from offsetParent left) of the element at the given index.
  1966. // This value is NOT relative to the offsetParent's right edge, like the CSS concept of "right" would be.
  1967. getRightPosition: function(leftIndex) {
  1968. this.ensureBuilt();
  1969. return this.rights[leftIndex] - this.origin.left;
  1970. },
  1971. // Gets the width of the element at the given index
  1972. getWidth: function(leftIndex) {
  1973. this.ensureBuilt();
  1974. return this.rights[leftIndex] - this.lefts[leftIndex];
  1975. },
  1976. // Gets the top offset (from document top) of the element at the given index
  1977. getTopOffset: function(topIndex) {
  1978. this.ensureBuilt();
  1979. return this.tops[topIndex];
  1980. },
  1981. // Gets the top position (from offsetParent top) of the element at the given position
  1982. getTopPosition: function(topIndex) {
  1983. this.ensureBuilt();
  1984. return this.tops[topIndex] - this.origin.top;
  1985. },
  1986. // Gets the bottom offset (from the document top) of the element at the given index.
  1987. // This value is NOT relative to the offsetParent's bottom edge, like the CSS concept of "bottom" would be.
  1988. getBottomOffset: function(topIndex) {
  1989. this.ensureBuilt();
  1990. return this.bottoms[topIndex];
  1991. },
  1992. // Gets the bottom position (from the offsetParent top) of the element at the given index.
  1993. // This value is NOT relative to the offsetParent's bottom edge, like the CSS concept of "bottom" would be.
  1994. getBottomPosition: function(topIndex) {
  1995. this.ensureBuilt();
  1996. return this.bottoms[topIndex] - this.origin.top;
  1997. },
  1998. // Gets the height of the element at the given index
  1999. getHeight: function(topIndex) {
  2000. this.ensureBuilt();
  2001. return this.bottoms[topIndex] - this.tops[topIndex];
  2002. },
  2003. // Bounding Rect
  2004. // TODO: decouple this from CoordCache
  2005. // Compute and return what the elements' bounding rectangle is, from the user's perspective.
  2006. // Right now, only returns a rectangle if constrained by an overflow:scroll element.
  2007. // Returns null if there are no elements
  2008. queryBoundingRect: function() {
  2009. var scrollParentEl;
  2010. if (this.els.length > 0) {
  2011. scrollParentEl = getScrollParent(this.els.eq(0));
  2012. if (!scrollParentEl.is(document)) {
  2013. return getClientRect(scrollParentEl);
  2014. }
  2015. }
  2016. return null;
  2017. },
  2018. isPointInBounds: function(leftOffset, topOffset) {
  2019. return this.isLeftInBounds(leftOffset) && this.isTopInBounds(topOffset);
  2020. },
  2021. isLeftInBounds: function(leftOffset) {
  2022. return !this.boundingRect || (leftOffset >= this.boundingRect.left && leftOffset < this.boundingRect.right);
  2023. },
  2024. isTopInBounds: function(topOffset) {
  2025. return !this.boundingRect || (topOffset >= this.boundingRect.top && topOffset < this.boundingRect.bottom);
  2026. }
  2027. });
  2028. ;;
  2029. /* Tracks a drag's mouse movement, firing various handlers
  2030. ----------------------------------------------------------------------------------------------------------------------*/
  2031. // TODO: use Emitter
  2032. var DragListener = FC.DragListener = Class.extend(ListenerMixin, {
  2033. options: null,
  2034. subjectEl: null,
  2035. // coordinates of the initial mousedown
  2036. originX: null,
  2037. originY: null,
  2038. // the wrapping element that scrolls, or MIGHT scroll if there's overflow.
  2039. // TODO: do this for wrappers that have overflow:hidden as well.
  2040. scrollEl: null,
  2041. isInteracting: false,
  2042. isDistanceSurpassed: false,
  2043. isDelayEnded: false,
  2044. isDragging: false,
  2045. isTouch: false,
  2046. delay: null,
  2047. delayTimeoutId: null,
  2048. minDistance: null,
  2049. shouldCancelTouchScroll: true,
  2050. scrollAlwaysKills: false,
  2051. constructor: function(options) {
  2052. this.options = options || {};
  2053. },
  2054. // Interaction (high-level)
  2055. // -----------------------------------------------------------------------------------------------------------------
  2056. startInteraction: function(ev, extraOptions) {
  2057. var isTouch = getEvIsTouch(ev);
  2058. if (ev.type === 'mousedown') {
  2059. if (GlobalEmitter.get().shouldIgnoreMouse()) {
  2060. return;
  2061. }
  2062. else if (!isPrimaryMouseButton(ev)) {
  2063. return;
  2064. }
  2065. else {
  2066. ev.preventDefault(); // prevents native selection in most browsers
  2067. }
  2068. }
  2069. if (!this.isInteracting) {
  2070. // process options
  2071. extraOptions = extraOptions || {};
  2072. this.delay = firstDefined(extraOptions.delay, this.options.delay, 0);
  2073. this.minDistance = firstDefined(extraOptions.distance, this.options.distance, 0);
  2074. this.subjectEl = this.options.subjectEl;
  2075. preventSelection($('body'));
  2076. this.isInteracting = true;
  2077. this.isTouch = isTouch;
  2078. this.isDelayEnded = false;
  2079. this.isDistanceSurpassed = false;
  2080. this.originX = getEvX(ev);
  2081. this.originY = getEvY(ev);
  2082. this.scrollEl = getScrollParent($(ev.target));
  2083. this.bindHandlers();
  2084. this.initAutoScroll();
  2085. this.handleInteractionStart(ev);
  2086. this.startDelay(ev);
  2087. if (!this.minDistance) {
  2088. this.handleDistanceSurpassed(ev);
  2089. }
  2090. }
  2091. },
  2092. handleInteractionStart: function(ev) {
  2093. this.trigger('interactionStart', ev);
  2094. },
  2095. endInteraction: function(ev, isCancelled) {
  2096. if (this.isInteracting) {
  2097. this.endDrag(ev);
  2098. if (this.delayTimeoutId) {
  2099. clearTimeout(this.delayTimeoutId);
  2100. this.delayTimeoutId = null;
  2101. }
  2102. this.destroyAutoScroll();
  2103. this.unbindHandlers();
  2104. this.isInteracting = false;
  2105. this.handleInteractionEnd(ev, isCancelled);
  2106. allowSelection($('body'));
  2107. }
  2108. },
  2109. handleInteractionEnd: function(ev, isCancelled) {
  2110. this.trigger('interactionEnd', ev, isCancelled || false);
  2111. },
  2112. // Binding To DOM
  2113. // -----------------------------------------------------------------------------------------------------------------
  2114. bindHandlers: function() {
  2115. // some browsers (Safari in iOS 10) don't allow preventDefault on touch events that are bound after touchstart,
  2116. // so listen to the GlobalEmitter singleton, which is always bound, instead of the document directly.
  2117. var globalEmitter = GlobalEmitter.get();
  2118. if (this.isTouch) {
  2119. this.listenTo(globalEmitter, {
  2120. touchmove: this.handleTouchMove,
  2121. touchend: this.endInteraction,
  2122. scroll: this.handleTouchScroll
  2123. });
  2124. }
  2125. else {
  2126. this.listenTo(globalEmitter, {
  2127. mousemove: this.handleMouseMove,
  2128. mouseup: this.endInteraction
  2129. });
  2130. }
  2131. this.listenTo(globalEmitter, {
  2132. selectstart: preventDefault, // don't allow selection while dragging
  2133. contextmenu: preventDefault // long taps would open menu on Chrome dev tools
  2134. });
  2135. },
  2136. unbindHandlers: function() {
  2137. this.stopListeningTo(GlobalEmitter.get());
  2138. },
  2139. // Drag (high-level)
  2140. // -----------------------------------------------------------------------------------------------------------------
  2141. // extraOptions ignored if drag already started
  2142. startDrag: function(ev, extraOptions) {
  2143. this.startInteraction(ev, extraOptions); // ensure interaction began
  2144. if (!this.isDragging) {
  2145. this.isDragging = true;
  2146. this.handleDragStart(ev);
  2147. }
  2148. },
  2149. handleDragStart: function(ev) {
  2150. this.trigger('dragStart', ev);
  2151. },
  2152. handleMove: function(ev) {
  2153. var dx = getEvX(ev) - this.originX;
  2154. var dy = getEvY(ev) - this.originY;
  2155. var minDistance = this.minDistance;
  2156. var distanceSq; // current distance from the origin, squared
  2157. if (!this.isDistanceSurpassed) {
  2158. distanceSq = dx * dx + dy * dy;
  2159. if (distanceSq >= minDistance * minDistance) { // use pythagorean theorem
  2160. this.handleDistanceSurpassed(ev);
  2161. }
  2162. }
  2163. if (this.isDragging) {
  2164. this.handleDrag(dx, dy, ev);
  2165. }
  2166. },
  2167. // Called while the mouse is being moved and when we know a legitimate drag is taking place
  2168. handleDrag: function(dx, dy, ev) {
  2169. this.trigger('drag', dx, dy, ev);
  2170. this.updateAutoScroll(ev); // will possibly cause scrolling
  2171. },
  2172. endDrag: function(ev) {
  2173. if (this.isDragging) {
  2174. this.isDragging = false;
  2175. this.handleDragEnd(ev);
  2176. }
  2177. },
  2178. handleDragEnd: function(ev) {
  2179. this.trigger('dragEnd', ev);
  2180. },
  2181. // Delay
  2182. // -----------------------------------------------------------------------------------------------------------------
  2183. startDelay: function(initialEv) {
  2184. var _this = this;
  2185. if (this.delay) {
  2186. this.delayTimeoutId = setTimeout(function() {
  2187. _this.handleDelayEnd(initialEv);
  2188. }, this.delay);
  2189. }
  2190. else {
  2191. this.handleDelayEnd(initialEv);
  2192. }
  2193. },
  2194. handleDelayEnd: function(initialEv) {
  2195. this.isDelayEnded = true;
  2196. if (this.isDistanceSurpassed) {
  2197. this.startDrag(initialEv);
  2198. }
  2199. },
  2200. // Distance
  2201. // -----------------------------------------------------------------------------------------------------------------
  2202. handleDistanceSurpassed: function(ev) {
  2203. this.isDistanceSurpassed = true;
  2204. if (this.isDelayEnded) {
  2205. this.startDrag(ev);
  2206. }
  2207. },
  2208. // Mouse / Touch
  2209. // -----------------------------------------------------------------------------------------------------------------
  2210. handleTouchMove: function(ev) {
  2211. // prevent inertia and touchmove-scrolling while dragging
  2212. if (this.isDragging && this.shouldCancelTouchScroll) {
  2213. ev.preventDefault();
  2214. }
  2215. this.handleMove(ev);
  2216. },
  2217. handleMouseMove: function(ev) {
  2218. this.handleMove(ev);
  2219. },
  2220. // Scrolling (unrelated to auto-scroll)
  2221. // -----------------------------------------------------------------------------------------------------------------
  2222. handleTouchScroll: function(ev) {
  2223. // if the drag is being initiated by touch, but a scroll happens before
  2224. // the drag-initiating delay is over, cancel the drag
  2225. if (!this.isDragging || this.scrollAlwaysKills) {
  2226. this.endInteraction(ev, true); // isCancelled=true
  2227. }
  2228. },
  2229. // Utils
  2230. // -----------------------------------------------------------------------------------------------------------------
  2231. // Triggers a callback. Calls a function in the option hash of the same name.
  2232. // Arguments beyond the first `name` are forwarded on.
  2233. trigger: function(name) {
  2234. if (this.options[name]) {
  2235. this.options[name].apply(this, Array.prototype.slice.call(arguments, 1));
  2236. }
  2237. // makes _methods callable by event name. TODO: kill this
  2238. if (this['_' + name]) {
  2239. this['_' + name].apply(this, Array.prototype.slice.call(arguments, 1));
  2240. }
  2241. }
  2242. });
  2243. ;;
  2244. /*
  2245. this.scrollEl is set in DragListener
  2246. */
  2247. DragListener.mixin({
  2248. isAutoScroll: false,
  2249. scrollBounds: null, // { top, bottom, left, right }
  2250. scrollTopVel: null, // pixels per second
  2251. scrollLeftVel: null, // pixels per second
  2252. scrollIntervalId: null, // ID of setTimeout for scrolling animation loop
  2253. // defaults
  2254. scrollSensitivity: 30, // pixels from edge for scrolling to start
  2255. scrollSpeed: 200, // pixels per second, at maximum speed
  2256. scrollIntervalMs: 50, // millisecond wait between scroll increment
  2257. initAutoScroll: function() {
  2258. var scrollEl = this.scrollEl;
  2259. this.isAutoScroll =
  2260. this.options.scroll &&
  2261. scrollEl &&
  2262. !scrollEl.is(window) &&
  2263. !scrollEl.is(document);
  2264. if (this.isAutoScroll) {
  2265. // debounce makes sure rapid calls don't happen
  2266. this.listenTo(scrollEl, 'scroll', debounce(this.handleDebouncedScroll, 100));
  2267. }
  2268. },
  2269. destroyAutoScroll: function() {
  2270. this.endAutoScroll(); // kill any animation loop
  2271. // remove the scroll handler if there is a scrollEl
  2272. if (this.isAutoScroll) {
  2273. this.stopListeningTo(this.scrollEl, 'scroll'); // will probably get removed by unbindHandlers too :(
  2274. }
  2275. },
  2276. // Computes and stores the bounding rectangle of scrollEl
  2277. computeScrollBounds: function() {
  2278. if (this.isAutoScroll) {
  2279. this.scrollBounds = getOuterRect(this.scrollEl);
  2280. // TODO: use getClientRect in future. but prevents auto scrolling when on top of scrollbars
  2281. }
  2282. },
  2283. // Called when the dragging is in progress and scrolling should be updated
  2284. updateAutoScroll: function(ev) {
  2285. var sensitivity = this.scrollSensitivity;
  2286. var bounds = this.scrollBounds;
  2287. var topCloseness, bottomCloseness;
  2288. var leftCloseness, rightCloseness;
  2289. var topVel = 0;
  2290. var leftVel = 0;
  2291. if (bounds) { // only scroll if scrollEl exists
  2292. // compute closeness to edges. valid range is from 0.0 - 1.0
  2293. topCloseness = (sensitivity - (getEvY(ev) - bounds.top)) / sensitivity;
  2294. bottomCloseness = (sensitivity - (bounds.bottom - getEvY(ev))) / sensitivity;
  2295. leftCloseness = (sensitivity - (getEvX(ev) - bounds.left)) / sensitivity;
  2296. rightCloseness = (sensitivity - (bounds.right - getEvX(ev))) / sensitivity;
  2297. // translate vertical closeness into velocity.
  2298. // mouse must be completely in bounds for velocity to happen.
  2299. if (topCloseness >= 0 && topCloseness <= 1) {
  2300. topVel = topCloseness * this.scrollSpeed * -1; // negative. for scrolling up
  2301. }
  2302. else if (bottomCloseness >= 0 && bottomCloseness <= 1) {
  2303. topVel = bottomCloseness * this.scrollSpeed;
  2304. }
  2305. // translate horizontal closeness into velocity
  2306. if (leftCloseness >= 0 && leftCloseness <= 1) {
  2307. leftVel = leftCloseness * this.scrollSpeed * -1; // negative. for scrolling left
  2308. }
  2309. else if (rightCloseness >= 0 && rightCloseness <= 1) {
  2310. leftVel = rightCloseness * this.scrollSpeed;
  2311. }
  2312. }
  2313. this.setScrollVel(topVel, leftVel);
  2314. },
  2315. // Sets the speed-of-scrolling for the scrollEl
  2316. setScrollVel: function(topVel, leftVel) {
  2317. this.scrollTopVel = topVel;
  2318. this.scrollLeftVel = leftVel;
  2319. this.constrainScrollVel(); // massages into realistic values
  2320. // if there is non-zero velocity, and an animation loop hasn't already started, then START
  2321. if ((this.scrollTopVel || this.scrollLeftVel) && !this.scrollIntervalId) {
  2322. this.scrollIntervalId = setInterval(
  2323. proxy(this, 'scrollIntervalFunc'), // scope to `this`
  2324. this.scrollIntervalMs
  2325. );
  2326. }
  2327. },
  2328. // Forces scrollTopVel and scrollLeftVel to be zero if scrolling has already gone all the way
  2329. constrainScrollVel: function() {
  2330. var el = this.scrollEl;
  2331. if (this.scrollTopVel < 0) { // scrolling up?
  2332. if (el.scrollTop() <= 0) { // already scrolled all the way up?
  2333. this.scrollTopVel = 0;
  2334. }
  2335. }
  2336. else if (this.scrollTopVel > 0) { // scrolling down?
  2337. if (el.scrollTop() + el[0].clientHeight >= el[0].scrollHeight) { // already scrolled all the way down?
  2338. this.scrollTopVel = 0;
  2339. }
  2340. }
  2341. if (this.scrollLeftVel < 0) { // scrolling left?
  2342. if (el.scrollLeft() <= 0) { // already scrolled all the left?
  2343. this.scrollLeftVel = 0;
  2344. }
  2345. }
  2346. else if (this.scrollLeftVel > 0) { // scrolling right?
  2347. if (el.scrollLeft() + el[0].clientWidth >= el[0].scrollWidth) { // already scrolled all the way right?
  2348. this.scrollLeftVel = 0;
  2349. }
  2350. }
  2351. },
  2352. // This function gets called during every iteration of the scrolling animation loop
  2353. scrollIntervalFunc: function() {
  2354. var el = this.scrollEl;
  2355. var frac = this.scrollIntervalMs / 1000; // considering animation frequency, what the vel should be mult'd by
  2356. // change the value of scrollEl's scroll
  2357. if (this.scrollTopVel) {
  2358. el.scrollTop(el.scrollTop() + this.scrollTopVel * frac);
  2359. }
  2360. if (this.scrollLeftVel) {
  2361. el.scrollLeft(el.scrollLeft() + this.scrollLeftVel * frac);
  2362. }
  2363. this.constrainScrollVel(); // since the scroll values changed, recompute the velocities
  2364. // if scrolled all the way, which causes the vels to be zero, stop the animation loop
  2365. if (!this.scrollTopVel && !this.scrollLeftVel) {
  2366. this.endAutoScroll();
  2367. }
  2368. },
  2369. // Kills any existing scrolling animation loop
  2370. endAutoScroll: function() {
  2371. if (this.scrollIntervalId) {
  2372. clearInterval(this.scrollIntervalId);
  2373. this.scrollIntervalId = null;
  2374. this.handleScrollEnd();
  2375. }
  2376. },
  2377. // Get called when the scrollEl is scrolled (NOTE: this is delayed via debounce)
  2378. handleDebouncedScroll: function() {
  2379. // recompute all coordinates, but *only* if this is *not* part of our scrolling animation
  2380. if (!this.scrollIntervalId) {
  2381. this.handleScrollEnd();
  2382. }
  2383. },
  2384. // Called when scrolling has stopped, whether through auto scroll, or the user scrolling
  2385. handleScrollEnd: function() {
  2386. }
  2387. });
  2388. ;;
  2389. /* Tracks mouse movements over a component and raises events about which hit the mouse is over.
  2390. ------------------------------------------------------------------------------------------------------------------------
  2391. options:
  2392. - subjectEl
  2393. - subjectCenter
  2394. */
  2395. var HitDragListener = DragListener.extend({
  2396. component: null, // converts coordinates to hits
  2397. // methods: hitsNeeded, hitsNotNeeded, queryHit
  2398. origHit: null, // the hit the mouse was over when listening started
  2399. hit: null, // the hit the mouse is over
  2400. coordAdjust: null, // delta that will be added to the mouse coordinates when computing collisions
  2401. constructor: function(component, options) {
  2402. DragListener.call(this, options); // call the super-constructor
  2403. this.component = component;
  2404. },
  2405. // Called when drag listening starts (but a real drag has not necessarily began).
  2406. // ev might be undefined if dragging was started manually.
  2407. handleInteractionStart: function(ev) {
  2408. var subjectEl = this.subjectEl;
  2409. var subjectRect;
  2410. var origPoint;
  2411. var point;
  2412. this.component.hitsNeeded();
  2413. this.computeScrollBounds(); // for autoscroll
  2414. if (ev) {
  2415. origPoint = { left: getEvX(ev), top: getEvY(ev) };
  2416. point = origPoint;
  2417. // constrain the point to bounds of the element being dragged
  2418. if (subjectEl) {
  2419. subjectRect = getOuterRect(subjectEl); // used for centering as well
  2420. point = constrainPoint(point, subjectRect);
  2421. }
  2422. this.origHit = this.queryHit(point.left, point.top);
  2423. // treat the center of the subject as the collision point?
  2424. if (subjectEl && this.options.subjectCenter) {
  2425. // only consider the area the subject overlaps the hit. best for large subjects.
  2426. // TODO: skip this if hit didn't supply left/right/top/bottom
  2427. if (this.origHit) {
  2428. subjectRect = intersectRects(this.origHit, subjectRect) ||
  2429. subjectRect; // in case there is no intersection
  2430. }
  2431. point = getRectCenter(subjectRect);
  2432. }
  2433. this.coordAdjust = diffPoints(point, origPoint); // point - origPoint
  2434. }
  2435. else {
  2436. this.origHit = null;
  2437. this.coordAdjust = null;
  2438. }
  2439. // call the super-method. do it after origHit has been computed
  2440. DragListener.prototype.handleInteractionStart.apply(this, arguments);
  2441. },
  2442. // Called when the actual drag has started
  2443. handleDragStart: function(ev) {
  2444. var hit;
  2445. DragListener.prototype.handleDragStart.apply(this, arguments); // call the super-method
  2446. // might be different from this.origHit if the min-distance is large
  2447. hit = this.queryHit(getEvX(ev), getEvY(ev));
  2448. // report the initial hit the mouse is over
  2449. // especially important if no min-distance and drag starts immediately
  2450. if (hit) {
  2451. this.handleHitOver(hit);
  2452. }
  2453. },
  2454. // Called when the drag moves
  2455. handleDrag: function(dx, dy, ev) {
  2456. var hit;
  2457. DragListener.prototype.handleDrag.apply(this, arguments); // call the super-method
  2458. hit = this.queryHit(getEvX(ev), getEvY(ev));
  2459. if (!isHitsEqual(hit, this.hit)) { // a different hit than before?
  2460. if (this.hit) {
  2461. this.handleHitOut();
  2462. }
  2463. if (hit) {
  2464. this.handleHitOver(hit);
  2465. }
  2466. }
  2467. },
  2468. // Called when dragging has been stopped
  2469. handleDragEnd: function() {
  2470. this.handleHitDone();
  2471. DragListener.prototype.handleDragEnd.apply(this, arguments); // call the super-method
  2472. },
  2473. // Called when a the mouse has just moved over a new hit
  2474. handleHitOver: function(hit) {
  2475. var isOrig = isHitsEqual(hit, this.origHit);
  2476. this.hit = hit;
  2477. this.trigger('hitOver', this.hit, isOrig, this.origHit);
  2478. },
  2479. // Called when the mouse has just moved out of a hit
  2480. handleHitOut: function() {
  2481. if (this.hit) {
  2482. this.trigger('hitOut', this.hit);
  2483. this.handleHitDone();
  2484. this.hit = null;
  2485. }
  2486. },
  2487. // Called after a hitOut. Also called before a dragStop
  2488. handleHitDone: function() {
  2489. if (this.hit) {
  2490. this.trigger('hitDone', this.hit);
  2491. }
  2492. },
  2493. // Called when the interaction ends, whether there was a real drag or not
  2494. handleInteractionEnd: function() {
  2495. DragListener.prototype.handleInteractionEnd.apply(this, arguments); // call the super-method
  2496. this.origHit = null;
  2497. this.hit = null;
  2498. this.component.hitsNotNeeded();
  2499. },
  2500. // Called when scrolling has stopped, whether through auto scroll, or the user scrolling
  2501. handleScrollEnd: function() {
  2502. DragListener.prototype.handleScrollEnd.apply(this, arguments); // call the super-method
  2503. // hits' absolute positions will be in new places after a user's scroll.
  2504. // HACK for recomputing.
  2505. if (this.isDragging) {
  2506. this.component.releaseHits();
  2507. this.component.prepareHits();
  2508. }
  2509. },
  2510. // Gets the hit underneath the coordinates for the given mouse event
  2511. queryHit: function(left, top) {
  2512. if (this.coordAdjust) {
  2513. left += this.coordAdjust.left;
  2514. top += this.coordAdjust.top;
  2515. }
  2516. return this.component.queryHit(left, top);
  2517. }
  2518. });
  2519. // Returns `true` if the hits are identically equal. `false` otherwise. Must be from the same component.
  2520. // Two null values will be considered equal, as two "out of the component" states are the same.
  2521. function isHitsEqual(hit0, hit1) {
  2522. if (!hit0 && !hit1) {
  2523. return true;
  2524. }
  2525. if (hit0 && hit1) {
  2526. return hit0.component === hit1.component &&
  2527. isHitPropsWithin(hit0, hit1) &&
  2528. isHitPropsWithin(hit1, hit0); // ensures all props are identical
  2529. }
  2530. return false;
  2531. }
  2532. // Returns true if all of subHit's non-standard properties are within superHit
  2533. function isHitPropsWithin(subHit, superHit) {
  2534. for (var propName in subHit) {
  2535. if (!/^(component|left|right|top|bottom)$/.test(propName)) {
  2536. if (subHit[propName] !== superHit[propName]) {
  2537. return false;
  2538. }
  2539. }
  2540. }
  2541. return true;
  2542. }
  2543. ;;
  2544. /*
  2545. Listens to document and window-level user-interaction events, like touch events and mouse events,
  2546. and fires these events as-is to whoever is observing a GlobalEmitter.
  2547. Best when used as a singleton via GlobalEmitter.get()
  2548. Normalizes mouse/touch events. For examples:
  2549. - ignores the the simulated mouse events that happen after a quick tap: mousemove+mousedown+mouseup+click
  2550. - compensates for various buggy scenarios where a touchend does not fire
  2551. */
  2552. FC.touchMouseIgnoreWait = 500;
  2553. var GlobalEmitter = Class.extend(ListenerMixin, EmitterMixin, {
  2554. isTouching: false,
  2555. mouseIgnoreDepth: 0,
  2556. handleScrollProxy: null,
  2557. bind: function() {
  2558. var _this = this;
  2559. this.listenTo($(document), {
  2560. touchstart: this.handleTouchStart,
  2561. touchcancel: this.handleTouchCancel,
  2562. touchend: this.handleTouchEnd,
  2563. mousedown: this.handleMouseDown,
  2564. mousemove: this.handleMouseMove,
  2565. mouseup: this.handleMouseUp,
  2566. click: this.handleClick,
  2567. selectstart: this.handleSelectStart,
  2568. contextmenu: this.handleContextMenu
  2569. });
  2570. // because we need to call preventDefault
  2571. // because https://www.chromestatus.com/features/5093566007214080
  2572. // TODO: investigate performance because this is a global handler
  2573. window.addEventListener(
  2574. 'touchmove',
  2575. this.handleTouchMoveProxy = function(ev) {
  2576. _this.handleTouchMove($.Event(ev));
  2577. },
  2578. { passive: false } // allows preventDefault()
  2579. );
  2580. // attach a handler to get called when ANY scroll action happens on the page.
  2581. // this was impossible to do with normal on/off because 'scroll' doesn't bubble.
  2582. // http://stackoverflow.com/a/32954565/96342
  2583. window.addEventListener(
  2584. 'scroll',
  2585. this.handleScrollProxy = function(ev) {
  2586. _this.handleScroll($.Event(ev));
  2587. },
  2588. true // useCapture
  2589. );
  2590. },
  2591. unbind: function() {
  2592. this.stopListeningTo($(document));
  2593. window.removeEventListener(
  2594. 'touchmove',
  2595. this.handleTouchMoveProxy
  2596. );
  2597. window.removeEventListener(
  2598. 'scroll',
  2599. this.handleScrollProxy,
  2600. true // useCapture
  2601. );
  2602. },
  2603. // Touch Handlers
  2604. // -----------------------------------------------------------------------------------------------------------------
  2605. handleTouchStart: function(ev) {
  2606. // if a previous touch interaction never ended with a touchend, then implicitly end it,
  2607. // but since a new touch interaction is about to begin, don't start the mouse ignore period.
  2608. this.stopTouch(ev, true); // skipMouseIgnore=true
  2609. this.isTouching = true;
  2610. this.trigger('touchstart', ev);
  2611. },
  2612. handleTouchMove: function(ev) {
  2613. if (this.isTouching) {
  2614. this.trigger('touchmove', ev);
  2615. }
  2616. },
  2617. handleTouchCancel: function(ev) {
  2618. if (this.isTouching) {
  2619. this.trigger('touchcancel', ev);
  2620. // Have touchcancel fire an artificial touchend. That way, handlers won't need to listen to both.
  2621. // If touchend fires later, it won't have any effect b/c isTouching will be false.
  2622. this.stopTouch(ev);
  2623. }
  2624. },
  2625. handleTouchEnd: function(ev) {
  2626. this.stopTouch(ev);
  2627. },
  2628. // Mouse Handlers
  2629. // -----------------------------------------------------------------------------------------------------------------
  2630. handleMouseDown: function(ev) {
  2631. if (!this.shouldIgnoreMouse()) {
  2632. this.trigger('mousedown', ev);
  2633. }
  2634. },
  2635. handleMouseMove: function(ev) {
  2636. if (!this.shouldIgnoreMouse()) {
  2637. this.trigger('mousemove', ev);
  2638. }
  2639. },
  2640. handleMouseUp: function(ev) {
  2641. if (!this.shouldIgnoreMouse()) {
  2642. this.trigger('mouseup', ev);
  2643. }
  2644. },
  2645. handleClick: function(ev) {
  2646. if (!this.shouldIgnoreMouse()) {
  2647. this.trigger('click', ev);
  2648. }
  2649. },
  2650. // Misc Handlers
  2651. // -----------------------------------------------------------------------------------------------------------------
  2652. handleSelectStart: function(ev) {
  2653. this.trigger('selectstart', ev);
  2654. },
  2655. handleContextMenu: function(ev) {
  2656. this.trigger('contextmenu', ev);
  2657. },
  2658. handleScroll: function(ev) {
  2659. this.trigger('scroll', ev);
  2660. },
  2661. // Utils
  2662. // -----------------------------------------------------------------------------------------------------------------
  2663. stopTouch: function(ev, skipMouseIgnore) {
  2664. if (this.isTouching) {
  2665. this.isTouching = false;
  2666. this.trigger('touchend', ev);
  2667. if (!skipMouseIgnore) {
  2668. this.startTouchMouseIgnore();
  2669. }
  2670. }
  2671. },
  2672. startTouchMouseIgnore: function() {
  2673. var _this = this;
  2674. var wait = FC.touchMouseIgnoreWait;
  2675. if (wait) {
  2676. this.mouseIgnoreDepth++;
  2677. setTimeout(function() {
  2678. _this.mouseIgnoreDepth--;
  2679. }, wait);
  2680. }
  2681. },
  2682. shouldIgnoreMouse: function() {
  2683. return this.isTouching || Boolean(this.mouseIgnoreDepth);
  2684. }
  2685. });
  2686. // Singleton
  2687. // ---------------------------------------------------------------------------------------------------------------------
  2688. (function() {
  2689. var globalEmitter = null;
  2690. var neededCount = 0;
  2691. // gets the singleton
  2692. GlobalEmitter.get = function() {
  2693. if (!globalEmitter) {
  2694. globalEmitter = new GlobalEmitter();
  2695. globalEmitter.bind();
  2696. }
  2697. return globalEmitter;
  2698. };
  2699. // called when an object knows it will need a GlobalEmitter in the near future.
  2700. GlobalEmitter.needed = function() {
  2701. GlobalEmitter.get(); // ensures globalEmitter
  2702. neededCount++;
  2703. };
  2704. // called when the object that originally called needed() doesn't need a GlobalEmitter anymore.
  2705. GlobalEmitter.unneeded = function() {
  2706. neededCount--;
  2707. if (!neededCount) { // nobody else needs it
  2708. globalEmitter.unbind();
  2709. globalEmitter = null;
  2710. }
  2711. };
  2712. })();
  2713. ;;
  2714. /* Creates a clone of an element and lets it track the mouse as it moves
  2715. ----------------------------------------------------------------------------------------------------------------------*/
  2716. var MouseFollower = Class.extend(ListenerMixin, {
  2717. options: null,
  2718. sourceEl: null, // the element that will be cloned and made to look like it is dragging
  2719. el: null, // the clone of `sourceEl` that will track the mouse
  2720. parentEl: null, // the element that `el` (the clone) will be attached to
  2721. // the initial position of el, relative to the offset parent. made to match the initial offset of sourceEl
  2722. top0: null,
  2723. left0: null,
  2724. // the absolute coordinates of the initiating touch/mouse action
  2725. y0: null,
  2726. x0: null,
  2727. // the number of pixels the mouse has moved from its initial position
  2728. topDelta: null,
  2729. leftDelta: null,
  2730. isFollowing: false,
  2731. isHidden: false,
  2732. isAnimating: false, // doing the revert animation?
  2733. constructor: function(sourceEl, options) {
  2734. this.options = options = options || {};
  2735. this.sourceEl = sourceEl;
  2736. this.parentEl = options.parentEl ? $(options.parentEl) : sourceEl.parent(); // default to sourceEl's parent
  2737. },
  2738. // Causes the element to start following the mouse
  2739. start: function(ev) {
  2740. if (!this.isFollowing) {
  2741. this.isFollowing = true;
  2742. this.y0 = getEvY(ev);
  2743. this.x0 = getEvX(ev);
  2744. this.topDelta = 0;
  2745. this.leftDelta = 0;
  2746. if (!this.isHidden) {
  2747. this.updatePosition();
  2748. }
  2749. if (getEvIsTouch(ev)) {
  2750. this.listenTo($(document), 'touchmove', this.handleMove);
  2751. }
  2752. else {
  2753. this.listenTo($(document), 'mousemove', this.handleMove);
  2754. }
  2755. }
  2756. },
  2757. // Causes the element to stop following the mouse. If shouldRevert is true, will animate back to original position.
  2758. // `callback` gets invoked when the animation is complete. If no animation, it is invoked immediately.
  2759. stop: function(shouldRevert, callback) {
  2760. var _this = this;
  2761. var revertDuration = this.options.revertDuration;
  2762. function complete() { // might be called by .animate(), which might change `this` context
  2763. _this.isAnimating = false;
  2764. _this.removeElement();
  2765. _this.top0 = _this.left0 = null; // reset state for future updatePosition calls
  2766. if (callback) {
  2767. callback();
  2768. }
  2769. }
  2770. if (this.isFollowing && !this.isAnimating) { // disallow more than one stop animation at a time
  2771. this.isFollowing = false;
  2772. this.stopListeningTo($(document));
  2773. if (shouldRevert && revertDuration && !this.isHidden) { // do a revert animation?
  2774. this.isAnimating = true;
  2775. this.el.animate({
  2776. top: this.top0,
  2777. left: this.left0
  2778. }, {
  2779. duration: revertDuration,
  2780. complete: complete
  2781. });
  2782. }
  2783. else {
  2784. complete();
  2785. }
  2786. }
  2787. },
  2788. // Gets the tracking element. Create it if necessary
  2789. getEl: function() {
  2790. var el = this.el;
  2791. if (!el) {
  2792. el = this.el = this.sourceEl.clone()
  2793. .addClass(this.options.additionalClass || '')
  2794. .css({
  2795. position: 'absolute',
  2796. visibility: '', // in case original element was hidden (commonly through hideEvents())
  2797. display: this.isHidden ? 'none' : '', // for when initially hidden
  2798. margin: 0,
  2799. right: 'auto', // erase and set width instead
  2800. bottom: 'auto', // erase and set height instead
  2801. width: this.sourceEl.width(), // explicit height in case there was a 'right' value
  2802. height: this.sourceEl.height(), // explicit width in case there was a 'bottom' value
  2803. opacity: this.options.opacity || '',
  2804. zIndex: this.options.zIndex
  2805. });
  2806. // we don't want long taps or any mouse interaction causing selection/menus.
  2807. // would use preventSelection(), but that prevents selectstart, causing problems.
  2808. el.addClass('fc-unselectable');
  2809. el.appendTo(this.parentEl);
  2810. }
  2811. return el;
  2812. },
  2813. // Removes the tracking element if it has already been created
  2814. removeElement: function() {
  2815. if (this.el) {
  2816. this.el.remove();
  2817. this.el = null;
  2818. }
  2819. },
  2820. // Update the CSS position of the tracking element
  2821. updatePosition: function() {
  2822. var sourceOffset;
  2823. var origin;
  2824. this.getEl(); // ensure this.el
  2825. // make sure origin info was computed
  2826. if (this.top0 === null) {
  2827. sourceOffset = this.sourceEl.offset();
  2828. origin = this.el.offsetParent().offset();
  2829. this.top0 = sourceOffset.top - origin.top;
  2830. this.left0 = sourceOffset.left - origin.left;
  2831. }
  2832. this.el.css({
  2833. top: this.top0 + this.topDelta,
  2834. left: this.left0 + this.leftDelta
  2835. });
  2836. },
  2837. // Gets called when the user moves the mouse
  2838. handleMove: function(ev) {
  2839. this.topDelta = getEvY(ev) - this.y0;
  2840. this.leftDelta = getEvX(ev) - this.x0;
  2841. if (!this.isHidden) {
  2842. this.updatePosition();
  2843. }
  2844. },
  2845. // Temporarily makes the tracking element invisible. Can be called before following starts
  2846. hide: function() {
  2847. if (!this.isHidden) {
  2848. this.isHidden = true;
  2849. if (this.el) {
  2850. this.el.hide();
  2851. }
  2852. }
  2853. },
  2854. // Show the tracking element after it has been temporarily hidden
  2855. show: function() {
  2856. if (this.isHidden) {
  2857. this.isHidden = false;
  2858. this.updatePosition();
  2859. this.getEl().show();
  2860. }
  2861. }
  2862. });
  2863. ;;
  2864. /* An abstract class comprised of a "grid" of areas that each represent a specific datetime
  2865. ----------------------------------------------------------------------------------------------------------------------*/
  2866. var Grid = FC.Grid = Class.extend(ListenerMixin, {
  2867. // self-config, overridable by subclasses
  2868. hasDayInteractions: true, // can user click/select ranges of time?
  2869. view: null, // a View object
  2870. isRTL: null, // shortcut to the view's isRTL option
  2871. start: null,
  2872. end: null,
  2873. el: null, // the containing element
  2874. elsByFill: null, // a hash of jQuery element sets used for rendering each fill. Keyed by fill name.
  2875. // derived from options
  2876. eventTimeFormat: null,
  2877. displayEventTime: null,
  2878. displayEventEnd: null,
  2879. minResizeDuration: null, // TODO: hack. set by subclasses. minumum event resize duration
  2880. // if defined, holds the unit identified (ex: "year" or "month") that determines the level of granularity
  2881. // of the date areas. if not defined, assumes to be day and time granularity.
  2882. // TODO: port isTimeScale into same system?
  2883. largeUnit: null,
  2884. dayClickListener: null,
  2885. daySelectListener: null,
  2886. segDragListener: null,
  2887. segResizeListener: null,
  2888. externalDragListener: null,
  2889. constructor: function(view) {
  2890. this.view = view;
  2891. this.isRTL = view.opt('isRTL');
  2892. this.elsByFill = {};
  2893. this.dayClickListener = this.buildDayClickListener();
  2894. this.daySelectListener = this.buildDaySelectListener();
  2895. },
  2896. /* Options
  2897. ------------------------------------------------------------------------------------------------------------------*/
  2898. // Generates the format string used for event time text, if not explicitly defined by 'timeFormat'
  2899. computeEventTimeFormat: function() {
  2900. return this.view.opt('smallTimeFormat');
  2901. },
  2902. // Determines whether events should have their end times displayed, if not explicitly defined by 'displayEventTime'.
  2903. // Only applies to non-all-day events.
  2904. computeDisplayEventTime: function() {
  2905. return true;
  2906. },
  2907. // Determines whether events should have their end times displayed, if not explicitly defined by 'displayEventEnd'
  2908. computeDisplayEventEnd: function() {
  2909. return true;
  2910. },
  2911. /* Dates
  2912. ------------------------------------------------------------------------------------------------------------------*/
  2913. // Tells the grid about what period of time to display.
  2914. // Any date-related internal data should be generated.
  2915. setRange: function(range) {
  2916. this.start = range.start.clone();
  2917. this.end = range.end.clone();
  2918. this.rangeUpdated();
  2919. this.processRangeOptions();
  2920. },
  2921. // Called when internal variables that rely on the range should be updated
  2922. rangeUpdated: function() {
  2923. },
  2924. // Updates values that rely on options and also relate to range
  2925. processRangeOptions: function() {
  2926. var view = this.view;
  2927. var displayEventTime;
  2928. var displayEventEnd;
  2929. this.eventTimeFormat =
  2930. view.opt('eventTimeFormat') ||
  2931. view.opt('timeFormat') || // deprecated
  2932. this.computeEventTimeFormat();
  2933. displayEventTime = view.opt('displayEventTime');
  2934. if (displayEventTime == null) {
  2935. displayEventTime = this.computeDisplayEventTime(); // might be based off of range
  2936. }
  2937. displayEventEnd = view.opt('displayEventEnd');
  2938. if (displayEventEnd == null) {
  2939. displayEventEnd = this.computeDisplayEventEnd(); // might be based off of range
  2940. }
  2941. this.displayEventTime = displayEventTime;
  2942. this.displayEventEnd = displayEventEnd;
  2943. },
  2944. // Converts a span (has unzoned start/end and any other grid-specific location information)
  2945. // into an array of segments (pieces of events whose format is decided by the grid).
  2946. spanToSegs: function(span) {
  2947. // subclasses must implement
  2948. },
  2949. // Diffs the two dates, returning a duration, based on granularity of the grid
  2950. // TODO: port isTimeScale into this system?
  2951. diffDates: function(a, b) {
  2952. if (this.largeUnit) {
  2953. return diffByUnit(a, b, this.largeUnit);
  2954. }
  2955. else {
  2956. return diffDayTime(a, b);
  2957. }
  2958. },
  2959. /* Hit Area
  2960. ------------------------------------------------------------------------------------------------------------------*/
  2961. hitsNeededDepth: 0, // necessary because multiple callers might need the same hits
  2962. hitsNeeded: function() {
  2963. if (!(this.hitsNeededDepth++)) {
  2964. this.prepareHits();
  2965. }
  2966. },
  2967. hitsNotNeeded: function() {
  2968. if (this.hitsNeededDepth && !(--this.hitsNeededDepth)) {
  2969. this.releaseHits();
  2970. }
  2971. },
  2972. // Called before one or more queryHit calls might happen. Should prepare any cached coordinates for queryHit
  2973. prepareHits: function() {
  2974. },
  2975. // Called when queryHit calls have subsided. Good place to clear any coordinate caches.
  2976. releaseHits: function() {
  2977. },
  2978. // Given coordinates from the topleft of the document, return data about the date-related area underneath.
  2979. // Can return an object with arbitrary properties (although top/right/left/bottom are encouraged).
  2980. // Must have a `grid` property, a reference to this current grid. TODO: avoid this
  2981. // The returned object will be processed by getHitSpan and getHitEl.
  2982. queryHit: function(leftOffset, topOffset) {
  2983. },
  2984. // Given position-level information about a date-related area within the grid,
  2985. // should return an object with at least a start/end date. Can provide other information as well.
  2986. getHitSpan: function(hit) {
  2987. },
  2988. // Given position-level information about a date-related area within the grid,
  2989. // should return a jQuery element that best represents it. passed to dayClick callback.
  2990. getHitEl: function(hit) {
  2991. },
  2992. /* Rendering
  2993. ------------------------------------------------------------------------------------------------------------------*/
  2994. // Sets the container element that the grid should render inside of.
  2995. // Does other DOM-related initializations.
  2996. setElement: function(el) {
  2997. this.el = el;
  2998. if (this.hasDayInteractions) {
  2999. preventSelection(el);
  3000. this.bindDayHandler('touchstart', this.dayTouchStart);
  3001. this.bindDayHandler('mousedown', this.dayMousedown);
  3002. }
  3003. // attach event-element-related handlers. in Grid.events
  3004. // same garbage collection note as above.
  3005. this.bindSegHandlers();
  3006. this.bindGlobalHandlers();
  3007. },
  3008. bindDayHandler: function(name, handler) {
  3009. var _this = this;
  3010. // attach a handler to the grid's root element.
  3011. // jQuery will take care of unregistering them when removeElement gets called.
  3012. this.el.on(name, function(ev) {
  3013. if (
  3014. !$(ev.target).is(
  3015. _this.segSelector + ',' + // directly on an event element
  3016. _this.segSelector + ' *,' + // within an event element
  3017. '.fc-more,' + // a "more.." link
  3018. 'a[data-goto]' // a clickable nav link
  3019. )
  3020. ) {
  3021. return handler.call(_this, ev);
  3022. }
  3023. });
  3024. },
  3025. // Removes the grid's container element from the DOM. Undoes any other DOM-related attachments.
  3026. // DOES NOT remove any content beforehand (doesn't clear events or call unrenderDates), unlike View
  3027. removeElement: function() {
  3028. this.unbindGlobalHandlers();
  3029. this.clearDragListeners();
  3030. this.el.remove();
  3031. // NOTE: we don't null-out this.el for the same reasons we don't do it within View::removeElement
  3032. },
  3033. // Renders the basic structure of grid view before any content is rendered
  3034. renderSkeleton: function() {
  3035. // subclasses should implement
  3036. },
  3037. // Renders the grid's date-related content (like areas that represent days/times).
  3038. // Assumes setRange has already been called and the skeleton has already been rendered.
  3039. renderDates: function() {
  3040. // subclasses should implement
  3041. },
  3042. // Unrenders the grid's date-related content
  3043. unrenderDates: function() {
  3044. // subclasses should implement
  3045. },
  3046. /* Handlers
  3047. ------------------------------------------------------------------------------------------------------------------*/
  3048. // Binds DOM handlers to elements that reside outside the grid, such as the document
  3049. bindGlobalHandlers: function() {
  3050. this.listenTo($(document), {
  3051. dragstart: this.externalDragStart, // jqui
  3052. sortstart: this.externalDragStart // jqui
  3053. });
  3054. },
  3055. // Unbinds DOM handlers from elements that reside outside the grid
  3056. unbindGlobalHandlers: function() {
  3057. this.stopListeningTo($(document));
  3058. },
  3059. // Process a mousedown on an element that represents a day. For day clicking and selecting.
  3060. dayMousedown: function(ev) {
  3061. var view = this.view;
  3062. // prevent a user's clickaway for unselecting a range or an event from
  3063. // causing a dayClick or starting an immediate new selection.
  3064. if (view.isSelected || view.selectedEvent) {
  3065. return;
  3066. }
  3067. this.dayClickListener.startInteraction(ev);
  3068. if (view.opt('selectable')) {
  3069. this.daySelectListener.startInteraction(ev, {
  3070. distance: view.opt('selectMinDistance')
  3071. });
  3072. }
  3073. },
  3074. dayTouchStart: function(ev) {
  3075. var view = this.view;
  3076. var selectLongPressDelay;
  3077. // prevent a user's clickaway for unselecting a range or an event from
  3078. // causing a dayClick or starting an immediate new selection.
  3079. if (view.isSelected || view.selectedEvent) {
  3080. return;
  3081. }
  3082. selectLongPressDelay = view.opt('selectLongPressDelay');
  3083. if (selectLongPressDelay == null) {
  3084. selectLongPressDelay = view.opt('longPressDelay'); // fallback
  3085. }
  3086. this.dayClickListener.startInteraction(ev);
  3087. if (view.opt('selectable')) {
  3088. this.daySelectListener.startInteraction(ev, {
  3089. delay: selectLongPressDelay
  3090. });
  3091. }
  3092. },
  3093. // Creates a listener that tracks the user's drag across day elements, for day clicking.
  3094. buildDayClickListener: function() {
  3095. var _this = this;
  3096. var view = this.view;
  3097. var dayClickHit; // null if invalid dayClick
  3098. var dragListener = new HitDragListener(this, {
  3099. scroll: view.opt('dragScroll'),
  3100. interactionStart: function() {
  3101. dayClickHit = dragListener.origHit;
  3102. },
  3103. hitOver: function(hit, isOrig, origHit) {
  3104. // if user dragged to another cell at any point, it can no longer be a dayClick
  3105. if (!isOrig) {
  3106. dayClickHit = null;
  3107. }
  3108. },
  3109. hitOut: function() { // called before mouse moves to a different hit OR moved out of all hits
  3110. dayClickHit = null;
  3111. },
  3112. interactionEnd: function(ev, isCancelled) {
  3113. if (!isCancelled && dayClickHit) {
  3114. view.triggerDayClick(
  3115. _this.getHitSpan(dayClickHit),
  3116. _this.getHitEl(dayClickHit),
  3117. ev
  3118. );
  3119. }
  3120. }
  3121. });
  3122. // because dayClickListener won't be called with any time delay, "dragging" will begin immediately,
  3123. // which will kill any touchmoving/scrolling. Prevent this.
  3124. dragListener.shouldCancelTouchScroll = false;
  3125. dragListener.scrollAlwaysKills = true;
  3126. return dragListener;
  3127. },
  3128. // Creates a listener that tracks the user's drag across day elements, for day selecting.
  3129. buildDaySelectListener: function() {
  3130. var _this = this;
  3131. var view = this.view;
  3132. var selectionSpan; // null if invalid selection
  3133. var dragListener = new HitDragListener(this, {
  3134. scroll: view.opt('dragScroll'),
  3135. interactionStart: function() {
  3136. selectionSpan = null;
  3137. },
  3138. dragStart: function() {
  3139. view.unselect(); // since we could be rendering a new selection, we want to clear any old one
  3140. },
  3141. hitOver: function(hit, isOrig, origHit) {
  3142. if (origHit) { // click needs to have started on a hit
  3143. selectionSpan = _this.computeSelection(
  3144. _this.getHitSpan(origHit),
  3145. _this.getHitSpan(hit)
  3146. );
  3147. if (selectionSpan) {
  3148. _this.renderSelection(selectionSpan);
  3149. }
  3150. else if (selectionSpan === false) {
  3151. disableCursor();
  3152. }
  3153. }
  3154. },
  3155. hitOut: function() { // called before mouse moves to a different hit OR moved out of all hits
  3156. selectionSpan = null;
  3157. _this.unrenderSelection();
  3158. },
  3159. hitDone: function() { // called after a hitOut OR before a dragEnd
  3160. enableCursor();
  3161. },
  3162. interactionEnd: function(ev, isCancelled) {
  3163. if (!isCancelled && selectionSpan) {
  3164. // the selection will already have been rendered. just report it
  3165. view.reportSelection(selectionSpan, ev);
  3166. }
  3167. }
  3168. });
  3169. return dragListener;
  3170. },
  3171. // Kills all in-progress dragging.
  3172. // Useful for when public API methods that result in re-rendering are invoked during a drag.
  3173. // Also useful for when touch devices misbehave and don't fire their touchend.
  3174. clearDragListeners: function() {
  3175. this.dayClickListener.endInteraction();
  3176. this.daySelectListener.endInteraction();
  3177. if (this.segDragListener) {
  3178. this.segDragListener.endInteraction(); // will clear this.segDragListener
  3179. }
  3180. if (this.segResizeListener) {
  3181. this.segResizeListener.endInteraction(); // will clear this.segResizeListener
  3182. }
  3183. if (this.externalDragListener) {
  3184. this.externalDragListener.endInteraction(); // will clear this.externalDragListener
  3185. }
  3186. },
  3187. /* Event Helper
  3188. ------------------------------------------------------------------------------------------------------------------*/
  3189. // TODO: should probably move this to Grid.events, like we did event dragging / resizing
  3190. // Renders a mock event at the given event location, which contains zoned start/end properties.
  3191. // Returns all mock event elements.
  3192. renderEventLocationHelper: function(eventLocation, sourceSeg) {
  3193. var fakeEvent = this.fabricateHelperEvent(eventLocation, sourceSeg);
  3194. return this.renderHelper(fakeEvent, sourceSeg); // do the actual rendering
  3195. },
  3196. // Builds a fake event given zoned event date properties and a segment is should be inspired from.
  3197. // The range's end can be null, in which case the mock event that is rendered will have a null end time.
  3198. // `sourceSeg` is the internal segment object involved in the drag. If null, something external is dragging.
  3199. fabricateHelperEvent: function(eventLocation, sourceSeg) {
  3200. var fakeEvent = sourceSeg ? createObject(sourceSeg.event) : {}; // mask the original event object if possible
  3201. fakeEvent.start = eventLocation.start.clone();
  3202. fakeEvent.end = eventLocation.end ? eventLocation.end.clone() : null;
  3203. fakeEvent.allDay = null; // force it to be freshly computed by normalizeEventDates
  3204. this.view.calendar.normalizeEventDates(fakeEvent);
  3205. // this extra className will be useful for differentiating real events from mock events in CSS
  3206. fakeEvent.className = (fakeEvent.className || []).concat('fc-helper');
  3207. // if something external is being dragged in, don't render a resizer
  3208. if (!sourceSeg) {
  3209. fakeEvent.editable = false;
  3210. }
  3211. return fakeEvent;
  3212. },
  3213. // Renders a mock event. Given zoned event date properties.
  3214. // Must return all mock event elements.
  3215. renderHelper: function(eventLocation, sourceSeg) {
  3216. // subclasses must implement
  3217. },
  3218. // Unrenders a mock event
  3219. unrenderHelper: function() {
  3220. // subclasses must implement
  3221. },
  3222. /* Selection
  3223. ------------------------------------------------------------------------------------------------------------------*/
  3224. // Renders a visual indication of a selection. Will highlight by default but can be overridden by subclasses.
  3225. // Given a span (unzoned start/end and other misc data)
  3226. renderSelection: function(span) {
  3227. this.renderHighlight(span);
  3228. },
  3229. // Unrenders any visual indications of a selection. Will unrender a highlight by default.
  3230. unrenderSelection: function() {
  3231. this.unrenderHighlight();
  3232. },
  3233. // Given the first and last date-spans of a selection, returns another date-span object.
  3234. // Subclasses can override and provide additional data in the span object. Will be passed to renderSelection().
  3235. // Will return false if the selection is invalid and this should be indicated to the user.
  3236. // Will return null/undefined if a selection invalid but no error should be reported.
  3237. computeSelection: function(span0, span1) {
  3238. var span = this.computeSelectionSpan(span0, span1);
  3239. if (span && !this.view.calendar.isSelectionSpanAllowed(span)) {
  3240. return false;
  3241. }
  3242. return span;
  3243. },
  3244. // Given two spans, must return the combination of the two.
  3245. // TODO: do this separation of concerns (combining VS validation) for event dnd/resize too.
  3246. computeSelectionSpan: function(span0, span1) {
  3247. var dates = [ span0.start, span0.end, span1.start, span1.end ];
  3248. dates.sort(compareNumbers); // sorts chronologically. works with Moments
  3249. return { start: dates[0].clone(), end: dates[3].clone() };
  3250. },
  3251. /* Highlight
  3252. ------------------------------------------------------------------------------------------------------------------*/
  3253. // Renders an emphasis on the given date range. Given a span (unzoned start/end and other misc data)
  3254. renderHighlight: function(span) {
  3255. this.renderFill('highlight', this.spanToSegs(span));
  3256. },
  3257. // Unrenders the emphasis on a date range
  3258. unrenderHighlight: function() {
  3259. this.unrenderFill('highlight');
  3260. },
  3261. // Generates an array of classNames for rendering the highlight. Used by the fill system.
  3262. highlightSegClasses: function() {
  3263. return [ 'fc-highlight' ];
  3264. },
  3265. /* Business Hours
  3266. ------------------------------------------------------------------------------------------------------------------*/
  3267. renderBusinessHours: function() {
  3268. },
  3269. unrenderBusinessHours: function() {
  3270. },
  3271. /* Now Indicator
  3272. ------------------------------------------------------------------------------------------------------------------*/
  3273. getNowIndicatorUnit: function() {
  3274. },
  3275. renderNowIndicator: function(date) {
  3276. },
  3277. unrenderNowIndicator: function() {
  3278. },
  3279. /* Fill System (highlight, background events, business hours)
  3280. --------------------------------------------------------------------------------------------------------------------
  3281. TODO: remove this system. like we did in TimeGrid
  3282. */
  3283. // Renders a set of rectangles over the given segments of time.
  3284. // MUST RETURN a subset of segs, the segs that were actually rendered.
  3285. // Responsible for populating this.elsByFill. TODO: better API for expressing this requirement
  3286. renderFill: function(type, segs) {
  3287. // subclasses must implement
  3288. },
  3289. // Unrenders a specific type of fill that is currently rendered on the grid
  3290. unrenderFill: function(type) {
  3291. var el = this.elsByFill[type];
  3292. if (el) {
  3293. el.remove();
  3294. delete this.elsByFill[type];
  3295. }
  3296. },
  3297. // Renders and assigns an `el` property for each fill segment. Generic enough to work with different types.
  3298. // Only returns segments that successfully rendered.
  3299. // To be harnessed by renderFill (implemented by subclasses).
  3300. // Analagous to renderFgSegEls.
  3301. renderFillSegEls: function(type, segs) {
  3302. var _this = this;
  3303. var segElMethod = this[type + 'SegEl'];
  3304. var html = '';
  3305. var renderedSegs = [];
  3306. var i;
  3307. if (segs.length) {
  3308. // build a large concatenation of segment HTML
  3309. for (i = 0; i < segs.length; i++) {
  3310. html += this.fillSegHtml(type, segs[i]);
  3311. }
  3312. // Grab individual elements from the combined HTML string. Use each as the default rendering.
  3313. // Then, compute the 'el' for each segment.
  3314. $(html).each(function(i, node) {
  3315. var seg = segs[i];
  3316. var el = $(node);
  3317. // allow custom filter methods per-type
  3318. if (segElMethod) {
  3319. el = segElMethod.call(_this, seg, el);
  3320. }
  3321. if (el) { // custom filters did not cancel the render
  3322. el = $(el); // allow custom filter to return raw DOM node
  3323. // correct element type? (would be bad if a non-TD were inserted into a table for example)
  3324. if (el.is(_this.fillSegTag)) {
  3325. seg.el = el;
  3326. renderedSegs.push(seg);
  3327. }
  3328. }
  3329. });
  3330. }
  3331. return renderedSegs;
  3332. },
  3333. fillSegTag: 'div', // subclasses can override
  3334. // Builds the HTML needed for one fill segment. Generic enough to work with different types.
  3335. fillSegHtml: function(type, seg) {
  3336. // custom hooks per-type
  3337. var classesMethod = this[type + 'SegClasses'];
  3338. var cssMethod = this[type + 'SegCss'];
  3339. var classes = classesMethod ? classesMethod.call(this, seg) : [];
  3340. var css = cssToStr(cssMethod ? cssMethod.call(this, seg) : {});
  3341. return '<' + this.fillSegTag +
  3342. (classes.length ? ' class="' + classes.join(' ') + '"' : '') +
  3343. (css ? ' style="' + css + '"' : '') +
  3344. ' />';
  3345. },
  3346. /* Generic rendering utilities for subclasses
  3347. ------------------------------------------------------------------------------------------------------------------*/
  3348. // Computes HTML classNames for a single-day element
  3349. getDayClasses: function(date, noThemeHighlight) {
  3350. var view = this.view;
  3351. var today = view.calendar.getNow();
  3352. var classes = [ 'fc-' + dayIDs[date.day()] ];
  3353. if (
  3354. view.intervalDuration.as('months') == 1 &&
  3355. date.month() != view.intervalStart.month()
  3356. ) {
  3357. classes.push('fc-other-month');
  3358. }
  3359. if (date.isSame(today, 'day')) {
  3360. classes.push('fc-today');
  3361. if (noThemeHighlight !== true) {
  3362. classes.push(view.highlightStateClass);
  3363. }
  3364. }
  3365. else if (date < today) {
  3366. classes.push('fc-past');
  3367. }
  3368. else {
  3369. classes.push('fc-future');
  3370. }
  3371. return classes;
  3372. }
  3373. });
  3374. ;;
  3375. /* Event-rendering and event-interaction methods for the abstract Grid class
  3376. ----------------------------------------------------------------------------------------------------------------------*/
  3377. Grid.mixin({
  3378. // self-config, overridable by subclasses
  3379. segSelector: '.fc-event-container > *', // what constitutes an event element?
  3380. mousedOverSeg: null, // the segment object the user's mouse is over. null if over nothing
  3381. isDraggingSeg: false, // is a segment being dragged? boolean
  3382. isResizingSeg: false, // is a segment being resized? boolean
  3383. isDraggingExternal: false, // jqui-dragging an external element? boolean
  3384. segs: null, // the *event* segments currently rendered in the grid. TODO: rename to `eventSegs`
  3385. // Renders the given events onto the grid
  3386. renderEvents: function(events) {
  3387. var bgEvents = [];
  3388. var fgEvents = [];
  3389. var i;
  3390. for (i = 0; i < events.length; i++) {
  3391. (isBgEvent(events[i]) ? bgEvents : fgEvents).push(events[i]);
  3392. }
  3393. this.segs = [].concat( // record all segs
  3394. this.renderBgEvents(bgEvents),
  3395. this.renderFgEvents(fgEvents)
  3396. );
  3397. },
  3398. renderBgEvents: function(events) {
  3399. var segs = this.eventsToSegs(events);
  3400. // renderBgSegs might return a subset of segs, segs that were actually rendered
  3401. return this.renderBgSegs(segs) || segs;
  3402. },
  3403. renderFgEvents: function(events) {
  3404. var segs = this.eventsToSegs(events);
  3405. // renderFgSegs might return a subset of segs, segs that were actually rendered
  3406. return this.renderFgSegs(segs) || segs;
  3407. },
  3408. // Unrenders all events currently rendered on the grid
  3409. unrenderEvents: function() {
  3410. this.handleSegMouseout(); // trigger an eventMouseout if user's mouse is over an event
  3411. this.clearDragListeners();
  3412. this.unrenderFgSegs();
  3413. this.unrenderBgSegs();
  3414. this.segs = null;
  3415. },
  3416. // Retrieves all rendered segment objects currently rendered on the grid
  3417. getEventSegs: function() {
  3418. return this.segs || [];
  3419. },
  3420. /* Foreground Segment Rendering
  3421. ------------------------------------------------------------------------------------------------------------------*/
  3422. // Renders foreground event segments onto the grid. May return a subset of segs that were rendered.
  3423. renderFgSegs: function(segs) {
  3424. // subclasses must implement
  3425. },
  3426. // Unrenders all currently rendered foreground segments
  3427. unrenderFgSegs: function() {
  3428. // subclasses must implement
  3429. },
  3430. // Renders and assigns an `el` property for each foreground event segment.
  3431. // Only returns segments that successfully rendered.
  3432. // A utility that subclasses may use.
  3433. renderFgSegEls: function(segs, disableResizing) {
  3434. var view = this.view;
  3435. var html = '';
  3436. var renderedSegs = [];
  3437. var i;
  3438. if (segs.length) { // don't build an empty html string
  3439. // build a large concatenation of event segment HTML
  3440. for (i = 0; i < segs.length; i++) {
  3441. html += this.fgSegHtml(segs[i], disableResizing);
  3442. }
  3443. // Grab individual elements from the combined HTML string. Use each as the default rendering.
  3444. // Then, compute the 'el' for each segment. An el might be null if the eventRender callback returned false.
  3445. $(html).each(function(i, node) {
  3446. var seg = segs[i];
  3447. var el = view.resolveEventEl(seg.event, $(node));
  3448. if (el) {
  3449. el.data('fc-seg', seg); // used by handlers
  3450. seg.el = el;
  3451. renderedSegs.push(seg);
  3452. }
  3453. });
  3454. }
  3455. return renderedSegs;
  3456. },
  3457. // Generates the HTML for the default rendering of a foreground event segment. Used by renderFgSegEls()
  3458. fgSegHtml: function(seg, disableResizing) {
  3459. // subclasses should implement
  3460. },
  3461. /* Background Segment Rendering
  3462. ------------------------------------------------------------------------------------------------------------------*/
  3463. // Renders the given background event segments onto the grid.
  3464. // Returns a subset of the segs that were actually rendered.
  3465. renderBgSegs: function(segs) {
  3466. return this.renderFill('bgEvent', segs);
  3467. },
  3468. // Unrenders all the currently rendered background event segments
  3469. unrenderBgSegs: function() {
  3470. this.unrenderFill('bgEvent');
  3471. },
  3472. // Renders a background event element, given the default rendering. Called by the fill system.
  3473. bgEventSegEl: function(seg, el) {
  3474. return this.view.resolveEventEl(seg.event, el); // will filter through eventRender
  3475. },
  3476. // Generates an array of classNames to be used for the default rendering of a background event.
  3477. // Called by fillSegHtml.
  3478. bgEventSegClasses: function(seg) {
  3479. var event = seg.event;
  3480. var source = event.source || {};
  3481. return [ 'fc-bgevent' ].concat(
  3482. event.className,
  3483. source.className || []
  3484. );
  3485. },
  3486. // Generates a semicolon-separated CSS string to be used for the default rendering of a background event.
  3487. // Called by fillSegHtml.
  3488. bgEventSegCss: function(seg) {
  3489. return {
  3490. 'background-color': this.getSegSkinCss(seg)['background-color']
  3491. };
  3492. },
  3493. // Generates an array of classNames to be used for the rendering business hours overlay. Called by the fill system.
  3494. // Called by fillSegHtml.
  3495. businessHoursSegClasses: function(seg) {
  3496. return [ 'fc-nonbusiness', 'fc-bgevent' ];
  3497. },
  3498. /* Business Hours
  3499. ------------------------------------------------------------------------------------------------------------------*/
  3500. // Compute business hour segs for the grid's current date range.
  3501. // Caller must ask if whole-day business hours are needed.
  3502. // If no `businessHours` configuration value is specified, assumes the calendar default.
  3503. buildBusinessHourSegs: function(wholeDay, businessHours) {
  3504. return this.eventsToSegs(
  3505. this.buildBusinessHourEvents(wholeDay, businessHours)
  3506. );
  3507. },
  3508. // Compute business hour *events* for the grid's current date range.
  3509. // Caller must ask if whole-day business hours are needed.
  3510. // If no `businessHours` configuration value is specified, assumes the calendar default.
  3511. buildBusinessHourEvents: function(wholeDay, businessHours) {
  3512. var calendar = this.view.calendar;
  3513. var events;
  3514. if (businessHours == null) {
  3515. // fallback
  3516. // access from calendawr. don't access from view. doesn't update with dynamic options.
  3517. businessHours = calendar.options.businessHours;
  3518. }
  3519. events = calendar.computeBusinessHourEvents(wholeDay, businessHours);
  3520. // HACK. Eventually refactor business hours "events" system.
  3521. // If no events are given, but businessHours is activated, this means the entire visible range should be
  3522. // marked as *not* business-hours, via inverse-background rendering.
  3523. if (!events.length && businessHours) {
  3524. events = [
  3525. $.extend({}, BUSINESS_HOUR_EVENT_DEFAULTS, {
  3526. start: this.view.end, // guaranteed out-of-range
  3527. end: this.view.end, // "
  3528. dow: null
  3529. })
  3530. ];
  3531. }
  3532. return events;
  3533. },
  3534. /* Handlers
  3535. ------------------------------------------------------------------------------------------------------------------*/
  3536. // Attaches event-element-related handlers for *all* rendered event segments of the view.
  3537. bindSegHandlers: function() {
  3538. this.bindSegHandlersToEl(this.el);
  3539. },
  3540. // Attaches event-element-related handlers to an arbitrary container element. leverages bubbling.
  3541. bindSegHandlersToEl: function(el) {
  3542. this.bindSegHandlerToEl(el, 'touchstart', this.handleSegTouchStart);
  3543. this.bindSegHandlerToEl(el, 'mouseenter', this.handleSegMouseover);
  3544. this.bindSegHandlerToEl(el, 'mouseleave', this.handleSegMouseout);
  3545. this.bindSegHandlerToEl(el, 'mousedown', this.handleSegMousedown);
  3546. this.bindSegHandlerToEl(el, 'click', this.handleSegClick);
  3547. },
  3548. // Executes a handler for any a user-interaction on a segment.
  3549. // Handler gets called with (seg, ev), and with the `this` context of the Grid
  3550. bindSegHandlerToEl: function(el, name, handler) {
  3551. var _this = this;
  3552. el.on(name, this.segSelector, function(ev) {
  3553. var seg = $(this).data('fc-seg'); // grab segment data. put there by View::renderEvents
  3554. // only call the handlers if there is not a drag/resize in progress
  3555. if (seg && !_this.isDraggingSeg && !_this.isResizingSeg) {
  3556. return handler.call(_this, seg, ev); // context will be the Grid
  3557. }
  3558. });
  3559. },
  3560. handleSegClick: function(seg, ev) {
  3561. var res = this.view.publiclyTrigger('eventClick', seg.el[0], seg.event, ev); // can return `false` to cancel
  3562. if (res === false) {
  3563. ev.preventDefault();
  3564. }
  3565. },
  3566. // Updates internal state and triggers handlers for when an event element is moused over
  3567. handleSegMouseover: function(seg, ev) {
  3568. if (
  3569. !GlobalEmitter.get().shouldIgnoreMouse() &&
  3570. !this.mousedOverSeg
  3571. ) {
  3572. this.mousedOverSeg = seg;
  3573. if (this.view.isEventResizable(seg.event)) {
  3574. seg.el.addClass('fc-allow-mouse-resize');
  3575. }
  3576. this.view.publiclyTrigger('eventMouseover', seg.el[0], seg.event, ev);
  3577. }
  3578. },
  3579. // Updates internal state and triggers handlers for when an event element is moused out.
  3580. // Can be given no arguments, in which case it will mouseout the segment that was previously moused over.
  3581. handleSegMouseout: function(seg, ev) {
  3582. ev = ev || {}; // if given no args, make a mock mouse event
  3583. if (this.mousedOverSeg) {
  3584. seg = seg || this.mousedOverSeg; // if given no args, use the currently moused-over segment
  3585. this.mousedOverSeg = null;
  3586. if (this.view.isEventResizable(seg.event)) {
  3587. seg.el.removeClass('fc-allow-mouse-resize');
  3588. }
  3589. this.view.publiclyTrigger('eventMouseout', seg.el[0], seg.event, ev);
  3590. }
  3591. },
  3592. handleSegMousedown: function(seg, ev) {
  3593. var isResizing = this.startSegResize(seg, ev, { distance: 5 });
  3594. if (!isResizing && this.view.isEventDraggable(seg.event)) {
  3595. this.buildSegDragListener(seg)
  3596. .startInteraction(ev, {
  3597. distance: 5
  3598. });
  3599. }
  3600. },
  3601. handleSegTouchStart: function(seg, ev) {
  3602. var view = this.view;
  3603. var event = seg.event;
  3604. var isSelected = view.isEventSelected(event);
  3605. var isDraggable = view.isEventDraggable(event);
  3606. var isResizable = view.isEventResizable(event);
  3607. var isResizing = false;
  3608. var dragListener;
  3609. var eventLongPressDelay;
  3610. if (isSelected && isResizable) {
  3611. // only allow resizing of the event is selected
  3612. isResizing = this.startSegResize(seg, ev);
  3613. }
  3614. if (!isResizing && (isDraggable || isResizable)) { // allowed to be selected?
  3615. eventLongPressDelay = view.opt('eventLongPressDelay');
  3616. if (eventLongPressDelay == null) {
  3617. eventLongPressDelay = view.opt('longPressDelay'); // fallback
  3618. }
  3619. dragListener = isDraggable ?
  3620. this.buildSegDragListener(seg) :
  3621. this.buildSegSelectListener(seg); // seg isn't draggable, but still needs to be selected
  3622. dragListener.startInteraction(ev, { // won't start if already started
  3623. delay: isSelected ? 0 : eventLongPressDelay // do delay if not already selected
  3624. });
  3625. }
  3626. },
  3627. // returns boolean whether resizing actually started or not.
  3628. // assumes the seg allows resizing.
  3629. // `dragOptions` are optional.
  3630. startSegResize: function(seg, ev, dragOptions) {
  3631. if ($(ev.target).is('.fc-resizer')) {
  3632. this.buildSegResizeListener(seg, $(ev.target).is('.fc-start-resizer'))
  3633. .startInteraction(ev, dragOptions);
  3634. return true;
  3635. }
  3636. return false;
  3637. },
  3638. /* Event Dragging
  3639. ------------------------------------------------------------------------------------------------------------------*/
  3640. // Builds a listener that will track user-dragging on an event segment.
  3641. // Generic enough to work with any type of Grid.
  3642. // Has side effect of setting/unsetting `segDragListener`
  3643. buildSegDragListener: function(seg) {
  3644. var _this = this;
  3645. var view = this.view;
  3646. var calendar = view.calendar;
  3647. var el = seg.el;
  3648. var event = seg.event;
  3649. var isDragging;
  3650. var mouseFollower; // A clone of the original element that will move with the mouse
  3651. var dropLocation; // zoned event date properties
  3652. if (this.segDragListener) {
  3653. return this.segDragListener;
  3654. }
  3655. // Tracks mouse movement over the *view's* coordinate map. Allows dragging and dropping between subcomponents
  3656. // of the view.
  3657. var dragListener = this.segDragListener = new HitDragListener(view, {
  3658. scroll: view.opt('dragScroll'),
  3659. subjectEl: el,
  3660. subjectCenter: true,
  3661. interactionStart: function(ev) {
  3662. seg.component = _this; // for renderDrag
  3663. isDragging = false;
  3664. mouseFollower = new MouseFollower(seg.el, {
  3665. additionalClass: 'fc-dragging',
  3666. parentEl: view.el,
  3667. opacity: dragListener.isTouch ? null : view.opt('dragOpacity'),
  3668. revertDuration: view.opt('dragRevertDuration'),
  3669. zIndex: 2 // one above the .fc-view
  3670. });
  3671. mouseFollower.hide(); // don't show until we know this is a real drag
  3672. mouseFollower.start(ev);
  3673. },
  3674. dragStart: function(ev) {
  3675. if (dragListener.isTouch && !view.isEventSelected(event)) {
  3676. // if not previously selected, will fire after a delay. then, select the event
  3677. view.selectEvent(event);
  3678. }
  3679. isDragging = true;
  3680. _this.handleSegMouseout(seg, ev); // ensure a mouseout on the manipulated event has been reported
  3681. _this.segDragStart(seg, ev);
  3682. view.hideEvent(event); // hide all event segments. our mouseFollower will take over
  3683. },
  3684. hitOver: function(hit, isOrig, origHit) {
  3685. var dragHelperEls;
  3686. // starting hit could be forced (DayGrid.limit)
  3687. if (seg.hit) {
  3688. origHit = seg.hit;
  3689. }
  3690. // since we are querying the parent view, might not belong to this grid
  3691. dropLocation = _this.computeEventDrop(
  3692. origHit.component.getHitSpan(origHit),
  3693. hit.component.getHitSpan(hit),
  3694. event
  3695. );
  3696. if (dropLocation && !calendar.isEventSpanAllowed(_this.eventToSpan(dropLocation), event)) {
  3697. disableCursor();
  3698. dropLocation = null;
  3699. }
  3700. // if a valid drop location, have the subclass render a visual indication
  3701. if (dropLocation && (dragHelperEls = view.renderDrag(dropLocation, seg))) {
  3702. dragHelperEls.addClass('fc-dragging');
  3703. if (!dragListener.isTouch) {
  3704. _this.applyDragOpacity(dragHelperEls);
  3705. }
  3706. mouseFollower.hide(); // if the subclass is already using a mock event "helper", hide our own
  3707. }
  3708. else {
  3709. mouseFollower.show(); // otherwise, have the helper follow the mouse (no snapping)
  3710. }
  3711. if (isOrig) {
  3712. dropLocation = null; // needs to have moved hits to be a valid drop
  3713. }
  3714. },
  3715. hitOut: function() { // called before mouse moves to a different hit OR moved out of all hits
  3716. view.unrenderDrag(); // unrender whatever was done in renderDrag
  3717. mouseFollower.show(); // show in case we are moving out of all hits
  3718. dropLocation = null;
  3719. },
  3720. hitDone: function() { // Called after a hitOut OR before a dragEnd
  3721. enableCursor();
  3722. },
  3723. interactionEnd: function(ev) {
  3724. delete seg.component; // prevent side effects
  3725. // do revert animation if hasn't changed. calls a callback when finished (whether animation or not)
  3726. mouseFollower.stop(!dropLocation, function() {
  3727. if (isDragging) {
  3728. view.unrenderDrag();
  3729. _this.segDragStop(seg, ev);
  3730. }
  3731. if (dropLocation) {
  3732. // no need to re-show original, will rerender all anyways. esp important if eventRenderWait
  3733. view.reportSegDrop(seg, dropLocation, _this.largeUnit, el, ev);
  3734. }
  3735. else {
  3736. view.showEvent(event);
  3737. }
  3738. });
  3739. _this.segDragListener = null;
  3740. }
  3741. });
  3742. return dragListener;
  3743. },
  3744. // seg isn't draggable, but let's use a generic DragListener
  3745. // simply for the delay, so it can be selected.
  3746. // Has side effect of setting/unsetting `segDragListener`
  3747. buildSegSelectListener: function(seg) {
  3748. var _this = this;
  3749. var view = this.view;
  3750. var event = seg.event;
  3751. if (this.segDragListener) {
  3752. return this.segDragListener;
  3753. }
  3754. var dragListener = this.segDragListener = new DragListener({
  3755. dragStart: function(ev) {
  3756. if (dragListener.isTouch && !view.isEventSelected(event)) {
  3757. // if not previously selected, will fire after a delay. then, select the event
  3758. view.selectEvent(event);
  3759. }
  3760. },
  3761. interactionEnd: function(ev) {
  3762. _this.segDragListener = null;
  3763. }
  3764. });
  3765. return dragListener;
  3766. },
  3767. // Called before event segment dragging starts
  3768. segDragStart: function(seg, ev) {
  3769. this.isDraggingSeg = true;
  3770. this.view.publiclyTrigger('eventDragStart', seg.el[0], seg.event, ev, {}); // last argument is jqui dummy
  3771. },
  3772. // Called after event segment dragging stops
  3773. segDragStop: function(seg, ev) {
  3774. this.isDraggingSeg = false;
  3775. this.view.publiclyTrigger('eventDragStop', seg.el[0], seg.event, ev, {}); // last argument is jqui dummy
  3776. },
  3777. // Given the spans an event drag began, and the span event was dropped, calculates the new zoned start/end/allDay
  3778. // values for the event. Subclasses may override and set additional properties to be used by renderDrag.
  3779. // A falsy returned value indicates an invalid drop.
  3780. // DOES NOT consider overlap/constraint.
  3781. computeEventDrop: function(startSpan, endSpan, event) {
  3782. var calendar = this.view.calendar;
  3783. var dragStart = startSpan.start;
  3784. var dragEnd = endSpan.start;
  3785. var delta;
  3786. var dropLocation; // zoned event date properties
  3787. if (dragStart.hasTime() === dragEnd.hasTime()) {
  3788. delta = this.diffDates(dragEnd, dragStart);
  3789. // if an all-day event was in a timed area and it was dragged to a different time,
  3790. // guarantee an end and adjust start/end to have times
  3791. if (event.allDay && durationHasTime(delta)) {
  3792. dropLocation = {
  3793. start: event.start.clone(),
  3794. end: calendar.getEventEnd(event), // will be an ambig day
  3795. allDay: false // for normalizeEventTimes
  3796. };
  3797. calendar.normalizeEventTimes(dropLocation);
  3798. }
  3799. // othewise, work off existing values
  3800. else {
  3801. dropLocation = pluckEventDateProps(event);
  3802. }
  3803. dropLocation.start.add(delta);
  3804. if (dropLocation.end) {
  3805. dropLocation.end.add(delta);
  3806. }
  3807. }
  3808. else {
  3809. // if switching from day <-> timed, start should be reset to the dropped date, and the end cleared
  3810. dropLocation = {
  3811. start: dragEnd.clone(),
  3812. end: null, // end should be cleared
  3813. allDay: !dragEnd.hasTime()
  3814. };
  3815. }
  3816. return dropLocation;
  3817. },
  3818. // Utility for apply dragOpacity to a jQuery set
  3819. applyDragOpacity: function(els) {
  3820. var opacity = this.view.opt('dragOpacity');
  3821. if (opacity != null) {
  3822. els.css('opacity', opacity);
  3823. }
  3824. },
  3825. /* External Element Dragging
  3826. ------------------------------------------------------------------------------------------------------------------*/
  3827. // Called when a jQuery UI drag is initiated anywhere in the DOM
  3828. externalDragStart: function(ev, ui) {
  3829. var view = this.view;
  3830. var el;
  3831. var accept;
  3832. if (view.opt('droppable')) { // only listen if this setting is on
  3833. el = $((ui ? ui.item : null) || ev.target);
  3834. // Test that the dragged element passes the dropAccept selector or filter function.
  3835. // FYI, the default is "*" (matches all)
  3836. accept = view.opt('dropAccept');
  3837. if ($.isFunction(accept) ? accept.call(el[0], el) : el.is(accept)) {
  3838. if (!this.isDraggingExternal) { // prevent double-listening if fired twice
  3839. this.listenToExternalDrag(el, ev, ui);
  3840. }
  3841. }
  3842. }
  3843. },
  3844. // Called when a jQuery UI drag starts and it needs to be monitored for dropping
  3845. listenToExternalDrag: function(el, ev, ui) {
  3846. var _this = this;
  3847. var calendar = this.view.calendar;
  3848. var meta = getDraggedElMeta(el); // extra data about event drop, including possible event to create
  3849. var dropLocation; // a null value signals an unsuccessful drag
  3850. // listener that tracks mouse movement over date-associated pixel regions
  3851. var dragListener = _this.externalDragListener = new HitDragListener(this, {
  3852. interactionStart: function() {
  3853. _this.isDraggingExternal = true;
  3854. },
  3855. hitOver: function(hit) {
  3856. dropLocation = _this.computeExternalDrop(
  3857. hit.component.getHitSpan(hit), // since we are querying the parent view, might not belong to this grid
  3858. meta
  3859. );
  3860. if ( // invalid hit?
  3861. dropLocation &&
  3862. !calendar.isExternalSpanAllowed(_this.eventToSpan(dropLocation), dropLocation, meta.eventProps)
  3863. ) {
  3864. disableCursor();
  3865. dropLocation = null;
  3866. }
  3867. if (dropLocation) {
  3868. _this.renderDrag(dropLocation); // called without a seg parameter
  3869. }
  3870. },
  3871. hitOut: function() {
  3872. dropLocation = null; // signal unsuccessful
  3873. },
  3874. hitDone: function() { // Called after a hitOut OR before a dragEnd
  3875. enableCursor();
  3876. _this.unrenderDrag();
  3877. },
  3878. interactionEnd: function(ev) {
  3879. if (dropLocation) { // element was dropped on a valid hit
  3880. _this.view.reportExternalDrop(meta, dropLocation, el, ev, ui);
  3881. }
  3882. _this.isDraggingExternal = false;
  3883. _this.externalDragListener = null;
  3884. }
  3885. });
  3886. dragListener.startDrag(ev); // start listening immediately
  3887. },
  3888. // Given a hit to be dropped upon, and misc data associated with the jqui drag (guaranteed to be a plain object),
  3889. // returns the zoned start/end dates for the event that would result from the hypothetical drop. end might be null.
  3890. // Returning a null value signals an invalid drop hit.
  3891. // DOES NOT consider overlap/constraint.
  3892. computeExternalDrop: function(span, meta) {
  3893. var calendar = this.view.calendar;
  3894. var dropLocation = {
  3895. start: calendar.applyTimezone(span.start), // simulate a zoned event start date
  3896. end: null
  3897. };
  3898. // if dropped on an all-day span, and element's metadata specified a time, set it
  3899. if (meta.startTime && !dropLocation.start.hasTime()) {
  3900. dropLocation.start.time(meta.startTime);
  3901. }
  3902. if (meta.duration) {
  3903. dropLocation.end = dropLocation.start.clone().add(meta.duration);
  3904. }
  3905. return dropLocation;
  3906. },
  3907. /* Drag Rendering (for both events and an external elements)
  3908. ------------------------------------------------------------------------------------------------------------------*/
  3909. // Renders a visual indication of an event or external element being dragged.
  3910. // `dropLocation` contains hypothetical start/end/allDay values the event would have if dropped. end can be null.
  3911. // `seg` is the internal segment object that is being dragged. If dragging an external element, `seg` is null.
  3912. // A truthy returned value indicates this method has rendered a helper element.
  3913. // Must return elements used for any mock events.
  3914. renderDrag: function(dropLocation, seg) {
  3915. // subclasses must implement
  3916. },
  3917. // Unrenders a visual indication of an event or external element being dragged
  3918. unrenderDrag: function() {
  3919. // subclasses must implement
  3920. },
  3921. /* Resizing
  3922. ------------------------------------------------------------------------------------------------------------------*/
  3923. // Creates a listener that tracks the user as they resize an event segment.
  3924. // Generic enough to work with any type of Grid.
  3925. buildSegResizeListener: function(seg, isStart) {
  3926. var _this = this;
  3927. var view = this.view;
  3928. var calendar = view.calendar;
  3929. var el = seg.el;
  3930. var event = seg.event;
  3931. var eventEnd = calendar.getEventEnd(event);
  3932. var isDragging;
  3933. var resizeLocation; // zoned event date properties. falsy if invalid resize
  3934. // Tracks mouse movement over the *grid's* coordinate map
  3935. var dragListener = this.segResizeListener = new HitDragListener(this, {
  3936. scroll: view.opt('dragScroll'),
  3937. subjectEl: el,
  3938. interactionStart: function() {
  3939. isDragging = false;
  3940. },
  3941. dragStart: function(ev) {
  3942. isDragging = true;
  3943. _this.handleSegMouseout(seg, ev); // ensure a mouseout on the manipulated event has been reported
  3944. _this.segResizeStart(seg, ev);
  3945. },
  3946. hitOver: function(hit, isOrig, origHit) {
  3947. var origHitSpan = _this.getHitSpan(origHit);
  3948. var hitSpan = _this.getHitSpan(hit);
  3949. resizeLocation = isStart ?
  3950. _this.computeEventStartResize(origHitSpan, hitSpan, event) :
  3951. _this.computeEventEndResize(origHitSpan, hitSpan, event);
  3952. if (resizeLocation) {
  3953. if (!calendar.isEventSpanAllowed(_this.eventToSpan(resizeLocation), event)) {
  3954. disableCursor();
  3955. resizeLocation = null;
  3956. }
  3957. // no change? (FYI, event dates might have zones)
  3958. else if (
  3959. resizeLocation.start.isSame(event.start.clone().stripZone()) &&
  3960. resizeLocation.end.isSame(eventEnd.clone().stripZone())
  3961. ) {
  3962. resizeLocation = null;
  3963. }
  3964. }
  3965. if (resizeLocation) {
  3966. view.hideEvent(event);
  3967. _this.renderEventResize(resizeLocation, seg);
  3968. }
  3969. },
  3970. hitOut: function() { // called before mouse moves to a different hit OR moved out of all hits
  3971. resizeLocation = null;
  3972. view.showEvent(event); // for when out-of-bounds. show original
  3973. },
  3974. hitDone: function() { // resets the rendering to show the original event
  3975. _this.unrenderEventResize();
  3976. enableCursor();
  3977. },
  3978. interactionEnd: function(ev) {
  3979. if (isDragging) {
  3980. _this.segResizeStop(seg, ev);
  3981. }
  3982. if (resizeLocation) { // valid date to resize to?
  3983. // no need to re-show original, will rerender all anyways. esp important if eventRenderWait
  3984. view.reportSegResize(seg, resizeLocation, _this.largeUnit, el, ev);
  3985. }
  3986. else {
  3987. view.showEvent(event);
  3988. }
  3989. _this.segResizeListener = null;
  3990. }
  3991. });
  3992. return dragListener;
  3993. },
  3994. // Called before event segment resizing starts
  3995. segResizeStart: function(seg, ev) {
  3996. this.isResizingSeg = true;
  3997. this.view.publiclyTrigger('eventResizeStart', seg.el[0], seg.event, ev, {}); // last argument is jqui dummy
  3998. },
  3999. // Called after event segment resizing stops
  4000. segResizeStop: function(seg, ev) {
  4001. this.isResizingSeg = false;
  4002. this.view.publiclyTrigger('eventResizeStop', seg.el[0], seg.event, ev, {}); // last argument is jqui dummy
  4003. },
  4004. // Returns new date-information for an event segment being resized from its start
  4005. computeEventStartResize: function(startSpan, endSpan, event) {
  4006. return this.computeEventResize('start', startSpan, endSpan, event);
  4007. },
  4008. // Returns new date-information for an event segment being resized from its end
  4009. computeEventEndResize: function(startSpan, endSpan, event) {
  4010. return this.computeEventResize('end', startSpan, endSpan, event);
  4011. },
  4012. // Returns new zoned date information for an event segment being resized from its start OR end
  4013. // `type` is either 'start' or 'end'.
  4014. // DOES NOT consider overlap/constraint.
  4015. computeEventResize: function(type, startSpan, endSpan, event) {
  4016. var calendar = this.view.calendar;
  4017. var delta = this.diffDates(endSpan[type], startSpan[type]);
  4018. var resizeLocation; // zoned event date properties
  4019. var defaultDuration;
  4020. // build original values to work from, guaranteeing a start and end
  4021. resizeLocation = {
  4022. start: event.start.clone(),
  4023. end: calendar.getEventEnd(event),
  4024. allDay: event.allDay
  4025. };
  4026. // if an all-day event was in a timed area and was resized to a time, adjust start/end to have times
  4027. if (resizeLocation.allDay && durationHasTime(delta)) {
  4028. resizeLocation.allDay = false;
  4029. calendar.normalizeEventTimes(resizeLocation);
  4030. }
  4031. resizeLocation[type].add(delta); // apply delta to start or end
  4032. // if the event was compressed too small, find a new reasonable duration for it
  4033. if (!resizeLocation.start.isBefore(resizeLocation.end)) {
  4034. defaultDuration =
  4035. this.minResizeDuration || // TODO: hack
  4036. (event.allDay ?
  4037. calendar.defaultAllDayEventDuration :
  4038. calendar.defaultTimedEventDuration);
  4039. if (type == 'start') { // resizing the start?
  4040. resizeLocation.start = resizeLocation.end.clone().subtract(defaultDuration);
  4041. }
  4042. else { // resizing the end?
  4043. resizeLocation.end = resizeLocation.start.clone().add(defaultDuration);
  4044. }
  4045. }
  4046. return resizeLocation;
  4047. },
  4048. // Renders a visual indication of an event being resized.
  4049. // `range` has the updated dates of the event. `seg` is the original segment object involved in the drag.
  4050. // Must return elements used for any mock events.
  4051. renderEventResize: function(range, seg) {
  4052. // subclasses must implement
  4053. },
  4054. // Unrenders a visual indication of an event being resized.
  4055. unrenderEventResize: function() {
  4056. // subclasses must implement
  4057. },
  4058. /* Rendering Utils
  4059. ------------------------------------------------------------------------------------------------------------------*/
  4060. // Compute the text that should be displayed on an event's element.
  4061. // `range` can be the Event object itself, or something range-like, with at least a `start`.
  4062. // If event times are disabled, or the event has no time, will return a blank string.
  4063. // If not specified, formatStr will default to the eventTimeFormat setting,
  4064. // and displayEnd will default to the displayEventEnd setting.
  4065. getEventTimeText: function(range, formatStr, displayEnd) {
  4066. if (formatStr == null) {
  4067. formatStr = this.eventTimeFormat;
  4068. }
  4069. if (displayEnd == null) {
  4070. displayEnd = this.displayEventEnd;
  4071. }
  4072. if (this.displayEventTime && range.start.hasTime()) {
  4073. if (displayEnd && range.end) {
  4074. return this.view.formatRange(range, formatStr);
  4075. }
  4076. else {
  4077. return range.start.format(formatStr);
  4078. }
  4079. }
  4080. return '';
  4081. },
  4082. // Generic utility for generating the HTML classNames for an event segment's element
  4083. getSegClasses: function(seg, isDraggable, isResizable) {
  4084. var view = this.view;
  4085. var classes = [
  4086. 'fc-event',
  4087. seg.isStart ? 'fc-start' : 'fc-not-start',
  4088. seg.isEnd ? 'fc-end' : 'fc-not-end'
  4089. ].concat(this.getSegCustomClasses(seg));
  4090. if (isDraggable) {
  4091. classes.push('fc-draggable');
  4092. }
  4093. if (isResizable) {
  4094. classes.push('fc-resizable');
  4095. }
  4096. // event is currently selected? attach a className.
  4097. if (view.isEventSelected(seg.event)) {
  4098. classes.push('fc-selected');
  4099. }
  4100. return classes;
  4101. },
  4102. // List of classes that were defined by the caller of the API in some way
  4103. getSegCustomClasses: function(seg) {
  4104. var event = seg.event;
  4105. return [].concat(
  4106. event.className, // guaranteed to be an array
  4107. event.source ? event.source.className : []
  4108. );
  4109. },
  4110. // Utility for generating event skin-related CSS properties
  4111. getSegSkinCss: function(seg) {
  4112. return {
  4113. 'background-color': this.getSegBackgroundColor(seg),
  4114. 'border-color': this.getSegBorderColor(seg),
  4115. color: this.getSegTextColor(seg)
  4116. };
  4117. },
  4118. // Queries for caller-specified color, then falls back to default
  4119. getSegBackgroundColor: function(seg) {
  4120. return seg.event.backgroundColor ||
  4121. seg.event.color ||
  4122. this.getSegDefaultBackgroundColor(seg);
  4123. },
  4124. getSegDefaultBackgroundColor: function(seg) {
  4125. var source = seg.event.source || {};
  4126. return source.backgroundColor ||
  4127. source.color ||
  4128. this.view.opt('eventBackgroundColor') ||
  4129. this.view.opt('eventColor');
  4130. },
  4131. // Queries for caller-specified color, then falls back to default
  4132. getSegBorderColor: function(seg) {
  4133. return seg.event.borderColor ||
  4134. seg.event.color ||
  4135. this.getSegDefaultBorderColor(seg);
  4136. },
  4137. getSegDefaultBorderColor: function(seg) {
  4138. var source = seg.event.source || {};
  4139. return source.borderColor ||
  4140. source.color ||
  4141. this.view.opt('eventBorderColor') ||
  4142. this.view.opt('eventColor');
  4143. },
  4144. // Queries for caller-specified color, then falls back to default
  4145. getSegTextColor: function(seg) {
  4146. return seg.event.textColor ||
  4147. this.getSegDefaultTextColor(seg);
  4148. },
  4149. getSegDefaultTextColor: function(seg) {
  4150. var source = seg.event.source || {};
  4151. return source.textColor ||
  4152. this.view.opt('eventTextColor');
  4153. },
  4154. /* Converting events -> eventRange -> eventSpan -> eventSegs
  4155. ------------------------------------------------------------------------------------------------------------------*/
  4156. // Generates an array of segments for the given single event
  4157. // Can accept an event "location" as well (which only has start/end and no allDay)
  4158. eventToSegs: function(event) {
  4159. return this.eventsToSegs([ event ]);
  4160. },
  4161. eventToSpan: function(event) {
  4162. return this.eventToSpans(event)[0];
  4163. },
  4164. // Generates spans (always unzoned) for the given event.
  4165. // Does not do any inverting for inverse-background events.
  4166. // Can accept an event "location" as well (which only has start/end and no allDay)
  4167. eventToSpans: function(event) {
  4168. var range = this.eventToRange(event);
  4169. return this.eventRangeToSpans(range, event);
  4170. },
  4171. // Converts an array of event objects into an array of event segment objects.
  4172. // A custom `segSliceFunc` may be given for arbitrarily slicing up events.
  4173. // Doesn't guarantee an order for the resulting array.
  4174. eventsToSegs: function(allEvents, segSliceFunc) {
  4175. var _this = this;
  4176. var eventsById = groupEventsById(allEvents);
  4177. var segs = [];
  4178. $.each(eventsById, function(id, events) {
  4179. var ranges = [];
  4180. var i;
  4181. for (i = 0; i < events.length; i++) {
  4182. ranges.push(_this.eventToRange(events[i]));
  4183. }
  4184. // inverse-background events (utilize only the first event in calculations)
  4185. if (isInverseBgEvent(events[0])) {
  4186. ranges = _this.invertRanges(ranges);
  4187. for (i = 0; i < ranges.length; i++) {
  4188. segs.push.apply(segs, // append to
  4189. _this.eventRangeToSegs(ranges[i], events[0], segSliceFunc));
  4190. }
  4191. }
  4192. // normal event ranges
  4193. else {
  4194. for (i = 0; i < ranges.length; i++) {
  4195. segs.push.apply(segs, // append to
  4196. _this.eventRangeToSegs(ranges[i], events[i], segSliceFunc));
  4197. }
  4198. }
  4199. });
  4200. return segs;
  4201. },
  4202. // Generates the unzoned start/end dates an event appears to occupy
  4203. // Can accept an event "location" as well (which only has start/end and no allDay)
  4204. eventToRange: function(event) {
  4205. var calendar = this.view.calendar;
  4206. var start = event.start.clone().stripZone();
  4207. var end = (
  4208. event.end ?
  4209. event.end.clone() :
  4210. // derive the end from the start and allDay. compute allDay if necessary
  4211. calendar.getDefaultEventEnd(
  4212. event.allDay != null ?
  4213. event.allDay :
  4214. !event.start.hasTime(),
  4215. event.start
  4216. )
  4217. ).stripZone();
  4218. // hack: dynamic locale change forgets to upate stored event localed
  4219. calendar.localizeMoment(start);
  4220. calendar.localizeMoment(end);
  4221. return { start: start, end: end };
  4222. },
  4223. // Given an event's range (unzoned start/end), and the event itself,
  4224. // slice into segments (using the segSliceFunc function if specified)
  4225. eventRangeToSegs: function(range, event, segSliceFunc) {
  4226. var spans = this.eventRangeToSpans(range, event);
  4227. var segs = [];
  4228. var i;
  4229. for (i = 0; i < spans.length; i++) {
  4230. segs.push.apply(segs, // append to
  4231. this.eventSpanToSegs(spans[i], event, segSliceFunc));
  4232. }
  4233. return segs;
  4234. },
  4235. // Given an event's unzoned date range, return an array of "span" objects.
  4236. // Subclasses can override.
  4237. eventRangeToSpans: function(range, event) {
  4238. return [ $.extend({}, range) ]; // copy into a single-item array
  4239. },
  4240. // Given an event's span (unzoned start/end and other misc data), and the event itself,
  4241. // slices into segments and attaches event-derived properties to them.
  4242. eventSpanToSegs: function(span, event, segSliceFunc) {
  4243. var segs = segSliceFunc ? segSliceFunc(span) : this.spanToSegs(span);
  4244. var i, seg;
  4245. for (i = 0; i < segs.length; i++) {
  4246. seg = segs[i];
  4247. seg.event = event;
  4248. seg.eventStartMS = +span.start; // TODO: not the best name after making spans unzoned
  4249. seg.eventDurationMS = span.end - span.start;
  4250. }
  4251. return segs;
  4252. },
  4253. // Produces a new array of range objects that will cover all the time NOT covered by the given ranges.
  4254. // SIDE EFFECT: will mutate the given array and will use its date references.
  4255. invertRanges: function(ranges) {
  4256. var view = this.view;
  4257. var viewStart = view.start.clone(); // need a copy
  4258. var viewEnd = view.end.clone(); // need a copy
  4259. var inverseRanges = [];
  4260. var start = viewStart; // the end of the previous range. the start of the new range
  4261. var i, range;
  4262. // ranges need to be in order. required for our date-walking algorithm
  4263. ranges.sort(compareRanges);
  4264. for (i = 0; i < ranges.length; i++) {
  4265. range = ranges[i];
  4266. // add the span of time before the event (if there is any)
  4267. if (range.start > start) { // compare millisecond time (skip any ambig logic)
  4268. inverseRanges.push({
  4269. start: start,
  4270. end: range.start
  4271. });
  4272. }
  4273. start = range.end;
  4274. }
  4275. // add the span of time after the last event (if there is any)
  4276. if (start < viewEnd) { // compare millisecond time (skip any ambig logic)
  4277. inverseRanges.push({
  4278. start: start,
  4279. end: viewEnd
  4280. });
  4281. }
  4282. return inverseRanges;
  4283. },
  4284. sortEventSegs: function(segs) {
  4285. segs.sort(proxy(this, 'compareEventSegs'));
  4286. },
  4287. // A cmp function for determining which segments should take visual priority
  4288. compareEventSegs: function(seg1, seg2) {
  4289. return seg1.eventStartMS - seg2.eventStartMS || // earlier events go first
  4290. seg2.eventDurationMS - seg1.eventDurationMS || // tie? longer events go first
  4291. seg2.event.allDay - seg1.event.allDay || // tie? put all-day events first (booleans cast to 0/1)
  4292. compareByFieldSpecs(seg1.event, seg2.event, this.view.eventOrderSpecs);
  4293. }
  4294. });
  4295. /* Utilities
  4296. ----------------------------------------------------------------------------------------------------------------------*/
  4297. function pluckEventDateProps(event) {
  4298. return {
  4299. start: event.start.clone(),
  4300. end: event.end ? event.end.clone() : null,
  4301. allDay: event.allDay // keep it the same
  4302. };
  4303. }
  4304. FC.pluckEventDateProps = pluckEventDateProps;
  4305. function isBgEvent(event) { // returns true if background OR inverse-background
  4306. var rendering = getEventRendering(event);
  4307. return rendering === 'background' || rendering === 'inverse-background';
  4308. }
  4309. FC.isBgEvent = isBgEvent; // export
  4310. function isInverseBgEvent(event) {
  4311. return getEventRendering(event) === 'inverse-background';
  4312. }
  4313. function getEventRendering(event) {
  4314. return firstDefined((event.source || {}).rendering, event.rendering);
  4315. }
  4316. function groupEventsById(events) {
  4317. var eventsById = {};
  4318. var i, event;
  4319. for (i = 0; i < events.length; i++) {
  4320. event = events[i];
  4321. (eventsById[event._id] || (eventsById[event._id] = [])).push(event);
  4322. }
  4323. return eventsById;
  4324. }
  4325. // A cmp function for determining which non-inverted "ranges" (see above) happen earlier
  4326. function compareRanges(range1, range2) {
  4327. return range1.start - range2.start; // earlier ranges go first
  4328. }
  4329. /* External-Dragging-Element Data
  4330. ----------------------------------------------------------------------------------------------------------------------*/
  4331. // Require all HTML5 data-* attributes used by FullCalendar to have this prefix.
  4332. // A value of '' will query attributes like data-event. A value of 'fc' will query attributes like data-fc-event.
  4333. FC.dataAttrPrefix = '';
  4334. // Given a jQuery element that might represent a dragged FullCalendar event, returns an intermediate data structure
  4335. // to be used for Event Object creation.
  4336. // A defined `.eventProps`, even when empty, indicates that an event should be created.
  4337. function getDraggedElMeta(el) {
  4338. var prefix = FC.dataAttrPrefix;
  4339. var eventProps; // properties for creating the event, not related to date/time
  4340. var startTime; // a Duration
  4341. var duration;
  4342. var stick;
  4343. if (prefix) { prefix += '-'; }
  4344. eventProps = el.data(prefix + 'event') || null;
  4345. if (eventProps) {
  4346. if (typeof eventProps === 'object') {
  4347. eventProps = $.extend({}, eventProps); // make a copy
  4348. }
  4349. else { // something like 1 or true. still signal event creation
  4350. eventProps = {};
  4351. }
  4352. // pluck special-cased date/time properties
  4353. startTime = eventProps.start;
  4354. if (startTime == null) { startTime = eventProps.time; } // accept 'time' as well
  4355. duration = eventProps.duration;
  4356. stick = eventProps.stick;
  4357. delete eventProps.start;
  4358. delete eventProps.time;
  4359. delete eventProps.duration;
  4360. delete eventProps.stick;
  4361. }
  4362. // fallback to standalone attribute values for each of the date/time properties
  4363. if (startTime == null) { startTime = el.data(prefix + 'start'); }
  4364. if (startTime == null) { startTime = el.data(prefix + 'time'); } // accept 'time' as well
  4365. if (duration == null) { duration = el.data(prefix + 'duration'); }
  4366. if (stick == null) { stick = el.data(prefix + 'stick'); }
  4367. // massage into correct data types
  4368. startTime = startTime != null ? moment.duration(startTime) : null;
  4369. duration = duration != null ? moment.duration(duration) : null;
  4370. stick = Boolean(stick);
  4371. return { eventProps: eventProps, startTime: startTime, duration: duration, stick: stick };
  4372. }
  4373. ;;
  4374. /*
  4375. A set of rendering and date-related methods for a visual component comprised of one or more rows of day columns.
  4376. Prerequisite: the object being mixed into needs to be a *Grid*
  4377. */
  4378. var DayTableMixin = FC.DayTableMixin = {
  4379. breakOnWeeks: false, // should create a new row for each week?
  4380. dayDates: null, // whole-day dates for each column. left to right
  4381. dayIndices: null, // for each day from start, the offset
  4382. daysPerRow: null,
  4383. rowCnt: null,
  4384. colCnt: null,
  4385. colHeadFormat: null,
  4386. // Populates internal variables used for date calculation and rendering
  4387. updateDayTable: function() {
  4388. var view = this.view;
  4389. var date = this.start.clone();
  4390. var dayIndex = -1;
  4391. var dayIndices = [];
  4392. var dayDates = [];
  4393. var daysPerRow;
  4394. var firstDay;
  4395. var rowCnt;
  4396. while (date.isBefore(this.end)) { // loop each day from start to end
  4397. if (view.isHiddenDay(date)) {
  4398. dayIndices.push(dayIndex + 0.5); // mark that it's between indices
  4399. }
  4400. else {
  4401. dayIndex++;
  4402. dayIndices.push(dayIndex);
  4403. dayDates.push(date.clone());
  4404. }
  4405. date.add(1, 'days');
  4406. }
  4407. if (this.breakOnWeeks) {
  4408. // count columns until the day-of-week repeats
  4409. firstDay = dayDates[0].day();
  4410. for (daysPerRow = 1; daysPerRow < dayDates.length; daysPerRow++) {
  4411. if (dayDates[daysPerRow].day() == firstDay) {
  4412. break;
  4413. }
  4414. }
  4415. rowCnt = Math.ceil(dayDates.length / daysPerRow);
  4416. }
  4417. else {
  4418. rowCnt = 1;
  4419. daysPerRow = dayDates.length;
  4420. }
  4421. this.dayDates = dayDates;
  4422. this.dayIndices = dayIndices;
  4423. this.daysPerRow = daysPerRow;
  4424. this.rowCnt = rowCnt;
  4425. this.updateDayTableCols();
  4426. },
  4427. // Computes and assigned the colCnt property and updates any options that may be computed from it
  4428. updateDayTableCols: function() {
  4429. this.colCnt = this.computeColCnt();
  4430. this.colHeadFormat = this.view.opt('columnFormat') || this.computeColHeadFormat();
  4431. },
  4432. // Determines how many columns there should be in the table
  4433. computeColCnt: function() {
  4434. return this.daysPerRow;
  4435. },
  4436. // Computes the ambiguously-timed moment for the given cell
  4437. getCellDate: function(row, col) {
  4438. return this.dayDates[
  4439. this.getCellDayIndex(row, col)
  4440. ].clone();
  4441. },
  4442. // Computes the ambiguously-timed date range for the given cell
  4443. getCellRange: function(row, col) {
  4444. var start = this.getCellDate(row, col);
  4445. var end = start.clone().add(1, 'days');
  4446. return { start: start, end: end };
  4447. },
  4448. // Returns the number of day cells, chronologically, from the first of the grid (0-based)
  4449. getCellDayIndex: function(row, col) {
  4450. return row * this.daysPerRow + this.getColDayIndex(col);
  4451. },
  4452. // Returns the numner of day cells, chronologically, from the first cell in *any given row*
  4453. getColDayIndex: function(col) {
  4454. if (this.isRTL) {
  4455. return this.colCnt - 1 - col;
  4456. }
  4457. else {
  4458. return col;
  4459. }
  4460. },
  4461. // Given a date, returns its chronolocial cell-index from the first cell of the grid.
  4462. // If the date lies between cells (because of hiddenDays), returns a floating-point value between offsets.
  4463. // If before the first offset, returns a negative number.
  4464. // If after the last offset, returns an offset past the last cell offset.
  4465. // Only works for *start* dates of cells. Will not work for exclusive end dates for cells.
  4466. getDateDayIndex: function(date) {
  4467. var dayIndices = this.dayIndices;
  4468. var dayOffset = date.diff(this.start, 'days');
  4469. if (dayOffset < 0) {
  4470. return dayIndices[0] - 1;
  4471. }
  4472. else if (dayOffset >= dayIndices.length) {
  4473. return dayIndices[dayIndices.length - 1] + 1;
  4474. }
  4475. else {
  4476. return dayIndices[dayOffset];
  4477. }
  4478. },
  4479. /* Options
  4480. ------------------------------------------------------------------------------------------------------------------*/
  4481. // Computes a default column header formatting string if `colFormat` is not explicitly defined
  4482. computeColHeadFormat: function() {
  4483. // if more than one week row, or if there are a lot of columns with not much space,
  4484. // put just the day numbers will be in each cell
  4485. if (this.rowCnt > 1 || this.colCnt > 10) {
  4486. return 'ddd'; // "Sat"
  4487. }
  4488. // multiple days, so full single date string WON'T be in title text
  4489. else if (this.colCnt > 1) {
  4490. return this.view.opt('dayOfMonthFormat'); // "Sat 12/10"
  4491. }
  4492. // single day, so full single date string will probably be in title text
  4493. else {
  4494. return 'dddd'; // "Saturday"
  4495. }
  4496. },
  4497. /* Slicing
  4498. ------------------------------------------------------------------------------------------------------------------*/
  4499. // Slices up a date range into a segment for every week-row it intersects with
  4500. sliceRangeByRow: function(range) {
  4501. var daysPerRow = this.daysPerRow;
  4502. var normalRange = this.view.computeDayRange(range); // make whole-day range, considering nextDayThreshold
  4503. var rangeFirst = this.getDateDayIndex(normalRange.start); // inclusive first index
  4504. var rangeLast = this.getDateDayIndex(normalRange.end.clone().subtract(1, 'days')); // inclusive last index
  4505. var segs = [];
  4506. var row;
  4507. var rowFirst, rowLast; // inclusive day-index range for current row
  4508. var segFirst, segLast; // inclusive day-index range for segment
  4509. for (row = 0; row < this.rowCnt; row++) {
  4510. rowFirst = row * daysPerRow;
  4511. rowLast = rowFirst + daysPerRow - 1;
  4512. // intersect segment's offset range with the row's
  4513. segFirst = Math.max(rangeFirst, rowFirst);
  4514. segLast = Math.min(rangeLast, rowLast);
  4515. // deal with in-between indices
  4516. segFirst = Math.ceil(segFirst); // in-between starts round to next cell
  4517. segLast = Math.floor(segLast); // in-between ends round to prev cell
  4518. if (segFirst <= segLast) { // was there any intersection with the current row?
  4519. segs.push({
  4520. row: row,
  4521. // normalize to start of row
  4522. firstRowDayIndex: segFirst - rowFirst,
  4523. lastRowDayIndex: segLast - rowFirst,
  4524. // must be matching integers to be the segment's start/end
  4525. isStart: segFirst === rangeFirst,
  4526. isEnd: segLast === rangeLast
  4527. });
  4528. }
  4529. }
  4530. return segs;
  4531. },
  4532. // Slices up a date range into a segment for every day-cell it intersects with.
  4533. // TODO: make more DRY with sliceRangeByRow somehow.
  4534. sliceRangeByDay: function(range) {
  4535. var daysPerRow = this.daysPerRow;
  4536. var normalRange = this.view.computeDayRange(range); // make whole-day range, considering nextDayThreshold
  4537. var rangeFirst = this.getDateDayIndex(normalRange.start); // inclusive first index
  4538. var rangeLast = this.getDateDayIndex(normalRange.end.clone().subtract(1, 'days')); // inclusive last index
  4539. var segs = [];
  4540. var row;
  4541. var rowFirst, rowLast; // inclusive day-index range for current row
  4542. var i;
  4543. var segFirst, segLast; // inclusive day-index range for segment
  4544. for (row = 0; row < this.rowCnt; row++) {
  4545. rowFirst = row * daysPerRow;
  4546. rowLast = rowFirst + daysPerRow - 1;
  4547. for (i = rowFirst; i <= rowLast; i++) {
  4548. // intersect segment's offset range with the row's
  4549. segFirst = Math.max(rangeFirst, i);
  4550. segLast = Math.min(rangeLast, i);
  4551. // deal with in-between indices
  4552. segFirst = Math.ceil(segFirst); // in-between starts round to next cell
  4553. segLast = Math.floor(segLast); // in-between ends round to prev cell
  4554. if (segFirst <= segLast) { // was there any intersection with the current row?
  4555. segs.push({
  4556. row: row,
  4557. // normalize to start of row
  4558. firstRowDayIndex: segFirst - rowFirst,
  4559. lastRowDayIndex: segLast - rowFirst,
  4560. // must be matching integers to be the segment's start/end
  4561. isStart: segFirst === rangeFirst,
  4562. isEnd: segLast === rangeLast
  4563. });
  4564. }
  4565. }
  4566. }
  4567. return segs;
  4568. },
  4569. /* Header Rendering
  4570. ------------------------------------------------------------------------------------------------------------------*/
  4571. renderHeadHtml: function() {
  4572. var view = this.view;
  4573. return '' +
  4574. '<div class="fc-row ' + view.widgetHeaderClass + '">' +
  4575. '<table>' +
  4576. '<thead>' +
  4577. this.renderHeadTrHtml() +
  4578. '</thead>' +
  4579. '</table>' +
  4580. '</div>';
  4581. },
  4582. renderHeadIntroHtml: function() {
  4583. return this.renderIntroHtml(); // fall back to generic
  4584. },
  4585. renderHeadTrHtml: function() {
  4586. return '' +
  4587. '<tr>' +
  4588. (this.isRTL ? '' : this.renderHeadIntroHtml()) +
  4589. this.renderHeadDateCellsHtml() +
  4590. (this.isRTL ? this.renderHeadIntroHtml() : '') +
  4591. '</tr>';
  4592. },
  4593. renderHeadDateCellsHtml: function() {
  4594. var htmls = [];
  4595. var col, date;
  4596. for (col = 0; col < this.colCnt; col++) {
  4597. date = this.getCellDate(0, col);
  4598. htmls.push(this.renderHeadDateCellHtml(date));
  4599. }
  4600. return htmls.join('');
  4601. },
  4602. // TODO: when internalApiVersion, accept an object for HTML attributes
  4603. // (colspan should be no different)
  4604. renderHeadDateCellHtml: function(date, colspan, otherAttrs) {
  4605. var view = this.view;
  4606. var classNames = [
  4607. 'fc-day-header',
  4608. view.widgetHeaderClass
  4609. ];
  4610. // if only one row of days, the classNames on the header can represent the specific days beneath
  4611. if (this.rowCnt === 1) {
  4612. classNames = classNames.concat(
  4613. // includes the day-of-week class
  4614. // noThemeHighlight=true (don't highlight the header)
  4615. this.getDayClasses(date, true)
  4616. );
  4617. }
  4618. else {
  4619. classNames.push('fc-' + dayIDs[date.day()]); // only add the day-of-week class
  4620. }
  4621. return '' +
  4622. '<th class="' + classNames.join(' ') + '"' +
  4623. (this.rowCnt === 1 ?
  4624. ' data-date="' + date.format('YYYY-MM-DD') + '"' :
  4625. '') +
  4626. (colspan > 1 ?
  4627. ' colspan="' + colspan + '"' :
  4628. '') +
  4629. (otherAttrs ?
  4630. ' ' + otherAttrs :
  4631. '') +
  4632. '>' +
  4633. // don't make a link if the heading could represent multiple days, or if there's only one day (forceOff)
  4634. view.buildGotoAnchorHtml(
  4635. { date: date, forceOff: this.rowCnt > 1 || this.colCnt === 1 },
  4636. htmlEscape(date.format(this.colHeadFormat)) // inner HTML
  4637. ) +
  4638. '</th>';
  4639. },
  4640. /* Background Rendering
  4641. ------------------------------------------------------------------------------------------------------------------*/
  4642. renderBgTrHtml: function(row) {
  4643. return '' +
  4644. '<tr>' +
  4645. (this.isRTL ? '' : this.renderBgIntroHtml(row)) +
  4646. this.renderBgCellsHtml(row) +
  4647. (this.isRTL ? this.renderBgIntroHtml(row) : '') +
  4648. '</tr>';
  4649. },
  4650. renderBgIntroHtml: function(row) {
  4651. return this.renderIntroHtml(); // fall back to generic
  4652. },
  4653. renderBgCellsHtml: function(row) {
  4654. var htmls = [];
  4655. var col, date;
  4656. for (col = 0; col < this.colCnt; col++) {
  4657. date = this.getCellDate(row, col);
  4658. htmls.push(this.renderBgCellHtml(date));
  4659. }
  4660. return htmls.join('');
  4661. },
  4662. renderBgCellHtml: function(date, otherAttrs) {
  4663. var view = this.view;
  4664. var classes = this.getDayClasses(date);
  4665. classes.unshift('fc-day', view.widgetContentClass);
  4666. return '<td class="' + classes.join(' ') + '"' +
  4667. ' data-date="' + date.format('YYYY-MM-DD') + '"' + // if date has a time, won't format it
  4668. (otherAttrs ?
  4669. ' ' + otherAttrs :
  4670. '') +
  4671. '></td>';
  4672. },
  4673. /* Generic
  4674. ------------------------------------------------------------------------------------------------------------------*/
  4675. // Generates the default HTML intro for any row. User classes should override
  4676. renderIntroHtml: function() {
  4677. },
  4678. // TODO: a generic method for dealing with <tr>, RTL, intro
  4679. // when increment internalApiVersion
  4680. // wrapTr (scheduler)
  4681. /* Utils
  4682. ------------------------------------------------------------------------------------------------------------------*/
  4683. // Applies the generic "intro" and "outro" HTML to the given cells.
  4684. // Intro means the leftmost cell when the calendar is LTR and the rightmost cell when RTL. Vice-versa for outro.
  4685. bookendCells: function(trEl) {
  4686. var introHtml = this.renderIntroHtml();
  4687. if (introHtml) {
  4688. if (this.isRTL) {
  4689. trEl.append(introHtml);
  4690. }
  4691. else {
  4692. trEl.prepend(introHtml);
  4693. }
  4694. }
  4695. }
  4696. };
  4697. ;;
  4698. /* A component that renders a grid of whole-days that runs horizontally. There can be multiple rows, one per week.
  4699. ----------------------------------------------------------------------------------------------------------------------*/
  4700. var DayGrid = FC.DayGrid = Grid.extend(DayTableMixin, {
  4701. numbersVisible: false, // should render a row for day/week numbers? set by outside view. TODO: make internal
  4702. bottomCoordPadding: 0, // hack for extending the hit area for the last row of the coordinate grid
  4703. rowEls: null, // set of fake row elements
  4704. cellEls: null, // set of whole-day elements comprising the row's background
  4705. helperEls: null, // set of cell skeleton elements for rendering the mock event "helper"
  4706. rowCoordCache: null,
  4707. colCoordCache: null,
  4708. // Renders the rows and columns into the component's `this.el`, which should already be assigned.
  4709. // isRigid determins whether the individual rows should ignore the contents and be a constant height.
  4710. // Relies on the view's colCnt and rowCnt. In the future, this component should probably be self-sufficient.
  4711. renderDates: function(isRigid) {
  4712. var view = this.view;
  4713. var rowCnt = this.rowCnt;
  4714. var colCnt = this.colCnt;
  4715. var html = '';
  4716. var row;
  4717. var col;
  4718. for (row = 0; row < rowCnt; row++) {
  4719. html += this.renderDayRowHtml(row, isRigid);
  4720. }
  4721. this.el.html(html);
  4722. this.rowEls = this.el.find('.fc-row');
  4723. this.cellEls = this.el.find('.fc-day');
  4724. this.rowCoordCache = new CoordCache({
  4725. els: this.rowEls,
  4726. isVertical: true
  4727. });
  4728. this.colCoordCache = new CoordCache({
  4729. els: this.cellEls.slice(0, this.colCnt), // only the first row
  4730. isHorizontal: true
  4731. });
  4732. // trigger dayRender with each cell's element
  4733. for (row = 0; row < rowCnt; row++) {
  4734. for (col = 0; col < colCnt; col++) {
  4735. view.publiclyTrigger(
  4736. 'dayRender',
  4737. null,
  4738. this.getCellDate(row, col),
  4739. this.getCellEl(row, col)
  4740. );
  4741. }
  4742. }
  4743. },
  4744. unrenderDates: function() {
  4745. this.removeSegPopover();
  4746. },
  4747. renderBusinessHours: function() {
  4748. var segs = this.buildBusinessHourSegs(true); // wholeDay=true
  4749. this.renderFill('businessHours', segs, 'bgevent');
  4750. },
  4751. unrenderBusinessHours: function() {
  4752. this.unrenderFill('businessHours');
  4753. },
  4754. // Generates the HTML for a single row, which is a div that wraps a table.
  4755. // `row` is the row number.
  4756. renderDayRowHtml: function(row, isRigid) {
  4757. var view = this.view;
  4758. var classes = [ 'fc-row', 'fc-week', view.widgetContentClass ];
  4759. if (isRigid) {
  4760. classes.push('fc-rigid');
  4761. }
  4762. return '' +
  4763. '<div class="' + classes.join(' ') + '">' +
  4764. '<div class="fc-bg">' +
  4765. '<table>' +
  4766. this.renderBgTrHtml(row) +
  4767. '</table>' +
  4768. '</div>' +
  4769. '<div class="fc-content-skeleton">' +
  4770. '<table>' +
  4771. (this.numbersVisible ?
  4772. '<thead>' +
  4773. this.renderNumberTrHtml(row) +
  4774. '</thead>' :
  4775. ''
  4776. ) +
  4777. '</table>' +
  4778. '</div>' +
  4779. '</div>';
  4780. },
  4781. /* Grid Number Rendering
  4782. ------------------------------------------------------------------------------------------------------------------*/
  4783. renderNumberTrHtml: function(row) {
  4784. return '' +
  4785. '<tr>' +
  4786. (this.isRTL ? '' : this.renderNumberIntroHtml(row)) +
  4787. this.renderNumberCellsHtml(row) +
  4788. (this.isRTL ? this.renderNumberIntroHtml(row) : '') +
  4789. '</tr>';
  4790. },
  4791. renderNumberIntroHtml: function(row) {
  4792. return this.renderIntroHtml();
  4793. },
  4794. renderNumberCellsHtml: function(row) {
  4795. var htmls = [];
  4796. var col, date;
  4797. for (col = 0; col < this.colCnt; col++) {
  4798. date = this.getCellDate(row, col);
  4799. htmls.push(this.renderNumberCellHtml(date));
  4800. }
  4801. return htmls.join('');
  4802. },
  4803. // Generates the HTML for the <td>s of the "number" row in the DayGrid's content skeleton.
  4804. // The number row will only exist if either day numbers or week numbers are turned on.
  4805. renderNumberCellHtml: function(date) {
  4806. var html = '';
  4807. var classes;
  4808. var weekCalcFirstDoW;
  4809. if (!this.view.dayNumbersVisible && !this.view.cellWeekNumbersVisible) {
  4810. // no numbers in day cell (week number must be along the side)
  4811. return '<td/>'; // will create an empty space above events :(
  4812. }
  4813. classes = this.getDayClasses(date);
  4814. classes.unshift('fc-day-top');
  4815. if (this.view.cellWeekNumbersVisible) {
  4816. // To determine the day of week number change under ISO, we cannot
  4817. // rely on moment.js methods such as firstDayOfWeek() or weekday(),
  4818. // because they rely on the locale's dow (possibly overridden by
  4819. // our firstDay option), which may not be Monday. We cannot change
  4820. // dow, because that would affect the calendar start day as well.
  4821. if (date._locale._fullCalendar_weekCalc === 'ISO') {
  4822. weekCalcFirstDoW = 1; // Monday by ISO 8601 definition
  4823. }
  4824. else {
  4825. weekCalcFirstDoW = date._locale.firstDayOfWeek();
  4826. }
  4827. }
  4828. html += '<td class="' + classes.join(' ') + '" data-date="' + date.format() + '">';
  4829. if (this.view.cellWeekNumbersVisible && (date.day() == weekCalcFirstDoW)) {
  4830. html += this.view.buildGotoAnchorHtml(
  4831. { date: date, type: 'week' },
  4832. { 'class': 'fc-week-number' },
  4833. date.format('w') // inner HTML
  4834. );
  4835. }
  4836. if (this.view.dayNumbersVisible) {
  4837. html += this.view.buildGotoAnchorHtml(
  4838. date,
  4839. { 'class': 'fc-day-number' },
  4840. date.date() // inner HTML
  4841. );
  4842. }
  4843. html += '</td>';
  4844. return html;
  4845. },
  4846. /* Options
  4847. ------------------------------------------------------------------------------------------------------------------*/
  4848. // Computes a default event time formatting string if `timeFormat` is not explicitly defined
  4849. computeEventTimeFormat: function() {
  4850. return this.view.opt('extraSmallTimeFormat'); // like "6p" or "6:30p"
  4851. },
  4852. // Computes a default `displayEventEnd` value if one is not expliclty defined
  4853. computeDisplayEventEnd: function() {
  4854. return this.colCnt == 1; // we'll likely have space if there's only one day
  4855. },
  4856. /* Dates
  4857. ------------------------------------------------------------------------------------------------------------------*/
  4858. rangeUpdated: function() {
  4859. this.updateDayTable();
  4860. },
  4861. // Slices up the given span (unzoned start/end with other misc data) into an array of segments
  4862. spanToSegs: function(span) {
  4863. var segs = this.sliceRangeByRow(span);
  4864. var i, seg;
  4865. for (i = 0; i < segs.length; i++) {
  4866. seg = segs[i];
  4867. if (this.isRTL) {
  4868. seg.leftCol = this.daysPerRow - 1 - seg.lastRowDayIndex;
  4869. seg.rightCol = this.daysPerRow - 1 - seg.firstRowDayIndex;
  4870. }
  4871. else {
  4872. seg.leftCol = seg.firstRowDayIndex;
  4873. seg.rightCol = seg.lastRowDayIndex;
  4874. }
  4875. }
  4876. return segs;
  4877. },
  4878. /* Hit System
  4879. ------------------------------------------------------------------------------------------------------------------*/
  4880. prepareHits: function() {
  4881. this.colCoordCache.build();
  4882. this.rowCoordCache.build();
  4883. this.rowCoordCache.bottoms[this.rowCnt - 1] += this.bottomCoordPadding; // hack
  4884. },
  4885. releaseHits: function() {
  4886. this.colCoordCache.clear();
  4887. this.rowCoordCache.clear();
  4888. },
  4889. queryHit: function(leftOffset, topOffset) {
  4890. if (this.colCoordCache.isLeftInBounds(leftOffset) && this.rowCoordCache.isTopInBounds(topOffset)) {
  4891. var col = this.colCoordCache.getHorizontalIndex(leftOffset);
  4892. var row = this.rowCoordCache.getVerticalIndex(topOffset);
  4893. if (row != null && col != null) {
  4894. return this.getCellHit(row, col);
  4895. }
  4896. }
  4897. },
  4898. getHitSpan: function(hit) {
  4899. return this.getCellRange(hit.row, hit.col);
  4900. },
  4901. getHitEl: function(hit) {
  4902. return this.getCellEl(hit.row, hit.col);
  4903. },
  4904. /* Cell System
  4905. ------------------------------------------------------------------------------------------------------------------*/
  4906. // FYI: the first column is the leftmost column, regardless of date
  4907. getCellHit: function(row, col) {
  4908. return {
  4909. row: row,
  4910. col: col,
  4911. component: this, // needed unfortunately :(
  4912. left: this.colCoordCache.getLeftOffset(col),
  4913. right: this.colCoordCache.getRightOffset(col),
  4914. top: this.rowCoordCache.getTopOffset(row),
  4915. bottom: this.rowCoordCache.getBottomOffset(row)
  4916. };
  4917. },
  4918. getCellEl: function(row, col) {
  4919. return this.cellEls.eq(row * this.colCnt + col);
  4920. },
  4921. /* Event Drag Visualization
  4922. ------------------------------------------------------------------------------------------------------------------*/
  4923. // TODO: move to DayGrid.event, similar to what we did with Grid's drag methods
  4924. // Renders a visual indication of an event or external element being dragged.
  4925. // `eventLocation` has zoned start and end (optional)
  4926. renderDrag: function(eventLocation, seg) {
  4927. // always render a highlight underneath
  4928. this.renderHighlight(this.eventToSpan(eventLocation));
  4929. // if a segment from the same calendar but another component is being dragged, render a helper event
  4930. if (seg && seg.component !== this) {
  4931. return this.renderEventLocationHelper(eventLocation, seg); // returns mock event elements
  4932. }
  4933. },
  4934. // Unrenders any visual indication of a hovering event
  4935. unrenderDrag: function() {
  4936. this.unrenderHighlight();
  4937. this.unrenderHelper();
  4938. },
  4939. /* Event Resize Visualization
  4940. ------------------------------------------------------------------------------------------------------------------*/
  4941. // Renders a visual indication of an event being resized
  4942. renderEventResize: function(eventLocation, seg) {
  4943. this.renderHighlight(this.eventToSpan(eventLocation));
  4944. return this.renderEventLocationHelper(eventLocation, seg); // returns mock event elements
  4945. },
  4946. // Unrenders a visual indication of an event being resized
  4947. unrenderEventResize: function() {
  4948. this.unrenderHighlight();
  4949. this.unrenderHelper();
  4950. },
  4951. /* Event Helper
  4952. ------------------------------------------------------------------------------------------------------------------*/
  4953. // Renders a mock "helper" event. `sourceSeg` is the associated internal segment object. It can be null.
  4954. renderHelper: function(event, sourceSeg) {
  4955. var helperNodes = [];
  4956. var segs = this.eventToSegs(event);
  4957. var rowStructs;
  4958. segs = this.renderFgSegEls(segs); // assigns each seg's el and returns a subset of segs that were rendered
  4959. rowStructs = this.renderSegRows(segs);
  4960. // inject each new event skeleton into each associated row
  4961. this.rowEls.each(function(row, rowNode) {
  4962. var rowEl = $(rowNode); // the .fc-row
  4963. var skeletonEl = $('<div class="fc-helper-skeleton"><table/></div>'); // will be absolutely positioned
  4964. var skeletonTop;
  4965. // If there is an original segment, match the top position. Otherwise, put it at the row's top level
  4966. if (sourceSeg && sourceSeg.row === row) {
  4967. skeletonTop = sourceSeg.el.position().top;
  4968. }
  4969. else {
  4970. skeletonTop = rowEl.find('.fc-content-skeleton tbody').position().top;
  4971. }
  4972. skeletonEl.css('top', skeletonTop)
  4973. .find('table')
  4974. .append(rowStructs[row].tbodyEl);
  4975. rowEl.append(skeletonEl);
  4976. helperNodes.push(skeletonEl[0]);
  4977. });
  4978. return ( // must return the elements rendered
  4979. this.helperEls = $(helperNodes) // array -> jQuery set
  4980. );
  4981. },
  4982. // Unrenders any visual indication of a mock helper event
  4983. unrenderHelper: function() {
  4984. if (this.helperEls) {
  4985. this.helperEls.remove();
  4986. this.helperEls = null;
  4987. }
  4988. },
  4989. /* Fill System (highlight, background events, business hours)
  4990. ------------------------------------------------------------------------------------------------------------------*/
  4991. fillSegTag: 'td', // override the default tag name
  4992. // Renders a set of rectangles over the given segments of days.
  4993. // Only returns segments that successfully rendered.
  4994. renderFill: function(type, segs, className) {
  4995. var nodes = [];
  4996. var i, seg;
  4997. var skeletonEl;
  4998. segs = this.renderFillSegEls(type, segs); // assignes `.el` to each seg. returns successfully rendered segs
  4999. for (i = 0; i < segs.length; i++) {
  5000. seg = segs[i];
  5001. skeletonEl = this.renderFillRow(type, seg, className);
  5002. this.rowEls.eq(seg.row).append(skeletonEl);
  5003. nodes.push(skeletonEl[0]);
  5004. }
  5005. this.elsByFill[type] = $(nodes);
  5006. return segs;
  5007. },
  5008. // Generates the HTML needed for one row of a fill. Requires the seg's el to be rendered.
  5009. renderFillRow: function(type, seg, className) {
  5010. var colCnt = this.colCnt;
  5011. var startCol = seg.leftCol;
  5012. var endCol = seg.rightCol + 1;
  5013. var skeletonEl;
  5014. var trEl;
  5015. className = className || type.toLowerCase();
  5016. skeletonEl = $(
  5017. '<div class="fc-' + className + '-skeleton">' +
  5018. '<table><tr/></table>' +
  5019. '</div>'
  5020. );
  5021. trEl = skeletonEl.find('tr');
  5022. if (startCol > 0) {
  5023. trEl.append('<td colspan="' + startCol + '"/>');
  5024. }
  5025. trEl.append(
  5026. seg.el.attr('colspan', endCol - startCol)
  5027. );
  5028. if (endCol < colCnt) {
  5029. trEl.append('<td colspan="' + (colCnt - endCol) + '"/>');
  5030. }
  5031. this.bookendCells(trEl);
  5032. return skeletonEl;
  5033. }
  5034. });
  5035. ;;
  5036. /* Event-rendering methods for the DayGrid class
  5037. ----------------------------------------------------------------------------------------------------------------------*/
  5038. DayGrid.mixin({
  5039. rowStructs: null, // an array of objects, each holding information about a row's foreground event-rendering
  5040. // Unrenders all events currently rendered on the grid
  5041. unrenderEvents: function() {
  5042. this.removeSegPopover(); // removes the "more.." events popover
  5043. Grid.prototype.unrenderEvents.apply(this, arguments); // calls the super-method
  5044. },
  5045. // Retrieves all rendered segment objects currently rendered on the grid
  5046. getEventSegs: function() {
  5047. return Grid.prototype.getEventSegs.call(this) // get the segments from the super-method
  5048. .concat(this.popoverSegs || []); // append the segments from the "more..." popover
  5049. },
  5050. // Renders the given background event segments onto the grid
  5051. renderBgSegs: function(segs) {
  5052. // don't render timed background events
  5053. var allDaySegs = $.grep(segs, function(seg) {
  5054. return seg.event.allDay;
  5055. });
  5056. return Grid.prototype.renderBgSegs.call(this, allDaySegs); // call the super-method
  5057. },
  5058. // Renders the given foreground event segments onto the grid
  5059. renderFgSegs: function(segs) {
  5060. var rowStructs;
  5061. // render an `.el` on each seg
  5062. // returns a subset of the segs. segs that were actually rendered
  5063. segs = this.renderFgSegEls(segs);
  5064. rowStructs = this.rowStructs = this.renderSegRows(segs);
  5065. // append to each row's content skeleton
  5066. this.rowEls.each(function(i, rowNode) {
  5067. $(rowNode).find('.fc-content-skeleton > table').append(
  5068. rowStructs[i].tbodyEl
  5069. );
  5070. });
  5071. return segs; // return only the segs that were actually rendered
  5072. },
  5073. // Unrenders all currently rendered foreground event segments
  5074. unrenderFgSegs: function() {
  5075. var rowStructs = this.rowStructs || [];
  5076. var rowStruct;
  5077. while ((rowStruct = rowStructs.pop())) {
  5078. rowStruct.tbodyEl.remove();
  5079. }
  5080. this.rowStructs = null;
  5081. },
  5082. // Uses the given events array to generate <tbody> elements that should be appended to each row's content skeleton.
  5083. // Returns an array of rowStruct objects (see the bottom of `renderSegRow`).
  5084. // PRECONDITION: each segment shoud already have a rendered and assigned `.el`
  5085. renderSegRows: function(segs) {
  5086. var rowStructs = [];
  5087. var segRows;
  5088. var row;
  5089. segRows = this.groupSegRows(segs); // group into nested arrays
  5090. // iterate each row of segment groupings
  5091. for (row = 0; row < segRows.length; row++) {
  5092. rowStructs.push(
  5093. this.renderSegRow(row, segRows[row])
  5094. );
  5095. }
  5096. return rowStructs;
  5097. },
  5098. // Builds the HTML to be used for the default element for an individual segment
  5099. fgSegHtml: function(seg, disableResizing) {
  5100. var view = this.view;
  5101. var event = seg.event;
  5102. var isDraggable = view.isEventDraggable(event);
  5103. var isResizableFromStart = !disableResizing && event.allDay &&
  5104. seg.isStart && view.isEventResizableFromStart(event);
  5105. var isResizableFromEnd = !disableResizing && event.allDay &&
  5106. seg.isEnd && view.isEventResizableFromEnd(event);
  5107. var classes = this.getSegClasses(seg, isDraggable, isResizableFromStart || isResizableFromEnd);
  5108. var skinCss = cssToStr(this.getSegSkinCss(seg));
  5109. var timeHtml = '';
  5110. var timeText;
  5111. var titleHtml;
  5112. classes.unshift('fc-day-grid-event', 'fc-h-event');
  5113. // Only display a timed events time if it is the starting segment
  5114. if (seg.isStart) {
  5115. timeText = this.getEventTimeText(event);
  5116. if (timeText) {
  5117. timeHtml = '<span class="fc-time">' + htmlEscape(timeText) + '</span>';
  5118. }
  5119. }
  5120. titleHtml =
  5121. '<span class="fc-title">' +
  5122. (htmlEscape(event.title || '') || '&nbsp;') + // we always want one line of height
  5123. '</span>';
  5124. return '<a class="' + classes.join(' ') + '"' +
  5125. (event.url ?
  5126. ' href="' + htmlEscape(event.url) + '"' :
  5127. ''
  5128. ) +
  5129. (skinCss ?
  5130. ' style="' + skinCss + '"' :
  5131. ''
  5132. ) +
  5133. '>' +
  5134. '<div class="fc-content">' +
  5135. (this.isRTL ?
  5136. titleHtml + ' ' + timeHtml : // put a natural space in between
  5137. timeHtml + ' ' + titleHtml //
  5138. ) +
  5139. '</div>' +
  5140. (isResizableFromStart ?
  5141. '<div class="fc-resizer fc-start-resizer" />' :
  5142. ''
  5143. ) +
  5144. (isResizableFromEnd ?
  5145. '<div class="fc-resizer fc-end-resizer" />' :
  5146. ''
  5147. ) +
  5148. '</a>';
  5149. },
  5150. // Given a row # and an array of segments all in the same row, render a <tbody> element, a skeleton that contains
  5151. // the segments. Returns object with a bunch of internal data about how the render was calculated.
  5152. // NOTE: modifies rowSegs
  5153. renderSegRow: function(row, rowSegs) {
  5154. var colCnt = this.colCnt;
  5155. var segLevels = this.buildSegLevels(rowSegs); // group into sub-arrays of levels
  5156. var levelCnt = Math.max(1, segLevels.length); // ensure at least one level
  5157. var tbody = $('<tbody/>');
  5158. var segMatrix = []; // lookup for which segments are rendered into which level+col cells
  5159. var cellMatrix = []; // lookup for all <td> elements of the level+col matrix
  5160. var loneCellMatrix = []; // lookup for <td> elements that only take up a single column
  5161. var i, levelSegs;
  5162. var col;
  5163. var tr;
  5164. var j, seg;
  5165. var td;
  5166. // populates empty cells from the current column (`col`) to `endCol`
  5167. function emptyCellsUntil(endCol) {
  5168. while (col < endCol) {
  5169. // try to grab a cell from the level above and extend its rowspan. otherwise, create a fresh cell
  5170. td = (loneCellMatrix[i - 1] || [])[col];
  5171. if (td) {
  5172. td.attr(
  5173. 'rowspan',
  5174. parseInt(td.attr('rowspan') || 1, 10) + 1
  5175. );
  5176. }
  5177. else {
  5178. td = $('<td/>');
  5179. tr.append(td);
  5180. }
  5181. cellMatrix[i][col] = td;
  5182. loneCellMatrix[i][col] = td;
  5183. col++;
  5184. }
  5185. }
  5186. for (i = 0; i < levelCnt; i++) { // iterate through all levels
  5187. levelSegs = segLevels[i];
  5188. col = 0;
  5189. tr = $('<tr/>');
  5190. segMatrix.push([]);
  5191. cellMatrix.push([]);
  5192. loneCellMatrix.push([]);
  5193. // levelCnt might be 1 even though there are no actual levels. protect against this.
  5194. // this single empty row is useful for styling.
  5195. if (levelSegs) {
  5196. for (j = 0; j < levelSegs.length; j++) { // iterate through segments in level
  5197. seg = levelSegs[j];
  5198. emptyCellsUntil(seg.leftCol);
  5199. // create a container that occupies or more columns. append the event element.
  5200. td = $('<td class="fc-event-container"/>').append(seg.el);
  5201. if (seg.leftCol != seg.rightCol) {
  5202. td.attr('colspan', seg.rightCol - seg.leftCol + 1);
  5203. }
  5204. else { // a single-column segment
  5205. loneCellMatrix[i][col] = td;
  5206. }
  5207. while (col <= seg.rightCol) {
  5208. cellMatrix[i][col] = td;
  5209. segMatrix[i][col] = seg;
  5210. col++;
  5211. }
  5212. tr.append(td);
  5213. }
  5214. }
  5215. emptyCellsUntil(colCnt); // finish off the row
  5216. this.bookendCells(tr);
  5217. tbody.append(tr);
  5218. }
  5219. return { // a "rowStruct"
  5220. row: row, // the row number
  5221. tbodyEl: tbody,
  5222. cellMatrix: cellMatrix,
  5223. segMatrix: segMatrix,
  5224. segLevels: segLevels,
  5225. segs: rowSegs
  5226. };
  5227. },
  5228. // Stacks a flat array of segments, which are all assumed to be in the same row, into subarrays of vertical levels.
  5229. // NOTE: modifies segs
  5230. buildSegLevels: function(segs) {
  5231. var levels = [];
  5232. var i, seg;
  5233. var j;
  5234. // Give preference to elements with certain criteria, so they have
  5235. // a chance to be closer to the top.
  5236. this.sortEventSegs(segs);
  5237. for (i = 0; i < segs.length; i++) {
  5238. seg = segs[i];
  5239. // loop through levels, starting with the topmost, until the segment doesn't collide with other segments
  5240. for (j = 0; j < levels.length; j++) {
  5241. if (!isDaySegCollision(seg, levels[j])) {
  5242. break;
  5243. }
  5244. }
  5245. // `j` now holds the desired subrow index
  5246. seg.level = j;
  5247. // create new level array if needed and append segment
  5248. (levels[j] || (levels[j] = [])).push(seg);
  5249. }
  5250. // order segments left-to-right. very important if calendar is RTL
  5251. for (j = 0; j < levels.length; j++) {
  5252. levels[j].sort(compareDaySegCols);
  5253. }
  5254. return levels;
  5255. },
  5256. // Given a flat array of segments, return an array of sub-arrays, grouped by each segment's row
  5257. groupSegRows: function(segs) {
  5258. var segRows = [];
  5259. var i;
  5260. for (i = 0; i < this.rowCnt; i++) {
  5261. segRows.push([]);
  5262. }
  5263. for (i = 0; i < segs.length; i++) {
  5264. segRows[segs[i].row].push(segs[i]);
  5265. }
  5266. return segRows;
  5267. }
  5268. });
  5269. // Computes whether two segments' columns collide. They are assumed to be in the same row.
  5270. function isDaySegCollision(seg, otherSegs) {
  5271. var i, otherSeg;
  5272. for (i = 0; i < otherSegs.length; i++) {
  5273. otherSeg = otherSegs[i];
  5274. if (
  5275. otherSeg.leftCol <= seg.rightCol &&
  5276. otherSeg.rightCol >= seg.leftCol
  5277. ) {
  5278. return true;
  5279. }
  5280. }
  5281. return false;
  5282. }
  5283. // A cmp function for determining the leftmost event
  5284. function compareDaySegCols(a, b) {
  5285. return a.leftCol - b.leftCol;
  5286. }
  5287. ;;
  5288. /* Methods relate to limiting the number events for a given day on a DayGrid
  5289. ----------------------------------------------------------------------------------------------------------------------*/
  5290. // NOTE: all the segs being passed around in here are foreground segs
  5291. DayGrid.mixin({
  5292. segPopover: null, // the Popover that holds events that can't fit in a cell. null when not visible
  5293. popoverSegs: null, // an array of segment objects that the segPopover holds. null when not visible
  5294. removeSegPopover: function() {
  5295. if (this.segPopover) {
  5296. this.segPopover.hide(); // in handler, will call segPopover's removeElement
  5297. }
  5298. },
  5299. // Limits the number of "levels" (vertically stacking layers of events) for each row of the grid.
  5300. // `levelLimit` can be false (don't limit), a number, or true (should be computed).
  5301. limitRows: function(levelLimit) {
  5302. var rowStructs = this.rowStructs || [];
  5303. var row; // row #
  5304. var rowLevelLimit;
  5305. for (row = 0; row < rowStructs.length; row++) {
  5306. this.unlimitRow(row);
  5307. if (!levelLimit) {
  5308. rowLevelLimit = false;
  5309. }
  5310. else if (typeof levelLimit === 'number') {
  5311. rowLevelLimit = levelLimit;
  5312. }
  5313. else {
  5314. rowLevelLimit = this.computeRowLevelLimit(row);
  5315. }
  5316. if (rowLevelLimit !== false) {
  5317. this.limitRow(row, rowLevelLimit);
  5318. }
  5319. }
  5320. },
  5321. // Computes the number of levels a row will accomodate without going outside its bounds.
  5322. // Assumes the row is "rigid" (maintains a constant height regardless of what is inside).
  5323. // `row` is the row number.
  5324. computeRowLevelLimit: function(row) {
  5325. var rowEl = this.rowEls.eq(row); // the containing "fake" row div
  5326. var rowHeight = rowEl.height(); // TODO: cache somehow?
  5327. var trEls = this.rowStructs[row].tbodyEl.children();
  5328. var i, trEl;
  5329. var trHeight;
  5330. function iterInnerHeights(i, childNode) {
  5331. trHeight = Math.max(trHeight, $(childNode).outerHeight());
  5332. }
  5333. // Reveal one level <tr> at a time and stop when we find one out of bounds
  5334. for (i = 0; i < trEls.length; i++) {
  5335. trEl = trEls.eq(i).removeClass('fc-limited'); // reset to original state (reveal)
  5336. // with rowspans>1 and IE8, trEl.outerHeight() would return the height of the largest cell,
  5337. // so instead, find the tallest inner content element.
  5338. trHeight = 0;
  5339. trEl.find('> td > :first-child').each(iterInnerHeights);
  5340. if (trEl.position().top + trHeight > rowHeight) {
  5341. return i;
  5342. }
  5343. }
  5344. return false; // should not limit at all
  5345. },
  5346. // Limits the given grid row to the maximum number of levels and injects "more" links if necessary.
  5347. // `row` is the row number.
  5348. // `levelLimit` is a number for the maximum (inclusive) number of levels allowed.
  5349. limitRow: function(row, levelLimit) {
  5350. var _this = this;
  5351. var rowStruct = this.rowStructs[row];
  5352. var moreNodes = []; // array of "more" <a> links and <td> DOM nodes
  5353. var col = 0; // col #, left-to-right (not chronologically)
  5354. var levelSegs; // array of segment objects in the last allowable level, ordered left-to-right
  5355. var cellMatrix; // a matrix (by level, then column) of all <td> jQuery elements in the row
  5356. var limitedNodes; // array of temporarily hidden level <tr> and segment <td> DOM nodes
  5357. var i, seg;
  5358. var segsBelow; // array of segment objects below `seg` in the current `col`
  5359. var totalSegsBelow; // total number of segments below `seg` in any of the columns `seg` occupies
  5360. var colSegsBelow; // array of segment arrays, below seg, one for each column (offset from segs's first column)
  5361. var td, rowspan;
  5362. var segMoreNodes; // array of "more" <td> cells that will stand-in for the current seg's cell
  5363. var j;
  5364. var moreTd, moreWrap, moreLink;
  5365. // Iterates through empty level cells and places "more" links inside if need be
  5366. function emptyCellsUntil(endCol) { // goes from current `col` to `endCol`
  5367. while (col < endCol) {
  5368. segsBelow = _this.getCellSegs(row, col, levelLimit);
  5369. if (segsBelow.length) {
  5370. td = cellMatrix[levelLimit - 1][col];
  5371. moreLink = _this.renderMoreLink(row, col, segsBelow);
  5372. moreWrap = $('<div/>').append(moreLink);
  5373. td.append(moreWrap);
  5374. moreNodes.push(moreWrap[0]);
  5375. }
  5376. col++;
  5377. }
  5378. }
  5379. if (levelLimit && levelLimit < rowStruct.segLevels.length) { // is it actually over the limit?
  5380. levelSegs = rowStruct.segLevels[levelLimit - 1];
  5381. cellMatrix = rowStruct.cellMatrix;
  5382. limitedNodes = rowStruct.tbodyEl.children().slice(levelLimit) // get level <tr> elements past the limit
  5383. .addClass('fc-limited').get(); // hide elements and get a simple DOM-nodes array
  5384. // iterate though segments in the last allowable level
  5385. for (i = 0; i < levelSegs.length; i++) {
  5386. seg = levelSegs[i];
  5387. emptyCellsUntil(seg.leftCol); // process empty cells before the segment
  5388. // determine *all* segments below `seg` that occupy the same columns
  5389. colSegsBelow = [];
  5390. totalSegsBelow = 0;
  5391. while (col <= seg.rightCol) {
  5392. segsBelow = this.getCellSegs(row, col, levelLimit);
  5393. colSegsBelow.push(segsBelow);
  5394. totalSegsBelow += segsBelow.length;
  5395. col++;
  5396. }
  5397. if (totalSegsBelow) { // do we need to replace this segment with one or many "more" links?
  5398. td = cellMatrix[levelLimit - 1][seg.leftCol]; // the segment's parent cell
  5399. rowspan = td.attr('rowspan') || 1;
  5400. segMoreNodes = [];
  5401. // make a replacement <td> for each column the segment occupies. will be one for each colspan
  5402. for (j = 0; j < colSegsBelow.length; j++) {
  5403. moreTd = $('<td class="fc-more-cell"/>').attr('rowspan', rowspan);
  5404. segsBelow = colSegsBelow[j];
  5405. moreLink = this.renderMoreLink(
  5406. row,
  5407. seg.leftCol + j,
  5408. [ seg ].concat(segsBelow) // count seg as hidden too
  5409. );
  5410. moreWrap = $('<div/>').append(moreLink);
  5411. moreTd.append(moreWrap);
  5412. segMoreNodes.push(moreTd[0]);
  5413. moreNodes.push(moreTd[0]);
  5414. }
  5415. td.addClass('fc-limited').after($(segMoreNodes)); // hide original <td> and inject replacements
  5416. limitedNodes.push(td[0]);
  5417. }
  5418. }
  5419. emptyCellsUntil(this.colCnt); // finish off the level
  5420. rowStruct.moreEls = $(moreNodes); // for easy undoing later
  5421. rowStruct.limitedEls = $(limitedNodes); // for easy undoing later
  5422. }
  5423. },
  5424. // Reveals all levels and removes all "more"-related elements for a grid's row.
  5425. // `row` is a row number.
  5426. unlimitRow: function(row) {
  5427. var rowStruct = this.rowStructs[row];
  5428. if (rowStruct.moreEls) {
  5429. rowStruct.moreEls.remove();
  5430. rowStruct.moreEls = null;
  5431. }
  5432. if (rowStruct.limitedEls) {
  5433. rowStruct.limitedEls.removeClass('fc-limited');
  5434. rowStruct.limitedEls = null;
  5435. }
  5436. },
  5437. // Renders an <a> element that represents hidden event element for a cell.
  5438. // Responsible for attaching click handler as well.
  5439. renderMoreLink: function(row, col, hiddenSegs) {
  5440. var _this = this;
  5441. var view = this.view;
  5442. return $('<a class="fc-more"/>')
  5443. .text(
  5444. this.getMoreLinkText(hiddenSegs.length)
  5445. )
  5446. .on('click', function(ev) {
  5447. var clickOption = view.opt('eventLimitClick');
  5448. var date = _this.getCellDate(row, col);
  5449. var moreEl = $(this);
  5450. var dayEl = _this.getCellEl(row, col);
  5451. var allSegs = _this.getCellSegs(row, col);
  5452. // rescope the segments to be within the cell's date
  5453. var reslicedAllSegs = _this.resliceDaySegs(allSegs, date);
  5454. var reslicedHiddenSegs = _this.resliceDaySegs(hiddenSegs, date);
  5455. if (typeof clickOption === 'function') {
  5456. // the returned value can be an atomic option
  5457. clickOption = view.publiclyTrigger('eventLimitClick', null, {
  5458. date: date,
  5459. dayEl: dayEl,
  5460. moreEl: moreEl,
  5461. segs: reslicedAllSegs,
  5462. hiddenSegs: reslicedHiddenSegs
  5463. }, ev);
  5464. }
  5465. if (clickOption === 'popover') {
  5466. _this.showSegPopover(row, col, moreEl, reslicedAllSegs);
  5467. }
  5468. else if (typeof clickOption === 'string') { // a view name
  5469. view.calendar.zoomTo(date, clickOption);
  5470. }
  5471. });
  5472. },
  5473. // Reveals the popover that displays all events within a cell
  5474. showSegPopover: function(row, col, moreLink, segs) {
  5475. var _this = this;
  5476. var view = this.view;
  5477. var moreWrap = moreLink.parent(); // the <div> wrapper around the <a>
  5478. var topEl; // the element we want to match the top coordinate of
  5479. var options;
  5480. if (this.rowCnt == 1) {
  5481. topEl = view.el; // will cause the popover to cover any sort of header
  5482. }
  5483. else {
  5484. topEl = this.rowEls.eq(row); // will align with top of row
  5485. }
  5486. options = {
  5487. className: 'fc-more-popover',
  5488. content: this.renderSegPopoverContent(row, col, segs),
  5489. parentEl: this.view.el, // attach to root of view. guarantees outside of scrollbars.
  5490. top: topEl.offset().top,
  5491. autoHide: true, // when the user clicks elsewhere, hide the popover
  5492. viewportConstrain: view.opt('popoverViewportConstrain'),
  5493. hide: function() {
  5494. // kill everything when the popover is hidden
  5495. // notify events to be removed
  5496. if (_this.popoverSegs) {
  5497. var seg;
  5498. for (var i = 0; i < _this.popoverSegs.length; ++i) {
  5499. seg = _this.popoverSegs[i];
  5500. view.publiclyTrigger('eventDestroy', seg.event, seg.event, seg.el);
  5501. }
  5502. }
  5503. _this.segPopover.removeElement();
  5504. _this.segPopover = null;
  5505. _this.popoverSegs = null;
  5506. }
  5507. };
  5508. // Determine horizontal coordinate.
  5509. // We use the moreWrap instead of the <td> to avoid border confusion.
  5510. if (this.isRTL) {
  5511. options.right = moreWrap.offset().left + moreWrap.outerWidth() + 1; // +1 to be over cell border
  5512. }
  5513. else {
  5514. options.left = moreWrap.offset().left - 1; // -1 to be over cell border
  5515. }
  5516. this.segPopover = new Popover(options);
  5517. this.segPopover.show();
  5518. // the popover doesn't live within the grid's container element, and thus won't get the event
  5519. // delegated-handlers for free. attach event-related handlers to the popover.
  5520. this.bindSegHandlersToEl(this.segPopover.el);
  5521. },
  5522. // Builds the inner DOM contents of the segment popover
  5523. renderSegPopoverContent: function(row, col, segs) {
  5524. var view = this.view;
  5525. var isTheme = view.opt('theme');
  5526. var title = this.getCellDate(row, col).format(view.opt('dayPopoverFormat'));
  5527. var content = $(
  5528. '<div class="fc-header ' + view.widgetHeaderClass + '">' +
  5529. '<span class="fc-close ' +
  5530. (isTheme ? 'ui-icon ui-icon-closethick' : 'fc-icon fc-icon-x') +
  5531. '"></span>' +
  5532. '<span class="fc-title">' +
  5533. htmlEscape(title) +
  5534. '</span>' +
  5535. '<div class="fc-clear"/>' +
  5536. '</div>' +
  5537. '<div class="fc-body ' + view.widgetContentClass + '">' +
  5538. '<div class="fc-event-container"></div>' +
  5539. '</div>'
  5540. );
  5541. var segContainer = content.find('.fc-event-container');
  5542. var i;
  5543. // render each seg's `el` and only return the visible segs
  5544. segs = this.renderFgSegEls(segs, true); // disableResizing=true
  5545. this.popoverSegs = segs;
  5546. for (i = 0; i < segs.length; i++) {
  5547. // because segments in the popover are not part of a grid coordinate system, provide a hint to any
  5548. // grids that want to do drag-n-drop about which cell it came from
  5549. this.hitsNeeded();
  5550. segs[i].hit = this.getCellHit(row, col);
  5551. this.hitsNotNeeded();
  5552. segContainer.append(segs[i].el);
  5553. }
  5554. return content;
  5555. },
  5556. // Given the events within an array of segment objects, reslice them to be in a single day
  5557. resliceDaySegs: function(segs, dayDate) {
  5558. // build an array of the original events
  5559. var events = $.map(segs, function(seg) {
  5560. return seg.event;
  5561. });
  5562. var dayStart = dayDate.clone();
  5563. var dayEnd = dayStart.clone().add(1, 'days');
  5564. var dayRange = { start: dayStart, end: dayEnd };
  5565. // slice the events with a custom slicing function
  5566. segs = this.eventsToSegs(
  5567. events,
  5568. function(range) {
  5569. var seg = intersectRanges(range, dayRange); // undefind if no intersection
  5570. return seg ? [ seg ] : []; // must return an array of segments
  5571. }
  5572. );
  5573. // force an order because eventsToSegs doesn't guarantee one
  5574. this.sortEventSegs(segs);
  5575. return segs;
  5576. },
  5577. // Generates the text that should be inside a "more" link, given the number of events it represents
  5578. getMoreLinkText: function(num) {
  5579. var opt = this.view.opt('eventLimitText');
  5580. if (typeof opt === 'function') {
  5581. return opt(num);
  5582. }
  5583. else {
  5584. return '+' + num + ' ' + opt;
  5585. }
  5586. },
  5587. // Returns segments within a given cell.
  5588. // If `startLevel` is specified, returns only events including and below that level. Otherwise returns all segs.
  5589. getCellSegs: function(row, col, startLevel) {
  5590. var segMatrix = this.rowStructs[row].segMatrix;
  5591. var level = startLevel || 0;
  5592. var segs = [];
  5593. var seg;
  5594. while (level < segMatrix.length) {
  5595. seg = segMatrix[level][col];
  5596. if (seg) {
  5597. segs.push(seg);
  5598. }
  5599. level++;
  5600. }
  5601. return segs;
  5602. }
  5603. });
  5604. ;;
  5605. /* A component that renders one or more columns of vertical time slots
  5606. ----------------------------------------------------------------------------------------------------------------------*/
  5607. // We mixin DayTable, even though there is only a single row of days
  5608. var TimeGrid = FC.TimeGrid = Grid.extend(DayTableMixin, {
  5609. slotDuration: null, // duration of a "slot", a distinct time segment on given day, visualized by lines
  5610. snapDuration: null, // granularity of time for dragging and selecting
  5611. snapsPerSlot: null,
  5612. minTime: null, // Duration object that denotes the first visible time of any given day
  5613. maxTime: null, // Duration object that denotes the exclusive visible end time of any given day
  5614. labelFormat: null, // formatting string for times running along vertical axis
  5615. labelInterval: null, // duration of how often a label should be displayed for a slot
  5616. colEls: null, // cells elements in the day-row background
  5617. slatContainerEl: null, // div that wraps all the slat rows
  5618. slatEls: null, // elements running horizontally across all columns
  5619. nowIndicatorEls: null,
  5620. colCoordCache: null,
  5621. slatCoordCache: null,
  5622. constructor: function() {
  5623. Grid.apply(this, arguments); // call the super-constructor
  5624. this.processOptions();
  5625. },
  5626. // Renders the time grid into `this.el`, which should already be assigned.
  5627. // Relies on the view's colCnt. In the future, this component should probably be self-sufficient.
  5628. renderDates: function() {
  5629. this.el.html(this.renderHtml());
  5630. this.colEls = this.el.find('.fc-day');
  5631. this.slatContainerEl = this.el.find('.fc-slats');
  5632. this.slatEls = this.slatContainerEl.find('tr');
  5633. this.colCoordCache = new CoordCache({
  5634. els: this.colEls,
  5635. isHorizontal: true
  5636. });
  5637. this.slatCoordCache = new CoordCache({
  5638. els: this.slatEls,
  5639. isVertical: true
  5640. });
  5641. this.renderContentSkeleton();
  5642. },
  5643. // Renders the basic HTML skeleton for the grid
  5644. renderHtml: function() {
  5645. return '' +
  5646. '<div class="fc-bg">' +
  5647. '<table>' +
  5648. this.renderBgTrHtml(0) + // row=0
  5649. '</table>' +
  5650. '</div>' +
  5651. '<div class="fc-slats">' +
  5652. '<table>' +
  5653. this.renderSlatRowHtml() +
  5654. '</table>' +
  5655. '</div>';
  5656. },
  5657. // Generates the HTML for the horizontal "slats" that run width-wise. Has a time axis on a side. Depends on RTL.
  5658. renderSlatRowHtml: function() {
  5659. var view = this.view;
  5660. var isRTL = this.isRTL;
  5661. var html = '';
  5662. var slotTime = moment.duration(+this.minTime); // wish there was .clone() for durations
  5663. var slotDate; // will be on the view's first day, but we only care about its time
  5664. var isLabeled;
  5665. var axisHtml;
  5666. // Calculate the time for each slot
  5667. while (slotTime < this.maxTime) {
  5668. slotDate = this.start.clone().time(slotTime);
  5669. isLabeled = isInt(divideDurationByDuration(slotTime, this.labelInterval));
  5670. axisHtml =
  5671. '<td class="fc-axis fc-time ' + view.widgetContentClass + '" ' + view.axisStyleAttr() + '>' +
  5672. (isLabeled ?
  5673. '<span>' + // for matchCellWidths
  5674. htmlEscape(slotDate.format(this.labelFormat)) +
  5675. '</span>' :
  5676. ''
  5677. ) +
  5678. '</td>';
  5679. html +=
  5680. '<tr data-time="' + slotDate.format('HH:mm:ss') + '"' +
  5681. (isLabeled ? '' : ' class="fc-minor"') +
  5682. '>' +
  5683. (!isRTL ? axisHtml : '') +
  5684. '<td class="' + view.widgetContentClass + '"/>' +
  5685. (isRTL ? axisHtml : '') +
  5686. "</tr>";
  5687. slotTime.add(this.slotDuration);
  5688. }
  5689. return html;
  5690. },
  5691. /* Options
  5692. ------------------------------------------------------------------------------------------------------------------*/
  5693. // Parses various options into properties of this object
  5694. processOptions: function() {
  5695. var view = this.view;
  5696. var slotDuration = view.opt('slotDuration');
  5697. var snapDuration = view.opt('snapDuration');
  5698. var input;
  5699. slotDuration = moment.duration(slotDuration);
  5700. snapDuration = snapDuration ? moment.duration(snapDuration) : slotDuration;
  5701. this.slotDuration = slotDuration;
  5702. this.snapDuration = snapDuration;
  5703. this.snapsPerSlot = slotDuration / snapDuration; // TODO: ensure an integer multiple?
  5704. this.minResizeDuration = snapDuration; // hack
  5705. this.minTime = moment.duration(view.opt('minTime'));
  5706. this.maxTime = moment.duration(view.opt('maxTime'));
  5707. // might be an array value (for TimelineView).
  5708. // if so, getting the most granular entry (the last one probably).
  5709. input = view.opt('slotLabelFormat');
  5710. if ($.isArray(input)) {
  5711. input = input[input.length - 1];
  5712. }
  5713. this.labelFormat =
  5714. input ||
  5715. view.opt('smallTimeFormat'); // the computed default
  5716. input = view.opt('slotLabelInterval');
  5717. this.labelInterval = input ?
  5718. moment.duration(input) :
  5719. this.computeLabelInterval(slotDuration);
  5720. },
  5721. // Computes an automatic value for slotLabelInterval
  5722. computeLabelInterval: function(slotDuration) {
  5723. var i;
  5724. var labelInterval;
  5725. var slotsPerLabel;
  5726. // find the smallest stock label interval that results in more than one slots-per-label
  5727. for (i = AGENDA_STOCK_SUB_DURATIONS.length - 1; i >= 0; i--) {
  5728. labelInterval = moment.duration(AGENDA_STOCK_SUB_DURATIONS[i]);
  5729. slotsPerLabel = divideDurationByDuration(labelInterval, slotDuration);
  5730. if (isInt(slotsPerLabel) && slotsPerLabel > 1) {
  5731. return labelInterval;
  5732. }
  5733. }
  5734. return moment.duration(slotDuration); // fall back. clone
  5735. },
  5736. // Computes a default event time formatting string if `timeFormat` is not explicitly defined
  5737. computeEventTimeFormat: function() {
  5738. return this.view.opt('noMeridiemTimeFormat'); // like "6:30" (no AM/PM)
  5739. },
  5740. // Computes a default `displayEventEnd` value if one is not expliclty defined
  5741. computeDisplayEventEnd: function() {
  5742. return true;
  5743. },
  5744. /* Hit System
  5745. ------------------------------------------------------------------------------------------------------------------*/
  5746. prepareHits: function() {
  5747. this.colCoordCache.build();
  5748. this.slatCoordCache.build();
  5749. },
  5750. releaseHits: function() {
  5751. this.colCoordCache.clear();
  5752. // NOTE: don't clear slatCoordCache because we rely on it for computeTimeTop
  5753. },
  5754. queryHit: function(leftOffset, topOffset) {
  5755. var snapsPerSlot = this.snapsPerSlot;
  5756. var colCoordCache = this.colCoordCache;
  5757. var slatCoordCache = this.slatCoordCache;
  5758. if (colCoordCache.isLeftInBounds(leftOffset) && slatCoordCache.isTopInBounds(topOffset)) {
  5759. var colIndex = colCoordCache.getHorizontalIndex(leftOffset);
  5760. var slatIndex = slatCoordCache.getVerticalIndex(topOffset);
  5761. if (colIndex != null && slatIndex != null) {
  5762. var slatTop = slatCoordCache.getTopOffset(slatIndex);
  5763. var slatHeight = slatCoordCache.getHeight(slatIndex);
  5764. var partial = (topOffset - slatTop) / slatHeight; // floating point number between 0 and 1
  5765. var localSnapIndex = Math.floor(partial * snapsPerSlot); // the snap # relative to start of slat
  5766. var snapIndex = slatIndex * snapsPerSlot + localSnapIndex;
  5767. var snapTop = slatTop + (localSnapIndex / snapsPerSlot) * slatHeight;
  5768. var snapBottom = slatTop + ((localSnapIndex + 1) / snapsPerSlot) * slatHeight;
  5769. return {
  5770. col: colIndex,
  5771. snap: snapIndex,
  5772. component: this, // needed unfortunately :(
  5773. left: colCoordCache.getLeftOffset(colIndex),
  5774. right: colCoordCache.getRightOffset(colIndex),
  5775. top: snapTop,
  5776. bottom: snapBottom
  5777. };
  5778. }
  5779. }
  5780. },
  5781. getHitSpan: function(hit) {
  5782. var start = this.getCellDate(0, hit.col); // row=0
  5783. var time = this.computeSnapTime(hit.snap); // pass in the snap-index
  5784. var end;
  5785. start.time(time);
  5786. end = start.clone().add(this.snapDuration);
  5787. return { start: start, end: end };
  5788. },
  5789. getHitEl: function(hit) {
  5790. return this.colEls.eq(hit.col);
  5791. },
  5792. /* Dates
  5793. ------------------------------------------------------------------------------------------------------------------*/
  5794. rangeUpdated: function() {
  5795. this.updateDayTable();
  5796. },
  5797. // Given a row number of the grid, representing a "snap", returns a time (Duration) from its start-of-day
  5798. computeSnapTime: function(snapIndex) {
  5799. return moment.duration(this.minTime + this.snapDuration * snapIndex);
  5800. },
  5801. // Slices up the given span (unzoned start/end with other misc data) into an array of segments
  5802. spanToSegs: function(span) {
  5803. var segs = this.sliceRangeByTimes(span);
  5804. var i;
  5805. for (i = 0; i < segs.length; i++) {
  5806. if (this.isRTL) {
  5807. segs[i].col = this.daysPerRow - 1 - segs[i].dayIndex;
  5808. }
  5809. else {
  5810. segs[i].col = segs[i].dayIndex;
  5811. }
  5812. }
  5813. return segs;
  5814. },
  5815. sliceRangeByTimes: function(range) {
  5816. var segs = [];
  5817. var seg;
  5818. var dayIndex;
  5819. var dayDate;
  5820. var dayRange;
  5821. for (dayIndex = 0; dayIndex < this.daysPerRow; dayIndex++) {
  5822. dayDate = this.dayDates[dayIndex].clone(); // TODO: better API for this?
  5823. dayRange = {
  5824. start: dayDate.clone().time(this.minTime),
  5825. end: dayDate.clone().time(this.maxTime)
  5826. };
  5827. seg = intersectRanges(range, dayRange); // both will be ambig timezone
  5828. if (seg) {
  5829. seg.dayIndex = dayIndex;
  5830. segs.push(seg);
  5831. }
  5832. }
  5833. return segs;
  5834. },
  5835. /* Coordinates
  5836. ------------------------------------------------------------------------------------------------------------------*/
  5837. updateSize: function(isResize) { // NOT a standard Grid method
  5838. this.slatCoordCache.build();
  5839. if (isResize) {
  5840. this.updateSegVerticals(
  5841. [].concat(this.fgSegs || [], this.bgSegs || [], this.businessSegs || [])
  5842. );
  5843. }
  5844. },
  5845. getTotalSlatHeight: function() {
  5846. return this.slatContainerEl.outerHeight();
  5847. },
  5848. // Computes the top coordinate, relative to the bounds of the grid, of the given date.
  5849. // A `startOfDayDate` must be given for avoiding ambiguity over how to treat midnight.
  5850. computeDateTop: function(date, startOfDayDate) {
  5851. return this.computeTimeTop(
  5852. moment.duration(
  5853. date - startOfDayDate.clone().stripTime()
  5854. )
  5855. );
  5856. },
  5857. // Computes the top coordinate, relative to the bounds of the grid, of the given time (a Duration).
  5858. computeTimeTop: function(time) {
  5859. var len = this.slatEls.length;
  5860. var slatCoverage = (time - this.minTime) / this.slotDuration; // floating-point value of # of slots covered
  5861. var slatIndex;
  5862. var slatRemainder;
  5863. // compute a floating-point number for how many slats should be progressed through.
  5864. // from 0 to number of slats (inclusive)
  5865. // constrained because minTime/maxTime might be customized.
  5866. slatCoverage = Math.max(0, slatCoverage);
  5867. slatCoverage = Math.min(len, slatCoverage);
  5868. // an integer index of the furthest whole slat
  5869. // from 0 to number slats (*exclusive*, so len-1)
  5870. slatIndex = Math.floor(slatCoverage);
  5871. slatIndex = Math.min(slatIndex, len - 1);
  5872. // how much further through the slatIndex slat (from 0.0-1.0) must be covered in addition.
  5873. // could be 1.0 if slatCoverage is covering *all* the slots
  5874. slatRemainder = slatCoverage - slatIndex;
  5875. return this.slatCoordCache.getTopPosition(slatIndex) +
  5876. this.slatCoordCache.getHeight(slatIndex) * slatRemainder;
  5877. },
  5878. /* Event Drag Visualization
  5879. ------------------------------------------------------------------------------------------------------------------*/
  5880. // Renders a visual indication of an event being dragged over the specified date(s).
  5881. // A returned value of `true` signals that a mock "helper" event has been rendered.
  5882. renderDrag: function(eventLocation, seg) {
  5883. if (seg) { // if there is event information for this drag, render a helper event
  5884. // returns mock event elements
  5885. // signal that a helper has been rendered
  5886. return this.renderEventLocationHelper(eventLocation, seg);
  5887. }
  5888. else {
  5889. // otherwise, just render a highlight
  5890. this.renderHighlight(this.eventToSpan(eventLocation));
  5891. }
  5892. },
  5893. // Unrenders any visual indication of an event being dragged
  5894. unrenderDrag: function() {
  5895. this.unrenderHelper();
  5896. this.unrenderHighlight();
  5897. },
  5898. /* Event Resize Visualization
  5899. ------------------------------------------------------------------------------------------------------------------*/
  5900. // Renders a visual indication of an event being resized
  5901. renderEventResize: function(eventLocation, seg) {
  5902. return this.renderEventLocationHelper(eventLocation, seg); // returns mock event elements
  5903. },
  5904. // Unrenders any visual indication of an event being resized
  5905. unrenderEventResize: function() {
  5906. this.unrenderHelper();
  5907. },
  5908. /* Event Helper
  5909. ------------------------------------------------------------------------------------------------------------------*/
  5910. // Renders a mock "helper" event. `sourceSeg` is the original segment object and might be null (an external drag)
  5911. renderHelper: function(event, sourceSeg) {
  5912. return this.renderHelperSegs(this.eventToSegs(event), sourceSeg); // returns mock event elements
  5913. },
  5914. // Unrenders any mock helper event
  5915. unrenderHelper: function() {
  5916. this.unrenderHelperSegs();
  5917. },
  5918. /* Business Hours
  5919. ------------------------------------------------------------------------------------------------------------------*/
  5920. renderBusinessHours: function() {
  5921. this.renderBusinessSegs(
  5922. this.buildBusinessHourSegs()
  5923. );
  5924. },
  5925. unrenderBusinessHours: function() {
  5926. this.unrenderBusinessSegs();
  5927. },
  5928. /* Now Indicator
  5929. ------------------------------------------------------------------------------------------------------------------*/
  5930. getNowIndicatorUnit: function() {
  5931. return 'minute'; // will refresh on the minute
  5932. },
  5933. renderNowIndicator: function(date) {
  5934. // seg system might be overkill, but it handles scenario where line needs to be rendered
  5935. // more than once because of columns with the same date (resources columns for example)
  5936. var segs = this.spanToSegs({ start: date, end: date });
  5937. var top = this.computeDateTop(date, date);
  5938. var nodes = [];
  5939. var i;
  5940. // render lines within the columns
  5941. for (i = 0; i < segs.length; i++) {
  5942. nodes.push($('<div class="fc-now-indicator fc-now-indicator-line"></div>')
  5943. .css('top', top)
  5944. .appendTo(this.colContainerEls.eq(segs[i].col))[0]);
  5945. }
  5946. // render an arrow over the axis
  5947. if (segs.length > 0) { // is the current time in view?
  5948. nodes.push($('<div class="fc-now-indicator fc-now-indicator-arrow"></div>')
  5949. .css('top', top)
  5950. .appendTo(this.el.find('.fc-content-skeleton'))[0]);
  5951. }
  5952. this.nowIndicatorEls = $(nodes);
  5953. },
  5954. unrenderNowIndicator: function() {
  5955. if (this.nowIndicatorEls) {
  5956. this.nowIndicatorEls.remove();
  5957. this.nowIndicatorEls = null;
  5958. }
  5959. },
  5960. /* Selection
  5961. ------------------------------------------------------------------------------------------------------------------*/
  5962. // Renders a visual indication of a selection. Overrides the default, which was to simply render a highlight.
  5963. renderSelection: function(span) {
  5964. if (this.view.opt('selectHelper')) { // this setting signals that a mock helper event should be rendered
  5965. // normally acceps an eventLocation, span has a start/end, which is good enough
  5966. this.renderEventLocationHelper(span);
  5967. }
  5968. else {
  5969. this.renderHighlight(span);
  5970. }
  5971. },
  5972. // Unrenders any visual indication of a selection
  5973. unrenderSelection: function() {
  5974. this.unrenderHelper();
  5975. this.unrenderHighlight();
  5976. },
  5977. /* Highlight
  5978. ------------------------------------------------------------------------------------------------------------------*/
  5979. renderHighlight: function(span) {
  5980. this.renderHighlightSegs(this.spanToSegs(span));
  5981. },
  5982. unrenderHighlight: function() {
  5983. this.unrenderHighlightSegs();
  5984. }
  5985. });
  5986. ;;
  5987. /* Methods for rendering SEGMENTS, pieces of content that live on the view
  5988. ( this file is no longer just for events )
  5989. ----------------------------------------------------------------------------------------------------------------------*/
  5990. TimeGrid.mixin({
  5991. colContainerEls: null, // containers for each column
  5992. // inner-containers for each column where different types of segs live
  5993. fgContainerEls: null,
  5994. bgContainerEls: null,
  5995. helperContainerEls: null,
  5996. highlightContainerEls: null,
  5997. businessContainerEls: null,
  5998. // arrays of different types of displayed segments
  5999. fgSegs: null,
  6000. bgSegs: null,
  6001. helperSegs: null,
  6002. highlightSegs: null,
  6003. businessSegs: null,
  6004. // Renders the DOM that the view's content will live in
  6005. renderContentSkeleton: function() {
  6006. var cellHtml = '';
  6007. var i;
  6008. var skeletonEl;
  6009. for (i = 0; i < this.colCnt; i++) {
  6010. cellHtml +=
  6011. '<td>' +
  6012. '<div class="fc-content-col">' +
  6013. '<div class="fc-event-container fc-helper-container"></div>' +
  6014. '<div class="fc-event-container"></div>' +
  6015. '<div class="fc-highlight-container"></div>' +
  6016. '<div class="fc-bgevent-container"></div>' +
  6017. '<div class="fc-business-container"></div>' +
  6018. '</div>' +
  6019. '</td>';
  6020. }
  6021. skeletonEl = $(
  6022. '<div class="fc-content-skeleton">' +
  6023. '<table>' +
  6024. '<tr>' + cellHtml + '</tr>' +
  6025. '</table>' +
  6026. '</div>'
  6027. );
  6028. this.colContainerEls = skeletonEl.find('.fc-content-col');
  6029. this.helperContainerEls = skeletonEl.find('.fc-helper-container');
  6030. this.fgContainerEls = skeletonEl.find('.fc-event-container:not(.fc-helper-container)');
  6031. this.bgContainerEls = skeletonEl.find('.fc-bgevent-container');
  6032. this.highlightContainerEls = skeletonEl.find('.fc-highlight-container');
  6033. this.businessContainerEls = skeletonEl.find('.fc-business-container');
  6034. this.bookendCells(skeletonEl.find('tr')); // TODO: do this on string level
  6035. this.el.append(skeletonEl);
  6036. },
  6037. /* Foreground Events
  6038. ------------------------------------------------------------------------------------------------------------------*/
  6039. renderFgSegs: function(segs) {
  6040. segs = this.renderFgSegsIntoContainers(segs, this.fgContainerEls);
  6041. this.fgSegs = segs;
  6042. return segs; // needed for Grid::renderEvents
  6043. },
  6044. unrenderFgSegs: function() {
  6045. this.unrenderNamedSegs('fgSegs');
  6046. },
  6047. /* Foreground Helper Events
  6048. ------------------------------------------------------------------------------------------------------------------*/
  6049. renderHelperSegs: function(segs, sourceSeg) {
  6050. var helperEls = [];
  6051. var i, seg;
  6052. var sourceEl;
  6053. segs = this.renderFgSegsIntoContainers(segs, this.helperContainerEls);
  6054. // Try to make the segment that is in the same row as sourceSeg look the same
  6055. for (i = 0; i < segs.length; i++) {
  6056. seg = segs[i];
  6057. if (sourceSeg && sourceSeg.col === seg.col) {
  6058. sourceEl = sourceSeg.el;
  6059. seg.el.css({
  6060. left: sourceEl.css('left'),
  6061. right: sourceEl.css('right'),
  6062. 'margin-left': sourceEl.css('margin-left'),
  6063. 'margin-right': sourceEl.css('margin-right')
  6064. });
  6065. }
  6066. helperEls.push(seg.el[0]);
  6067. }
  6068. this.helperSegs = segs;
  6069. return $(helperEls); // must return rendered helpers
  6070. },
  6071. unrenderHelperSegs: function() {
  6072. this.unrenderNamedSegs('helperSegs');
  6073. },
  6074. /* Background Events
  6075. ------------------------------------------------------------------------------------------------------------------*/
  6076. renderBgSegs: function(segs) {
  6077. segs = this.renderFillSegEls('bgEvent', segs); // TODO: old fill system
  6078. this.updateSegVerticals(segs);
  6079. this.attachSegsByCol(this.groupSegsByCol(segs), this.bgContainerEls);
  6080. this.bgSegs = segs;
  6081. return segs; // needed for Grid::renderEvents
  6082. },
  6083. unrenderBgSegs: function() {
  6084. this.unrenderNamedSegs('bgSegs');
  6085. },
  6086. /* Highlight
  6087. ------------------------------------------------------------------------------------------------------------------*/
  6088. renderHighlightSegs: function(segs) {
  6089. segs = this.renderFillSegEls('highlight', segs); // TODO: old fill system
  6090. this.updateSegVerticals(segs);
  6091. this.attachSegsByCol(this.groupSegsByCol(segs), this.highlightContainerEls);
  6092. this.highlightSegs = segs;
  6093. },
  6094. unrenderHighlightSegs: function() {
  6095. this.unrenderNamedSegs('highlightSegs');
  6096. },
  6097. /* Business Hours
  6098. ------------------------------------------------------------------------------------------------------------------*/
  6099. renderBusinessSegs: function(segs) {
  6100. segs = this.renderFillSegEls('businessHours', segs); // TODO: old fill system
  6101. this.updateSegVerticals(segs);
  6102. this.attachSegsByCol(this.groupSegsByCol(segs), this.businessContainerEls);
  6103. this.businessSegs = segs;
  6104. },
  6105. unrenderBusinessSegs: function() {
  6106. this.unrenderNamedSegs('businessSegs');
  6107. },
  6108. /* Seg Rendering Utils
  6109. ------------------------------------------------------------------------------------------------------------------*/
  6110. // Given a flat array of segments, return an array of sub-arrays, grouped by each segment's col
  6111. groupSegsByCol: function(segs) {
  6112. var segsByCol = [];
  6113. var i;
  6114. for (i = 0; i < this.colCnt; i++) {
  6115. segsByCol.push([]);
  6116. }
  6117. for (i = 0; i < segs.length; i++) {
  6118. segsByCol[segs[i].col].push(segs[i]);
  6119. }
  6120. return segsByCol;
  6121. },
  6122. // Given segments grouped by column, insert the segments' elements into a parallel array of container
  6123. // elements, each living within a column.
  6124. attachSegsByCol: function(segsByCol, containerEls) {
  6125. var col;
  6126. var segs;
  6127. var i;
  6128. for (col = 0; col < this.colCnt; col++) { // iterate each column grouping
  6129. segs = segsByCol[col];
  6130. for (i = 0; i < segs.length; i++) {
  6131. containerEls.eq(col).append(segs[i].el);
  6132. }
  6133. }
  6134. },
  6135. // Given the name of a property of `this` object, assumed to be an array of segments,
  6136. // loops through each segment and removes from DOM. Will null-out the property afterwards.
  6137. unrenderNamedSegs: function(propName) {
  6138. var segs = this[propName];
  6139. var i;
  6140. if (segs) {
  6141. for (i = 0; i < segs.length; i++) {
  6142. segs[i].el.remove();
  6143. }
  6144. this[propName] = null;
  6145. }
  6146. },
  6147. /* Foreground Event Rendering Utils
  6148. ------------------------------------------------------------------------------------------------------------------*/
  6149. // Given an array of foreground segments, render a DOM element for each, computes position,
  6150. // and attaches to the column inner-container elements.
  6151. renderFgSegsIntoContainers: function(segs, containerEls) {
  6152. var segsByCol;
  6153. var col;
  6154. segs = this.renderFgSegEls(segs); // will call fgSegHtml
  6155. segsByCol = this.groupSegsByCol(segs);
  6156. for (col = 0; col < this.colCnt; col++) {
  6157. this.updateFgSegCoords(segsByCol[col]);
  6158. }
  6159. this.attachSegsByCol(segsByCol, containerEls);
  6160. return segs;
  6161. },
  6162. // Renders the HTML for a single event segment's default rendering
  6163. fgSegHtml: function(seg, disableResizing) {
  6164. var view = this.view;
  6165. var event = seg.event;
  6166. var isDraggable = view.isEventDraggable(event);
  6167. var isResizableFromStart = !disableResizing && seg.isStart && view.isEventResizableFromStart(event);
  6168. var isResizableFromEnd = !disableResizing && seg.isEnd && view.isEventResizableFromEnd(event);
  6169. var classes = this.getSegClasses(seg, isDraggable, isResizableFromStart || isResizableFromEnd);
  6170. var skinCss = cssToStr(this.getSegSkinCss(seg));
  6171. var timeText;
  6172. var fullTimeText; // more verbose time text. for the print stylesheet
  6173. var startTimeText; // just the start time text
  6174. classes.unshift('fc-time-grid-event', 'fc-v-event');
  6175. if (view.isMultiDayEvent(event)) { // if the event appears to span more than one day...
  6176. // Don't display time text on segments that run entirely through a day.
  6177. // That would appear as midnight-midnight and would look dumb.
  6178. // Otherwise, display the time text for the *segment's* times (like 6pm-midnight or midnight-10am)
  6179. if (seg.isStart || seg.isEnd) {
  6180. timeText = this.getEventTimeText(seg);
  6181. fullTimeText = this.getEventTimeText(seg, 'LT');
  6182. startTimeText = this.getEventTimeText(seg, null, false); // displayEnd=false
  6183. }
  6184. } else {
  6185. // Display the normal time text for the *event's* times
  6186. timeText = this.getEventTimeText(event);
  6187. fullTimeText = this.getEventTimeText(event, 'LT');
  6188. startTimeText = this.getEventTimeText(event, null, false); // displayEnd=false
  6189. }
  6190. return '<a class="' + classes.join(' ') + '"' +
  6191. (event.url ?
  6192. ' href="' + htmlEscape(event.url) + '"' :
  6193. ''
  6194. ) +
  6195. (skinCss ?
  6196. ' style="' + skinCss + '"' :
  6197. ''
  6198. ) +
  6199. '>' +
  6200. '<div class="fc-content">' +
  6201. (timeText ?
  6202. '<div class="fc-time"' +
  6203. ' data-start="' + htmlEscape(startTimeText) + '"' +
  6204. ' data-full="' + htmlEscape(fullTimeText) + '"' +
  6205. '>' +
  6206. '<span>' + htmlEscape(timeText) + '</span>' +
  6207. '</div>' :
  6208. ''
  6209. ) +
  6210. (event.title ?
  6211. '<div class="fc-title">' +
  6212. htmlEscape(event.title) +
  6213. '</div>' :
  6214. ''
  6215. ) +
  6216. '</div>' +
  6217. '<div class="fc-bg"/>' +
  6218. /* TODO: write CSS for this
  6219. (isResizableFromStart ?
  6220. '<div class="fc-resizer fc-start-resizer" />' :
  6221. ''
  6222. ) +
  6223. */
  6224. (isResizableFromEnd ?
  6225. '<div class="fc-resizer fc-end-resizer" />' :
  6226. ''
  6227. ) +
  6228. '</a>';
  6229. },
  6230. /* Seg Position Utils
  6231. ------------------------------------------------------------------------------------------------------------------*/
  6232. // Refreshes the CSS top/bottom coordinates for each segment element.
  6233. // Works when called after initial render, after a window resize/zoom for example.
  6234. updateSegVerticals: function(segs) {
  6235. this.computeSegVerticals(segs);
  6236. this.assignSegVerticals(segs);
  6237. },
  6238. // For each segment in an array, computes and assigns its top and bottom properties
  6239. computeSegVerticals: function(segs) {
  6240. var i, seg;
  6241. for (i = 0; i < segs.length; i++) {
  6242. seg = segs[i];
  6243. seg.top = this.computeDateTop(seg.start, seg.start);
  6244. seg.bottom = this.computeDateTop(seg.end, seg.start);
  6245. }
  6246. },
  6247. // Given segments that already have their top/bottom properties computed, applies those values to
  6248. // the segments' elements.
  6249. assignSegVerticals: function(segs) {
  6250. var i, seg;
  6251. for (i = 0; i < segs.length; i++) {
  6252. seg = segs[i];
  6253. seg.el.css(this.generateSegVerticalCss(seg));
  6254. }
  6255. },
  6256. // Generates an object with CSS properties for the top/bottom coordinates of a segment element
  6257. generateSegVerticalCss: function(seg) {
  6258. return {
  6259. top: seg.top,
  6260. bottom: -seg.bottom // flipped because needs to be space beyond bottom edge of event container
  6261. };
  6262. },
  6263. /* Foreground Event Positioning Utils
  6264. ------------------------------------------------------------------------------------------------------------------*/
  6265. // Given segments that are assumed to all live in the *same column*,
  6266. // compute their verical/horizontal coordinates and assign to their elements.
  6267. updateFgSegCoords: function(segs) {
  6268. this.computeSegVerticals(segs); // horizontals relies on this
  6269. this.computeFgSegHorizontals(segs); // compute horizontal coordinates, z-index's, and reorder the array
  6270. this.assignSegVerticals(segs);
  6271. this.assignFgSegHorizontals(segs);
  6272. },
  6273. // Given an array of segments that are all in the same column, sets the backwardCoord and forwardCoord on each.
  6274. // NOTE: Also reorders the given array by date!
  6275. computeFgSegHorizontals: function(segs) {
  6276. var levels;
  6277. var level0;
  6278. var i;
  6279. this.sortEventSegs(segs); // order by certain criteria
  6280. levels = buildSlotSegLevels(segs);
  6281. computeForwardSlotSegs(levels);
  6282. if ((level0 = levels[0])) {
  6283. for (i = 0; i < level0.length; i++) {
  6284. computeSlotSegPressures(level0[i]);
  6285. }
  6286. for (i = 0; i < level0.length; i++) {
  6287. this.computeFgSegForwardBack(level0[i], 0, 0);
  6288. }
  6289. }
  6290. },
  6291. // Calculate seg.forwardCoord and seg.backwardCoord for the segment, where both values range
  6292. // from 0 to 1. If the calendar is left-to-right, the seg.backwardCoord maps to "left" and
  6293. // seg.forwardCoord maps to "right" (via percentage). Vice-versa if the calendar is right-to-left.
  6294. //
  6295. // The segment might be part of a "series", which means consecutive segments with the same pressure
  6296. // who's width is unknown until an edge has been hit. `seriesBackwardPressure` is the number of
  6297. // segments behind this one in the current series, and `seriesBackwardCoord` is the starting
  6298. // coordinate of the first segment in the series.
  6299. computeFgSegForwardBack: function(seg, seriesBackwardPressure, seriesBackwardCoord) {
  6300. var forwardSegs = seg.forwardSegs;
  6301. var i;
  6302. if (seg.forwardCoord === undefined) { // not already computed
  6303. if (!forwardSegs.length) {
  6304. // if there are no forward segments, this segment should butt up against the edge
  6305. seg.forwardCoord = 1;
  6306. }
  6307. else {
  6308. // sort highest pressure first
  6309. this.sortForwardSegs(forwardSegs);
  6310. // this segment's forwardCoord will be calculated from the backwardCoord of the
  6311. // highest-pressure forward segment.
  6312. this.computeFgSegForwardBack(forwardSegs[0], seriesBackwardPressure + 1, seriesBackwardCoord);
  6313. seg.forwardCoord = forwardSegs[0].backwardCoord;
  6314. }
  6315. // calculate the backwardCoord from the forwardCoord. consider the series
  6316. seg.backwardCoord = seg.forwardCoord -
  6317. (seg.forwardCoord - seriesBackwardCoord) / // available width for series
  6318. (seriesBackwardPressure + 1); // # of segments in the series
  6319. // use this segment's coordinates to computed the coordinates of the less-pressurized
  6320. // forward segments
  6321. for (i=0; i<forwardSegs.length; i++) {
  6322. this.computeFgSegForwardBack(forwardSegs[i], 0, seg.forwardCoord);
  6323. }
  6324. }
  6325. },
  6326. sortForwardSegs: function(forwardSegs) {
  6327. forwardSegs.sort(proxy(this, 'compareForwardSegs'));
  6328. },
  6329. // A cmp function for determining which forward segment to rely on more when computing coordinates.
  6330. compareForwardSegs: function(seg1, seg2) {
  6331. // put higher-pressure first
  6332. return seg2.forwardPressure - seg1.forwardPressure ||
  6333. // put segments that are closer to initial edge first (and favor ones with no coords yet)
  6334. (seg1.backwardCoord || 0) - (seg2.backwardCoord || 0) ||
  6335. // do normal sorting...
  6336. this.compareEventSegs(seg1, seg2);
  6337. },
  6338. // Given foreground event segments that have already had their position coordinates computed,
  6339. // assigns position-related CSS values to their elements.
  6340. assignFgSegHorizontals: function(segs) {
  6341. var i, seg;
  6342. for (i = 0; i < segs.length; i++) {
  6343. seg = segs[i];
  6344. seg.el.css(this.generateFgSegHorizontalCss(seg));
  6345. // if the height is short, add a className for alternate styling
  6346. if (seg.bottom - seg.top < 30) {
  6347. seg.el.addClass('fc-short');
  6348. }
  6349. }
  6350. },
  6351. // Generates an object with CSS properties/values that should be applied to an event segment element.
  6352. // Contains important positioning-related properties that should be applied to any event element, customized or not.
  6353. generateFgSegHorizontalCss: function(seg) {
  6354. var shouldOverlap = this.view.opt('slotEventOverlap');
  6355. var backwardCoord = seg.backwardCoord; // the left side if LTR. the right side if RTL. floating-point
  6356. var forwardCoord = seg.forwardCoord; // the right side if LTR. the left side if RTL. floating-point
  6357. var props = this.generateSegVerticalCss(seg); // get top/bottom first
  6358. var left; // amount of space from left edge, a fraction of the total width
  6359. var right; // amount of space from right edge, a fraction of the total width
  6360. if (shouldOverlap) {
  6361. // double the width, but don't go beyond the maximum forward coordinate (1.0)
  6362. forwardCoord = Math.min(1, backwardCoord + (forwardCoord - backwardCoord) * 2);
  6363. }
  6364. if (this.isRTL) {
  6365. left = 1 - forwardCoord;
  6366. right = backwardCoord;
  6367. }
  6368. else {
  6369. left = backwardCoord;
  6370. right = 1 - forwardCoord;
  6371. }
  6372. props.zIndex = seg.level + 1; // convert from 0-base to 1-based
  6373. props.left = left * 100 + '%';
  6374. props.right = right * 100 + '%';
  6375. if (shouldOverlap && seg.forwardPressure) {
  6376. // add padding to the edge so that forward stacked events don't cover the resizer's icon
  6377. props[this.isRTL ? 'marginLeft' : 'marginRight'] = 10 * 2; // 10 is a guesstimate of the icon's width
  6378. }
  6379. return props;
  6380. }
  6381. });
  6382. // Builds an array of segments "levels". The first level will be the leftmost tier of segments if the calendar is
  6383. // left-to-right, or the rightmost if the calendar is right-to-left. Assumes the segments are already ordered by date.
  6384. function buildSlotSegLevels(segs) {
  6385. var levels = [];
  6386. var i, seg;
  6387. var j;
  6388. for (i=0; i<segs.length; i++) {
  6389. seg = segs[i];
  6390. // go through all the levels and stop on the first level where there are no collisions
  6391. for (j=0; j<levels.length; j++) {
  6392. if (!computeSlotSegCollisions(seg, levels[j]).length) {
  6393. break;
  6394. }
  6395. }
  6396. seg.level = j;
  6397. (levels[j] || (levels[j] = [])).push(seg);
  6398. }
  6399. return levels;
  6400. }
  6401. // For every segment, figure out the other segments that are in subsequent
  6402. // levels that also occupy the same vertical space. Accumulate in seg.forwardSegs
  6403. function computeForwardSlotSegs(levels) {
  6404. var i, level;
  6405. var j, seg;
  6406. var k;
  6407. for (i=0; i<levels.length; i++) {
  6408. level = levels[i];
  6409. for (j=0; j<level.length; j++) {
  6410. seg = level[j];
  6411. seg.forwardSegs = [];
  6412. for (k=i+1; k<levels.length; k++) {
  6413. computeSlotSegCollisions(seg, levels[k], seg.forwardSegs);
  6414. }
  6415. }
  6416. }
  6417. }
  6418. // Figure out which path forward (via seg.forwardSegs) results in the longest path until
  6419. // the furthest edge is reached. The number of segments in this path will be seg.forwardPressure
  6420. function computeSlotSegPressures(seg) {
  6421. var forwardSegs = seg.forwardSegs;
  6422. var forwardPressure = 0;
  6423. var i, forwardSeg;
  6424. if (seg.forwardPressure === undefined) { // not already computed
  6425. for (i=0; i<forwardSegs.length; i++) {
  6426. forwardSeg = forwardSegs[i];
  6427. // figure out the child's maximum forward path
  6428. computeSlotSegPressures(forwardSeg);
  6429. // either use the existing maximum, or use the child's forward pressure
  6430. // plus one (for the forwardSeg itself)
  6431. forwardPressure = Math.max(
  6432. forwardPressure,
  6433. 1 + forwardSeg.forwardPressure
  6434. );
  6435. }
  6436. seg.forwardPressure = forwardPressure;
  6437. }
  6438. }
  6439. // Find all the segments in `otherSegs` that vertically collide with `seg`.
  6440. // Append into an optionally-supplied `results` array and return.
  6441. function computeSlotSegCollisions(seg, otherSegs, results) {
  6442. results = results || [];
  6443. for (var i=0; i<otherSegs.length; i++) {
  6444. if (isSlotSegCollision(seg, otherSegs[i])) {
  6445. results.push(otherSegs[i]);
  6446. }
  6447. }
  6448. return results;
  6449. }
  6450. // Do these segments occupy the same vertical space?
  6451. function isSlotSegCollision(seg1, seg2) {
  6452. return seg1.bottom > seg2.top && seg1.top < seg2.bottom;
  6453. }
  6454. ;;
  6455. /* An abstract class from which other views inherit from
  6456. ----------------------------------------------------------------------------------------------------------------------*/
  6457. var View = FC.View = Class.extend(EmitterMixin, ListenerMixin, {
  6458. type: null, // subclass' view name (string)
  6459. name: null, // deprecated. use `type` instead
  6460. title: null, // the text that will be displayed in the header's title
  6461. calendar: null, // owner Calendar object
  6462. options: null, // hash containing all options. already merged with view-specific-options
  6463. el: null, // the view's containing element. set by Calendar
  6464. isDateSet: false,
  6465. isDateRendered: false,
  6466. dateRenderQueue: null,
  6467. isEventsBound: false,
  6468. isEventsSet: false,
  6469. isEventsRendered: false,
  6470. eventRenderQueue: null,
  6471. // range the view is actually displaying (moments)
  6472. start: null,
  6473. end: null, // exclusive
  6474. // range the view is formally responsible for (moments)
  6475. // may be different from start/end. for example, a month view might have 1st-31st, excluding padded dates
  6476. intervalStart: null,
  6477. intervalEnd: null, // exclusive
  6478. intervalDuration: null,
  6479. intervalUnit: null, // name of largest unit being displayed, like "month" or "week"
  6480. isRTL: false,
  6481. isSelected: false, // boolean whether a range of time is user-selected or not
  6482. selectedEvent: null,
  6483. eventOrderSpecs: null, // criteria for ordering events when they have same date/time
  6484. // classNames styled by jqui themes
  6485. widgetHeaderClass: null,
  6486. widgetContentClass: null,
  6487. highlightStateClass: null,
  6488. // for date utils, computed from options
  6489. nextDayThreshold: null,
  6490. isHiddenDayHash: null,
  6491. // now indicator
  6492. isNowIndicatorRendered: null,
  6493. initialNowDate: null, // result first getNow call
  6494. initialNowQueriedMs: null, // ms time the getNow was called
  6495. nowIndicatorTimeoutID: null, // for refresh timing of now indicator
  6496. nowIndicatorIntervalID: null, // "
  6497. constructor: function(calendar, type, options, intervalDuration) {
  6498. this.calendar = calendar;
  6499. this.type = this.name = type; // .name is deprecated
  6500. this.options = options;
  6501. this.intervalDuration = intervalDuration || moment.duration(1, 'day');
  6502. this.nextDayThreshold = moment.duration(this.opt('nextDayThreshold'));
  6503. this.initThemingProps();
  6504. this.initHiddenDays();
  6505. this.isRTL = this.opt('isRTL');
  6506. this.eventOrderSpecs = parseFieldSpecs(this.opt('eventOrder'));
  6507. this.dateRenderQueue = new TaskQueue();
  6508. this.eventRenderQueue = new TaskQueue(this.opt('eventRenderWait'));
  6509. this.initialize();
  6510. },
  6511. // A good place for subclasses to initialize member variables
  6512. initialize: function() {
  6513. // subclasses can implement
  6514. },
  6515. // Retrieves an option with the given name
  6516. opt: function(name) {
  6517. return this.options[name];
  6518. },
  6519. // Triggers handlers that are view-related. Modifies args before passing to calendar.
  6520. publiclyTrigger: function(name, thisObj) { // arguments beyond thisObj are passed along
  6521. var calendar = this.calendar;
  6522. return calendar.publiclyTrigger.apply(
  6523. calendar,
  6524. [name, thisObj || this].concat(
  6525. Array.prototype.slice.call(arguments, 2), // arguments beyond thisObj
  6526. [ this ] // always make the last argument a reference to the view. TODO: deprecate
  6527. )
  6528. );
  6529. },
  6530. // Returns a proxy of the given promise that will be rejected if the given event fires
  6531. // before the promise resolves.
  6532. rejectOn: function(eventName, promise) {
  6533. var _this = this;
  6534. return new Promise(function(resolve, reject) {
  6535. _this.one(eventName, reject);
  6536. function cleanup() {
  6537. _this.off(eventName, reject);
  6538. }
  6539. promise.then(function(res) { // success
  6540. cleanup();
  6541. resolve(res);
  6542. }, function() { // failure
  6543. cleanup();
  6544. reject();
  6545. });
  6546. });
  6547. },
  6548. /* Date Computation
  6549. ------------------------------------------------------------------------------------------------------------------*/
  6550. // Updates all internal dates for displaying the given unzoned range.
  6551. setRange: function(range) {
  6552. $.extend(this, range); // assigns every property to this object's member variables
  6553. this.updateTitle();
  6554. },
  6555. // Given a single current unzoned date, produce information about what range to display.
  6556. // Subclasses can override. Must return all properties.
  6557. computeRange: function(date) {
  6558. var intervalUnit = computeIntervalUnit(this.intervalDuration);
  6559. var intervalStart = date.clone().startOf(intervalUnit);
  6560. var intervalEnd = intervalStart.clone().add(this.intervalDuration);
  6561. var start, end;
  6562. // normalize the range's time-ambiguity
  6563. if (/year|month|week|day/.test(intervalUnit)) { // whole-days?
  6564. intervalStart.stripTime();
  6565. intervalEnd.stripTime();
  6566. }
  6567. else { // needs to have a time?
  6568. if (!intervalStart.hasTime()) {
  6569. intervalStart = this.calendar.time(0); // give 00:00 time
  6570. }
  6571. if (!intervalEnd.hasTime()) {
  6572. intervalEnd = this.calendar.time(0); // give 00:00 time
  6573. }
  6574. }
  6575. start = intervalStart.clone();
  6576. start = this.skipHiddenDays(start);
  6577. end = intervalEnd.clone();
  6578. end = this.skipHiddenDays(end, -1, true); // exclusively move backwards
  6579. return {
  6580. intervalUnit: intervalUnit,
  6581. intervalStart: intervalStart,
  6582. intervalEnd: intervalEnd,
  6583. start: start,
  6584. end: end
  6585. };
  6586. },
  6587. // Computes the new date when the user hits the prev button, given the current date
  6588. computePrevDate: function(date) {
  6589. return this.massageCurrentDate(
  6590. date.clone().startOf(this.intervalUnit).subtract(this.intervalDuration), -1
  6591. );
  6592. },
  6593. // Computes the new date when the user hits the next button, given the current date
  6594. computeNextDate: function(date) {
  6595. return this.massageCurrentDate(
  6596. date.clone().startOf(this.intervalUnit).add(this.intervalDuration)
  6597. );
  6598. },
  6599. // Given an arbitrarily calculated current date of the calendar, returns a date that is ensured to be completely
  6600. // visible. `direction` is optional and indicates which direction the current date was being
  6601. // incremented or decremented (1 or -1).
  6602. massageCurrentDate: function(date, direction) {
  6603. if (this.intervalDuration.as('days') <= 1) { // if the view displays a single day or smaller
  6604. if (this.isHiddenDay(date)) {
  6605. date = this.skipHiddenDays(date, direction);
  6606. date.startOf('day');
  6607. }
  6608. }
  6609. return date;
  6610. },
  6611. /* Title and Date Formatting
  6612. ------------------------------------------------------------------------------------------------------------------*/
  6613. // Sets the view's title property to the most updated computed value
  6614. updateTitle: function() {
  6615. this.title = this.computeTitle();
  6616. this.calendar.setToolbarsTitle(this.title);
  6617. },
  6618. // Computes what the title at the top of the calendar should be for this view
  6619. computeTitle: function() {
  6620. var start, end;
  6621. // for views that span a large unit of time, show the proper interval, ignoring stray days before and after
  6622. if (this.intervalUnit === 'year' || this.intervalUnit === 'month') {
  6623. start = this.intervalStart;
  6624. end = this.intervalEnd;
  6625. }
  6626. else { // for day units or smaller, use the actual day range
  6627. start = this.start;
  6628. end = this.end;
  6629. }
  6630. return this.formatRange(
  6631. {
  6632. // in case intervalStart/End has a time, make sure timezone is correct
  6633. start: this.calendar.applyTimezone(start),
  6634. end: this.calendar.applyTimezone(end)
  6635. },
  6636. this.opt('titleFormat') || this.computeTitleFormat(),
  6637. this.opt('titleRangeSeparator')
  6638. );
  6639. },
  6640. // Generates the format string that should be used to generate the title for the current date range.
  6641. // Attempts to compute the most appropriate format if not explicitly specified with `titleFormat`.
  6642. computeTitleFormat: function() {
  6643. if (this.intervalUnit == 'year') {
  6644. return 'YYYY';
  6645. }
  6646. else if (this.intervalUnit == 'month') {
  6647. return this.opt('monthYearFormat'); // like "September 2014"
  6648. }
  6649. else if (this.intervalDuration.as('days') > 1) {
  6650. return 'll'; // multi-day range. shorter, like "Sep 9 - 10 2014"
  6651. }
  6652. else {
  6653. return 'LL'; // one day. longer, like "September 9 2014"
  6654. }
  6655. },
  6656. // Utility for formatting a range. Accepts a range object, formatting string, and optional separator.
  6657. // Displays all-day ranges naturally, with an inclusive end. Takes the current isRTL into account.
  6658. // The timezones of the dates within `range` will be respected.
  6659. formatRange: function(range, formatStr, separator) {
  6660. var end = range.end;
  6661. if (!end.hasTime()) { // all-day?
  6662. end = end.clone().subtract(1); // convert to inclusive. last ms of previous day
  6663. }
  6664. return formatRange(range.start, end, formatStr, separator, this.opt('isRTL'));
  6665. },
  6666. getAllDayHtml: function() {
  6667. return this.opt('allDayHtml') || htmlEscape(this.opt('allDayText'));
  6668. },
  6669. /* Navigation
  6670. ------------------------------------------------------------------------------------------------------------------*/
  6671. // Generates HTML for an anchor to another view into the calendar.
  6672. // Will either generate an <a> tag or a non-clickable <span> tag, depending on enabled settings.
  6673. // `gotoOptions` can either be a moment input, or an object with the form:
  6674. // { date, type, forceOff }
  6675. // `type` is a view-type like "day" or "week". default value is "day".
  6676. // `attrs` and `innerHtml` are use to generate the rest of the HTML tag.
  6677. buildGotoAnchorHtml: function(gotoOptions, attrs, innerHtml) {
  6678. var date, type, forceOff;
  6679. var finalOptions;
  6680. if ($.isPlainObject(gotoOptions)) {
  6681. date = gotoOptions.date;
  6682. type = gotoOptions.type;
  6683. forceOff = gotoOptions.forceOff;
  6684. }
  6685. else {
  6686. date = gotoOptions; // a single moment input
  6687. }
  6688. date = FC.moment(date); // if a string, parse it
  6689. finalOptions = { // for serialization into the link
  6690. date: date.format('YYYY-MM-DD'),
  6691. type: type || 'day'
  6692. };
  6693. if (typeof attrs === 'string') {
  6694. innerHtml = attrs;
  6695. attrs = null;
  6696. }
  6697. attrs = attrs ? ' ' + attrsToStr(attrs) : ''; // will have a leading space
  6698. innerHtml = innerHtml || '';
  6699. if (!forceOff && this.opt('navLinks')) {
  6700. return '<a' + attrs +
  6701. ' data-goto="' + htmlEscape(JSON.stringify(finalOptions)) + '">' +
  6702. innerHtml +
  6703. '</a>';
  6704. }
  6705. else {
  6706. return '<span' + attrs + '>' +
  6707. innerHtml +
  6708. '</span>';
  6709. }
  6710. },
  6711. // Rendering Non-date-related Content
  6712. // -----------------------------------------------------------------------------------------------------------------
  6713. // Sets the container element that the view should render inside of, does global DOM-related initializations,
  6714. // and renders all the non-date-related content inside.
  6715. setElement: function(el) {
  6716. this.el = el;
  6717. this.bindGlobalHandlers();
  6718. this.renderSkeleton();
  6719. },
  6720. // Removes the view's container element from the DOM, clearing any content beforehand.
  6721. // Undoes any other DOM-related attachments.
  6722. removeElement: function() {
  6723. this.unsetDate();
  6724. this.unrenderSkeleton();
  6725. this.unbindGlobalHandlers();
  6726. this.el.remove();
  6727. // NOTE: don't null-out this.el in case the View was destroyed within an API callback.
  6728. // We don't null-out the View's other jQuery element references upon destroy,
  6729. // so we shouldn't kill this.el either.
  6730. },
  6731. // Renders the basic structure of the view before any content is rendered
  6732. renderSkeleton: function() {
  6733. // subclasses should implement
  6734. },
  6735. // Unrenders the basic structure of the view
  6736. unrenderSkeleton: function() {
  6737. // subclasses should implement
  6738. },
  6739. // Date Setting/Unsetting
  6740. // -----------------------------------------------------------------------------------------------------------------
  6741. setDate: function(date) {
  6742. var isReset = this.isDateSet;
  6743. this.isDateSet = true;
  6744. this.handleDate(date, isReset);
  6745. this.trigger(isReset ? 'dateReset' : 'dateSet', date);
  6746. },
  6747. unsetDate: function() {
  6748. if (this.isDateSet) {
  6749. this.isDateSet = false;
  6750. this.handleDateUnset();
  6751. this.trigger('dateUnset');
  6752. }
  6753. },
  6754. // Date Handling
  6755. // -----------------------------------------------------------------------------------------------------------------
  6756. handleDate: function(date, isReset) {
  6757. var _this = this;
  6758. this.unbindEvents(); // will do nothing if not already bound
  6759. this.requestDateRender(date).then(function() {
  6760. // wish we could start earlier, but setRange/computeRange needs to execute first
  6761. _this.bindEvents(); // will request events
  6762. });
  6763. },
  6764. handleDateUnset: function() {
  6765. this.unbindEvents();
  6766. this.requestDateUnrender();
  6767. },
  6768. // Date Render Queuing
  6769. // -----------------------------------------------------------------------------------------------------------------
  6770. // if date not specified, uses current
  6771. requestDateRender: function(date) {
  6772. var _this = this;
  6773. return this.dateRenderQueue.add(function() {
  6774. return _this.executeDateRender(date);
  6775. });
  6776. },
  6777. requestDateUnrender: function() {
  6778. var _this = this;
  6779. return this.dateRenderQueue.add(function() {
  6780. return _this.executeDateUnrender();
  6781. });
  6782. },
  6783. // Date High-level Rendering
  6784. // -----------------------------------------------------------------------------------------------------------------
  6785. // if date not specified, uses current
  6786. executeDateRender: function(date) {
  6787. var _this = this;
  6788. // if rendering a new date, reset scroll to initial state (scrollTime)
  6789. if (date) {
  6790. this.captureInitialScroll();
  6791. }
  6792. else {
  6793. this.captureScroll(); // a rerender of the current date
  6794. }
  6795. this.freezeHeight();
  6796. return this.executeDateUnrender().then(function() {
  6797. if (date) {
  6798. _this.setRange(_this.computeRange(date));
  6799. }
  6800. if (_this.render) {
  6801. _this.render(); // TODO: deprecate
  6802. }
  6803. _this.renderDates();
  6804. _this.updateSize();
  6805. _this.renderBusinessHours(); // might need coordinates, so should go after updateSize()
  6806. _this.startNowIndicator();
  6807. _this.thawHeight();
  6808. _this.releaseScroll();
  6809. _this.isDateRendered = true;
  6810. _this.onDateRender();
  6811. _this.trigger('dateRender');
  6812. });
  6813. },
  6814. executeDateUnrender: function() {
  6815. var _this = this;
  6816. if (_this.isDateRendered) {
  6817. return this.requestEventsUnrender().then(function() {
  6818. _this.unselect();
  6819. _this.stopNowIndicator();
  6820. _this.triggerUnrender();
  6821. _this.unrenderBusinessHours();
  6822. _this.unrenderDates();
  6823. if (_this.destroy) {
  6824. _this.destroy(); // TODO: deprecate
  6825. }
  6826. _this.isDateRendered = false;
  6827. _this.trigger('dateUnrender');
  6828. });
  6829. }
  6830. else {
  6831. return Promise.resolve();
  6832. }
  6833. },
  6834. // Date Rendering Triggers
  6835. // -----------------------------------------------------------------------------------------------------------------
  6836. onDateRender: function() {
  6837. this.triggerRender();
  6838. },
  6839. // Date Low-level Rendering
  6840. // -----------------------------------------------------------------------------------------------------------------
  6841. // date-cell content only
  6842. renderDates: function() {
  6843. // subclasses should implement
  6844. },
  6845. // date-cell content only
  6846. unrenderDates: function() {
  6847. // subclasses should override
  6848. },
  6849. // Misc view rendering utils
  6850. // -------------------------
  6851. // Signals that the view's content has been rendered
  6852. triggerRender: function() {
  6853. this.publiclyTrigger('viewRender', this, this, this.el);
  6854. },
  6855. // Signals that the view's content is about to be unrendered
  6856. triggerUnrender: function() {
  6857. this.publiclyTrigger('viewDestroy', this, this, this.el);
  6858. },
  6859. // Binds DOM handlers to elements that reside outside the view container, such as the document
  6860. bindGlobalHandlers: function() {
  6861. this.listenTo(GlobalEmitter.get(), {
  6862. touchstart: this.processUnselect,
  6863. mousedown: this.handleDocumentMousedown
  6864. });
  6865. },
  6866. // Unbinds DOM handlers from elements that reside outside the view container
  6867. unbindGlobalHandlers: function() {
  6868. this.stopListeningTo(GlobalEmitter.get());
  6869. },
  6870. // Initializes internal variables related to theming
  6871. initThemingProps: function() {
  6872. var tm = this.opt('theme') ? 'ui' : 'fc';
  6873. this.widgetHeaderClass = tm + '-widget-header';
  6874. this.widgetContentClass = tm + '-widget-content';
  6875. this.highlightStateClass = tm + '-state-highlight';
  6876. },
  6877. /* Business Hours
  6878. ------------------------------------------------------------------------------------------------------------------*/
  6879. // Renders business-hours onto the view. Assumes updateSize has already been called.
  6880. renderBusinessHours: function() {
  6881. // subclasses should implement
  6882. },
  6883. // Unrenders previously-rendered business-hours
  6884. unrenderBusinessHours: function() {
  6885. // subclasses should implement
  6886. },
  6887. /* Now Indicator
  6888. ------------------------------------------------------------------------------------------------------------------*/
  6889. // Immediately render the current time indicator and begins re-rendering it at an interval,
  6890. // which is defined by this.getNowIndicatorUnit().
  6891. // TODO: somehow do this for the current whole day's background too
  6892. startNowIndicator: function() {
  6893. var _this = this;
  6894. var unit;
  6895. var update;
  6896. var delay; // ms wait value
  6897. if (this.opt('nowIndicator')) {
  6898. unit = this.getNowIndicatorUnit();
  6899. if (unit) {
  6900. update = proxy(this, 'updateNowIndicator'); // bind to `this`
  6901. this.initialNowDate = this.calendar.getNow();
  6902. this.initialNowQueriedMs = +new Date();
  6903. this.renderNowIndicator(this.initialNowDate);
  6904. this.isNowIndicatorRendered = true;
  6905. // wait until the beginning of the next interval
  6906. delay = this.initialNowDate.clone().startOf(unit).add(1, unit) - this.initialNowDate;
  6907. this.nowIndicatorTimeoutID = setTimeout(function() {
  6908. _this.nowIndicatorTimeoutID = null;
  6909. update();
  6910. delay = +moment.duration(1, unit);
  6911. delay = Math.max(100, delay); // prevent too frequent
  6912. _this.nowIndicatorIntervalID = setInterval(update, delay); // update every interval
  6913. }, delay);
  6914. }
  6915. }
  6916. },
  6917. // rerenders the now indicator, computing the new current time from the amount of time that has passed
  6918. // since the initial getNow call.
  6919. updateNowIndicator: function() {
  6920. if (this.isNowIndicatorRendered) {
  6921. this.unrenderNowIndicator();
  6922. this.renderNowIndicator(
  6923. this.initialNowDate.clone().add(new Date() - this.initialNowQueriedMs) // add ms
  6924. );
  6925. }
  6926. },
  6927. // Immediately unrenders the view's current time indicator and stops any re-rendering timers.
  6928. // Won't cause side effects if indicator isn't rendered.
  6929. stopNowIndicator: function() {
  6930. if (this.isNowIndicatorRendered) {
  6931. if (this.nowIndicatorTimeoutID) {
  6932. clearTimeout(this.nowIndicatorTimeoutID);
  6933. this.nowIndicatorTimeoutID = null;
  6934. }
  6935. if (this.nowIndicatorIntervalID) {
  6936. clearTimeout(this.nowIndicatorIntervalID);
  6937. this.nowIndicatorIntervalID = null;
  6938. }
  6939. this.unrenderNowIndicator();
  6940. this.isNowIndicatorRendered = false;
  6941. }
  6942. },
  6943. // Returns a string unit, like 'second' or 'minute' that defined how often the current time indicator
  6944. // should be refreshed. If something falsy is returned, no time indicator is rendered at all.
  6945. getNowIndicatorUnit: function() {
  6946. // subclasses should implement
  6947. },
  6948. // Renders a current time indicator at the given datetime
  6949. renderNowIndicator: function(date) {
  6950. // subclasses should implement
  6951. },
  6952. // Undoes the rendering actions from renderNowIndicator
  6953. unrenderNowIndicator: function() {
  6954. // subclasses should implement
  6955. },
  6956. /* Dimensions
  6957. ------------------------------------------------------------------------------------------------------------------*/
  6958. // Refreshes anything dependant upon sizing of the container element of the grid
  6959. updateSize: function(isResize) {
  6960. if (isResize) {
  6961. this.captureScroll();
  6962. }
  6963. this.updateHeight(isResize);
  6964. this.updateWidth(isResize);
  6965. this.updateNowIndicator();
  6966. if (isResize) {
  6967. this.releaseScroll();
  6968. }
  6969. },
  6970. // Refreshes the horizontal dimensions of the calendar
  6971. updateWidth: function(isResize) {
  6972. // subclasses should implement
  6973. },
  6974. // Refreshes the vertical dimensions of the calendar
  6975. updateHeight: function(isResize) {
  6976. var calendar = this.calendar; // we poll the calendar for height information
  6977. this.setHeight(
  6978. calendar.getSuggestedViewHeight(),
  6979. calendar.isHeightAuto()
  6980. );
  6981. },
  6982. // Updates the vertical dimensions of the calendar to the specified height.
  6983. // if `isAuto` is set to true, height becomes merely a suggestion and the view should use its "natural" height.
  6984. setHeight: function(height, isAuto) {
  6985. // subclasses should implement
  6986. },
  6987. /* Scroller
  6988. ------------------------------------------------------------------------------------------------------------------*/
  6989. capturedScroll: null,
  6990. capturedScrollDepth: 0,
  6991. captureScroll: function() {
  6992. if (!(this.capturedScrollDepth++)) {
  6993. this.capturedScroll = this.isDateRendered ? this.queryScroll() : {}; // require a render first
  6994. return true; // root?
  6995. }
  6996. return false;
  6997. },
  6998. captureInitialScroll: function(forcedScroll) {
  6999. if (this.captureScroll()) { // root?
  7000. this.capturedScroll.isInitial = true;
  7001. if (forcedScroll) {
  7002. $.extend(this.capturedScroll, forcedScroll);
  7003. }
  7004. else {
  7005. this.capturedScroll.isComputed = true;
  7006. }
  7007. }
  7008. },
  7009. releaseScroll: function() {
  7010. var scroll = this.capturedScroll;
  7011. var isRoot = this.discardScroll();
  7012. if (scroll.isComputed) {
  7013. if (isRoot) {
  7014. // only compute initial scroll if it will actually be used (is the root capture)
  7015. $.extend(scroll, this.computeInitialScroll());
  7016. }
  7017. else {
  7018. scroll = null; // scroll couldn't be computed. don't apply it to the DOM
  7019. }
  7020. }
  7021. if (scroll) {
  7022. // we act immediately on a releaseScroll operation, as opposed to captureScroll.
  7023. // if capture/release wraps a render operation that screws up the scroll,
  7024. // we still want to restore it a good state after, regardless of depth.
  7025. if (scroll.isInitial) {
  7026. this.hardSetScroll(scroll); // outsmart how browsers set scroll on initial DOM
  7027. }
  7028. else {
  7029. this.setScroll(scroll);
  7030. }
  7031. }
  7032. },
  7033. discardScroll: function() {
  7034. if (!(--this.capturedScrollDepth)) {
  7035. this.capturedScroll = null;
  7036. return true; // root?
  7037. }
  7038. return false;
  7039. },
  7040. computeInitialScroll: function() {
  7041. return {};
  7042. },
  7043. queryScroll: function() {
  7044. return {};
  7045. },
  7046. hardSetScroll: function(scroll) {
  7047. var _this = this;
  7048. var exec = function() { _this.setScroll(scroll); };
  7049. exec();
  7050. setTimeout(exec, 0); // to surely clear the browser's initial scroll for the DOM
  7051. },
  7052. setScroll: function(scroll) {
  7053. },
  7054. /* Height Freezing
  7055. ------------------------------------------------------------------------------------------------------------------*/
  7056. freezeHeight: function() {
  7057. this.calendar.freezeContentHeight();
  7058. },
  7059. thawHeight: function() {
  7060. this.calendar.thawContentHeight();
  7061. },
  7062. // Event Binding/Unbinding
  7063. // -----------------------------------------------------------------------------------------------------------------
  7064. bindEvents: function() {
  7065. var _this = this;
  7066. if (!this.isEventsBound) {
  7067. this.isEventsBound = true;
  7068. this.rejectOn('eventsUnbind', this.requestEvents()).then(function(events) { // TODO: test rejection
  7069. _this.listenTo(_this.calendar, 'eventsReset', _this.setEvents);
  7070. _this.setEvents(events);
  7071. });
  7072. }
  7073. },
  7074. unbindEvents: function() {
  7075. if (this.isEventsBound) {
  7076. this.isEventsBound = false;
  7077. this.stopListeningTo(this.calendar, 'eventsReset');
  7078. this.unsetEvents();
  7079. this.trigger('eventsUnbind');
  7080. }
  7081. },
  7082. // Event Setting/Unsetting
  7083. // -----------------------------------------------------------------------------------------------------------------
  7084. setEvents: function(events) {
  7085. var isReset = this.isEventSet;
  7086. this.isEventsSet = true;
  7087. this.handleEvents(events, isReset);
  7088. this.trigger(isReset ? 'eventsReset' : 'eventsSet', events);
  7089. },
  7090. unsetEvents: function() {
  7091. if (this.isEventsSet) {
  7092. this.isEventsSet = false;
  7093. this.handleEventsUnset();
  7094. this.trigger('eventsUnset');
  7095. }
  7096. },
  7097. whenEventsSet: function() {
  7098. var _this = this;
  7099. if (this.isEventsSet) {
  7100. return Promise.resolve(this.getCurrentEvents());
  7101. }
  7102. else {
  7103. return new Promise(function(resolve) {
  7104. _this.one('eventsSet', resolve);
  7105. });
  7106. }
  7107. },
  7108. // Event Handling
  7109. // -----------------------------------------------------------------------------------------------------------------
  7110. handleEvents: function(events, isReset) {
  7111. this.requestEventsRender(events);
  7112. },
  7113. handleEventsUnset: function() {
  7114. this.requestEventsUnrender();
  7115. },
  7116. // Event Render Queuing
  7117. // -----------------------------------------------------------------------------------------------------------------
  7118. // assumes any previous event renders have been cleared already
  7119. requestEventsRender: function(events) {
  7120. var _this = this;
  7121. return this.eventRenderQueue.add(function() { // might not return a promise if debounced!? bad
  7122. return _this.executeEventsRender(events);
  7123. });
  7124. },
  7125. requestEventsUnrender: function() {
  7126. var _this = this;
  7127. if (this.isEventsRendered) {
  7128. return this.eventRenderQueue.addQuickly(function() {
  7129. return _this.executeEventsUnrender();
  7130. });
  7131. }
  7132. else {
  7133. return Promise.resolve();
  7134. }
  7135. },
  7136. requestCurrentEventsRender: function() {
  7137. if (this.isEventsSet) {
  7138. this.requestEventsRender(this.getCurrentEvents());
  7139. }
  7140. else {
  7141. return Promise.reject();
  7142. }
  7143. },
  7144. // Event High-level Rendering
  7145. // -----------------------------------------------------------------------------------------------------------------
  7146. executeEventsRender: function(events) {
  7147. var _this = this;
  7148. this.captureScroll();
  7149. this.freezeHeight();
  7150. return this.executeEventsUnrender().then(function() {
  7151. _this.renderEvents(events);
  7152. _this.thawHeight();
  7153. _this.releaseScroll();
  7154. _this.isEventsRendered = true;
  7155. _this.onEventsRender();
  7156. _this.trigger('eventsRender');
  7157. });
  7158. },
  7159. executeEventsUnrender: function() {
  7160. if (this.isEventsRendered) {
  7161. this.onBeforeEventsUnrender();
  7162. this.captureScroll();
  7163. this.freezeHeight();
  7164. if (this.destroyEvents) {
  7165. this.destroyEvents(); // TODO: deprecate
  7166. }
  7167. this.unrenderEvents();
  7168. this.thawHeight();
  7169. this.releaseScroll();
  7170. this.isEventsRendered = false;
  7171. this.trigger('eventsUnrender');
  7172. }
  7173. return Promise.resolve(); // always synchronous
  7174. },
  7175. // Event Rendering Triggers
  7176. // -----------------------------------------------------------------------------------------------------------------
  7177. // Signals that all events have been rendered
  7178. onEventsRender: function() {
  7179. this.renderedEventSegEach(function(seg) {
  7180. this.publiclyTrigger('eventAfterRender', seg.event, seg.event, seg.el);
  7181. });
  7182. this.publiclyTrigger('eventAfterAllRender');
  7183. },
  7184. // Signals that all event elements are about to be removed
  7185. onBeforeEventsUnrender: function() {
  7186. this.renderedEventSegEach(function(seg) {
  7187. this.publiclyTrigger('eventDestroy', seg.event, seg.event, seg.el);
  7188. });
  7189. },
  7190. // Event Low-level Rendering
  7191. // -----------------------------------------------------------------------------------------------------------------
  7192. // Renders the events onto the view.
  7193. renderEvents: function(events) {
  7194. // subclasses should implement
  7195. },
  7196. // Removes event elements from the view.
  7197. unrenderEvents: function() {
  7198. // subclasses should implement
  7199. },
  7200. // Event Data Access
  7201. // -----------------------------------------------------------------------------------------------------------------
  7202. requestEvents: function() {
  7203. return this.calendar.requestEvents(this.start, this.end);
  7204. },
  7205. getCurrentEvents: function() {
  7206. return this.calendar.getPrunedEventCache();
  7207. },
  7208. // Event Rendering Utils
  7209. // -----------------------------------------------------------------------------------------------------------------
  7210. // Given an event and the default element used for rendering, returns the element that should actually be used.
  7211. // Basically runs events and elements through the eventRender hook.
  7212. resolveEventEl: function(event, el) {
  7213. var custom = this.publiclyTrigger('eventRender', event, event, el);
  7214. if (custom === false) { // means don't render at all
  7215. el = null;
  7216. }
  7217. else if (custom && custom !== true) {
  7218. el = $(custom);
  7219. }
  7220. return el;
  7221. },
  7222. // Hides all rendered event segments linked to the given event
  7223. showEvent: function(event) {
  7224. this.renderedEventSegEach(function(seg) {
  7225. seg.el.css('visibility', '');
  7226. }, event);
  7227. },
  7228. // Shows all rendered event segments linked to the given event
  7229. hideEvent: function(event) {
  7230. this.renderedEventSegEach(function(seg) {
  7231. seg.el.css('visibility', 'hidden');
  7232. }, event);
  7233. },
  7234. // Iterates through event segments that have been rendered (have an el). Goes through all by default.
  7235. // If the optional `event` argument is specified, only iterates through segments linked to that event.
  7236. // The `this` value of the callback function will be the view.
  7237. renderedEventSegEach: function(func, event) {
  7238. var segs = this.getEventSegs();
  7239. var i;
  7240. for (i = 0; i < segs.length; i++) {
  7241. if (!event || segs[i].event._id === event._id) {
  7242. if (segs[i].el) {
  7243. func.call(this, segs[i]);
  7244. }
  7245. }
  7246. }
  7247. },
  7248. // Retrieves all the rendered segment objects for the view
  7249. getEventSegs: function() {
  7250. // subclasses must implement
  7251. return [];
  7252. },
  7253. /* Event Drag-n-Drop
  7254. ------------------------------------------------------------------------------------------------------------------*/
  7255. // Computes if the given event is allowed to be dragged by the user
  7256. isEventDraggable: function(event) {
  7257. return this.isEventStartEditable(event);
  7258. },
  7259. isEventStartEditable: function(event) {
  7260. return firstDefined(
  7261. event.startEditable,
  7262. (event.source || {}).startEditable,
  7263. this.opt('eventStartEditable'),
  7264. this.isEventGenerallyEditable(event)
  7265. );
  7266. },
  7267. isEventGenerallyEditable: function(event) {
  7268. return firstDefined(
  7269. event.editable,
  7270. (event.source || {}).editable,
  7271. this.opt('editable')
  7272. );
  7273. },
  7274. // Must be called when an event in the view is dropped onto new location.
  7275. // `dropLocation` is an object that contains the new zoned start/end/allDay values for the event.
  7276. reportSegDrop: function(seg, dropLocation, largeUnit, el, ev) {
  7277. var calendar = this.calendar;
  7278. var mutateResult = calendar.mutateSeg(seg, dropLocation, largeUnit);
  7279. var undoFunc = function() {
  7280. mutateResult.undo();
  7281. calendar.reportEventChange();
  7282. };
  7283. this.triggerEventDrop(seg.event, mutateResult.dateDelta, undoFunc, el, ev);
  7284. calendar.reportEventChange(); // will rerender events
  7285. },
  7286. // Triggers event-drop handlers that have subscribed via the API
  7287. triggerEventDrop: function(event, dateDelta, undoFunc, el, ev) {
  7288. this.publiclyTrigger('eventDrop', el[0], event, dateDelta, undoFunc, ev, {}); // {} = jqui dummy
  7289. },
  7290. /* External Element Drag-n-Drop
  7291. ------------------------------------------------------------------------------------------------------------------*/
  7292. // Must be called when an external element, via jQuery UI, has been dropped onto the calendar.
  7293. // `meta` is the parsed data that has been embedded into the dragging event.
  7294. // `dropLocation` is an object that contains the new zoned start/end/allDay values for the event.
  7295. reportExternalDrop: function(meta, dropLocation, el, ev, ui) {
  7296. var eventProps = meta.eventProps;
  7297. var eventInput;
  7298. var event;
  7299. // Try to build an event object and render it. TODO: decouple the two
  7300. if (eventProps) {
  7301. eventInput = $.extend({}, eventProps, dropLocation);
  7302. event = this.calendar.renderEvent(eventInput, meta.stick)[0]; // renderEvent returns an array
  7303. }
  7304. this.triggerExternalDrop(event, dropLocation, el, ev, ui);
  7305. },
  7306. // Triggers external-drop handlers that have subscribed via the API
  7307. triggerExternalDrop: function(event, dropLocation, el, ev, ui) {
  7308. // trigger 'drop' regardless of whether element represents an event
  7309. this.publiclyTrigger('drop', el[0], dropLocation.start, ev, ui);
  7310. if (event) {
  7311. this.publiclyTrigger('eventReceive', null, event); // signal an external event landed
  7312. }
  7313. },
  7314. /* Drag-n-Drop Rendering (for both events and external elements)
  7315. ------------------------------------------------------------------------------------------------------------------*/
  7316. // Renders a visual indication of a event or external-element drag over the given drop zone.
  7317. // If an external-element, seg will be `null`.
  7318. // Must return elements used for any mock events.
  7319. renderDrag: function(dropLocation, seg) {
  7320. // subclasses must implement
  7321. },
  7322. // Unrenders a visual indication of an event or external-element being dragged.
  7323. unrenderDrag: function() {
  7324. // subclasses must implement
  7325. },
  7326. /* Event Resizing
  7327. ------------------------------------------------------------------------------------------------------------------*/
  7328. // Computes if the given event is allowed to be resized from its starting edge
  7329. isEventResizableFromStart: function(event) {
  7330. return this.opt('eventResizableFromStart') && this.isEventResizable(event);
  7331. },
  7332. // Computes if the given event is allowed to be resized from its ending edge
  7333. isEventResizableFromEnd: function(event) {
  7334. return this.isEventResizable(event);
  7335. },
  7336. // Computes if the given event is allowed to be resized by the user at all
  7337. isEventResizable: function(event) {
  7338. var source = event.source || {};
  7339. return firstDefined(
  7340. event.durationEditable,
  7341. source.durationEditable,
  7342. this.opt('eventDurationEditable'),
  7343. event.editable,
  7344. source.editable,
  7345. this.opt('editable')
  7346. );
  7347. },
  7348. // Must be called when an event in the view has been resized to a new length
  7349. reportSegResize: function(seg, resizeLocation, largeUnit, el, ev) {
  7350. var calendar = this.calendar;
  7351. var mutateResult = calendar.mutateSeg(seg, resizeLocation, largeUnit);
  7352. var undoFunc = function() {
  7353. mutateResult.undo();
  7354. calendar.reportEventChange();
  7355. };
  7356. this.triggerEventResize(seg.event, mutateResult.durationDelta, undoFunc, el, ev);
  7357. calendar.reportEventChange(); // will rerender events
  7358. },
  7359. // Triggers event-resize handlers that have subscribed via the API
  7360. triggerEventResize: function(event, durationDelta, undoFunc, el, ev) {
  7361. this.publiclyTrigger('eventResize', el[0], event, durationDelta, undoFunc, ev, {}); // {} = jqui dummy
  7362. },
  7363. /* Selection (time range)
  7364. ------------------------------------------------------------------------------------------------------------------*/
  7365. // Selects a date span on the view. `start` and `end` are both Moments.
  7366. // `ev` is the native mouse event that begin the interaction.
  7367. select: function(span, ev) {
  7368. this.unselect(ev);
  7369. this.renderSelection(span);
  7370. this.reportSelection(span, ev);
  7371. },
  7372. // Renders a visual indication of the selection
  7373. renderSelection: function(span) {
  7374. // subclasses should implement
  7375. },
  7376. // Called when a new selection is made. Updates internal state and triggers handlers.
  7377. reportSelection: function(span, ev) {
  7378. this.isSelected = true;
  7379. this.triggerSelect(span, ev);
  7380. },
  7381. // Triggers handlers to 'select'
  7382. triggerSelect: function(span, ev) {
  7383. this.publiclyTrigger(
  7384. 'select',
  7385. null,
  7386. this.calendar.applyTimezone(span.start), // convert to calendar's tz for external API
  7387. this.calendar.applyTimezone(span.end), // "
  7388. ev
  7389. );
  7390. },
  7391. // Undoes a selection. updates in the internal state and triggers handlers.
  7392. // `ev` is the native mouse event that began the interaction.
  7393. unselect: function(ev) {
  7394. if (this.isSelected) {
  7395. this.isSelected = false;
  7396. if (this.destroySelection) {
  7397. this.destroySelection(); // TODO: deprecate
  7398. }
  7399. this.unrenderSelection();
  7400. this.publiclyTrigger('unselect', null, ev);
  7401. }
  7402. },
  7403. // Unrenders a visual indication of selection
  7404. unrenderSelection: function() {
  7405. // subclasses should implement
  7406. },
  7407. /* Event Selection
  7408. ------------------------------------------------------------------------------------------------------------------*/
  7409. selectEvent: function(event) {
  7410. if (!this.selectedEvent || this.selectedEvent !== event) {
  7411. this.unselectEvent();
  7412. this.renderedEventSegEach(function(seg) {
  7413. seg.el.addClass('fc-selected');
  7414. }, event);
  7415. this.selectedEvent = event;
  7416. }
  7417. },
  7418. unselectEvent: function() {
  7419. if (this.selectedEvent) {
  7420. this.renderedEventSegEach(function(seg) {
  7421. seg.el.removeClass('fc-selected');
  7422. }, this.selectedEvent);
  7423. this.selectedEvent = null;
  7424. }
  7425. },
  7426. isEventSelected: function(event) {
  7427. // event references might change on refetchEvents(), while selectedEvent doesn't,
  7428. // so compare IDs
  7429. return this.selectedEvent && this.selectedEvent._id === event._id;
  7430. },
  7431. /* Mouse / Touch Unselecting (time range & event unselection)
  7432. ------------------------------------------------------------------------------------------------------------------*/
  7433. // TODO: move consistently to down/start or up/end?
  7434. // TODO: don't kill previous selection if touch scrolling
  7435. handleDocumentMousedown: function(ev) {
  7436. if (isPrimaryMouseButton(ev)) {
  7437. this.processUnselect(ev);
  7438. }
  7439. },
  7440. processUnselect: function(ev) {
  7441. this.processRangeUnselect(ev);
  7442. this.processEventUnselect(ev);
  7443. },
  7444. processRangeUnselect: function(ev) {
  7445. var ignore;
  7446. // is there a time-range selection?
  7447. if (this.isSelected && this.opt('unselectAuto')) {
  7448. // only unselect if the clicked element is not identical to or inside of an 'unselectCancel' element
  7449. ignore = this.opt('unselectCancel');
  7450. if (!ignore || !$(ev.target).closest(ignore).length) {
  7451. this.unselect(ev);
  7452. }
  7453. }
  7454. },
  7455. processEventUnselect: function(ev) {
  7456. if (this.selectedEvent) {
  7457. if (!$(ev.target).closest('.fc-selected').length) {
  7458. this.unselectEvent();
  7459. }
  7460. }
  7461. },
  7462. /* Day Click
  7463. ------------------------------------------------------------------------------------------------------------------*/
  7464. // Triggers handlers to 'dayClick'
  7465. // Span has start/end of the clicked area. Only the start is useful.
  7466. triggerDayClick: function(span, dayEl, ev) {
  7467. this.publiclyTrigger(
  7468. 'dayClick',
  7469. dayEl,
  7470. this.calendar.applyTimezone(span.start), // convert to calendar's timezone for external API
  7471. ev
  7472. );
  7473. },
  7474. /* Date Utils
  7475. ------------------------------------------------------------------------------------------------------------------*/
  7476. // Initializes internal variables related to calculating hidden days-of-week
  7477. initHiddenDays: function() {
  7478. var hiddenDays = this.opt('hiddenDays') || []; // array of day-of-week indices that are hidden
  7479. var isHiddenDayHash = []; // is the day-of-week hidden? (hash with day-of-week-index -> bool)
  7480. var dayCnt = 0;
  7481. var i;
  7482. if (this.opt('weekends') === false) {
  7483. hiddenDays.push(0, 6); // 0=sunday, 6=saturday
  7484. }
  7485. for (i = 0; i < 7; i++) {
  7486. if (
  7487. !(isHiddenDayHash[i] = $.inArray(i, hiddenDays) !== -1)
  7488. ) {
  7489. dayCnt++;
  7490. }
  7491. }
  7492. if (!dayCnt) {
  7493. throw 'invalid hiddenDays'; // all days were hidden? bad.
  7494. }
  7495. this.isHiddenDayHash = isHiddenDayHash;
  7496. },
  7497. // Is the current day hidden?
  7498. // `day` is a day-of-week index (0-6), or a Moment
  7499. isHiddenDay: function(day) {
  7500. if (moment.isMoment(day)) {
  7501. day = day.day();
  7502. }
  7503. return this.isHiddenDayHash[day];
  7504. },
  7505. // Incrementing the current day until it is no longer a hidden day, returning a copy.
  7506. // If the initial value of `date` is not a hidden day, don't do anything.
  7507. // Pass `isExclusive` as `true` if you are dealing with an end date.
  7508. // `inc` defaults to `1` (increment one day forward each time)
  7509. skipHiddenDays: function(date, inc, isExclusive) {
  7510. var out = date.clone();
  7511. inc = inc || 1;
  7512. while (
  7513. this.isHiddenDayHash[(out.day() + (isExclusive ? inc : 0) + 7) % 7]
  7514. ) {
  7515. out.add(inc, 'days');
  7516. }
  7517. return out;
  7518. },
  7519. // Returns the date range of the full days the given range visually appears to occupy.
  7520. // Returns a new range object.
  7521. computeDayRange: function(range) {
  7522. var startDay = range.start.clone().stripTime(); // the beginning of the day the range starts
  7523. var end = range.end;
  7524. var endDay = null;
  7525. var endTimeMS;
  7526. if (end) {
  7527. endDay = end.clone().stripTime(); // the beginning of the day the range exclusively ends
  7528. endTimeMS = +end.time(); // # of milliseconds into `endDay`
  7529. // If the end time is actually inclusively part of the next day and is equal to or
  7530. // beyond the next day threshold, adjust the end to be the exclusive end of `endDay`.
  7531. // Otherwise, leaving it as inclusive will cause it to exclude `endDay`.
  7532. if (endTimeMS && endTimeMS >= this.nextDayThreshold) {
  7533. endDay.add(1, 'days');
  7534. }
  7535. }
  7536. // If no end was specified, or if it is within `startDay` but not past nextDayThreshold,
  7537. // assign the default duration of one day.
  7538. if (!end || endDay <= startDay) {
  7539. endDay = startDay.clone().add(1, 'days');
  7540. }
  7541. return { start: startDay, end: endDay };
  7542. },
  7543. // Does the given event visually appear to occupy more than one day?
  7544. isMultiDayEvent: function(event) {
  7545. var range = this.computeDayRange(event); // event is range-ish
  7546. return range.end.diff(range.start, 'days') > 1;
  7547. }
  7548. });
  7549. ;;
  7550. /*
  7551. Embodies a div that has potential scrollbars
  7552. */
  7553. var Scroller = FC.Scroller = Class.extend({
  7554. el: null, // the guaranteed outer element
  7555. scrollEl: null, // the element with the scrollbars
  7556. overflowX: null,
  7557. overflowY: null,
  7558. constructor: function(options) {
  7559. options = options || {};
  7560. this.overflowX = options.overflowX || options.overflow || 'auto';
  7561. this.overflowY = options.overflowY || options.overflow || 'auto';
  7562. },
  7563. render: function() {
  7564. this.el = this.renderEl();
  7565. this.applyOverflow();
  7566. },
  7567. renderEl: function() {
  7568. return (this.scrollEl = $('<div class="fc-scroller"></div>'));
  7569. },
  7570. // sets to natural height, unlocks overflow
  7571. clear: function() {
  7572. this.setHeight('auto');
  7573. this.applyOverflow();
  7574. },
  7575. destroy: function() {
  7576. this.el.remove();
  7577. },
  7578. // Overflow
  7579. // -----------------------------------------------------------------------------------------------------------------
  7580. applyOverflow: function() {
  7581. this.scrollEl.css({
  7582. 'overflow-x': this.overflowX,
  7583. 'overflow-y': this.overflowY
  7584. });
  7585. },
  7586. // Causes any 'auto' overflow values to resolves to 'scroll' or 'hidden'.
  7587. // Useful for preserving scrollbar widths regardless of future resizes.
  7588. // Can pass in scrollbarWidths for optimization.
  7589. lockOverflow: function(scrollbarWidths) {
  7590. var overflowX = this.overflowX;
  7591. var overflowY = this.overflowY;
  7592. scrollbarWidths = scrollbarWidths || this.getScrollbarWidths();
  7593. if (overflowX === 'auto') {
  7594. overflowX = (
  7595. scrollbarWidths.top || scrollbarWidths.bottom || // horizontal scrollbars?
  7596. // OR scrolling pane with massless scrollbars?
  7597. this.scrollEl[0].scrollWidth - 1 > this.scrollEl[0].clientWidth
  7598. // subtract 1 because of IE off-by-one issue
  7599. ) ? 'scroll' : 'hidden';
  7600. }
  7601. if (overflowY === 'auto') {
  7602. overflowY = (
  7603. scrollbarWidths.left || scrollbarWidths.right || // vertical scrollbars?
  7604. // OR scrolling pane with massless scrollbars?
  7605. this.scrollEl[0].scrollHeight - 1 > this.scrollEl[0].clientHeight
  7606. // subtract 1 because of IE off-by-one issue
  7607. ) ? 'scroll' : 'hidden';
  7608. }
  7609. this.scrollEl.css({ 'overflow-x': overflowX, 'overflow-y': overflowY });
  7610. },
  7611. // Getters / Setters
  7612. // -----------------------------------------------------------------------------------------------------------------
  7613. setHeight: function(height) {
  7614. this.scrollEl.height(height);
  7615. },
  7616. getScrollTop: function() {
  7617. return this.scrollEl.scrollTop();
  7618. },
  7619. setScrollTop: function(top) {
  7620. this.scrollEl.scrollTop(top);
  7621. },
  7622. getClientWidth: function() {
  7623. return this.scrollEl[0].clientWidth;
  7624. },
  7625. getClientHeight: function() {
  7626. return this.scrollEl[0].clientHeight;
  7627. },
  7628. getScrollbarWidths: function() {
  7629. return getScrollbarWidths(this.scrollEl);
  7630. }
  7631. });
  7632. ;;
  7633. function Iterator(items) {
  7634. this.items = items || [];
  7635. }
  7636. /* Calls a method on every item passing the arguments through */
  7637. Iterator.prototype.proxyCall = function(methodName) {
  7638. var args = Array.prototype.slice.call(arguments, 1);
  7639. var results = [];
  7640. this.items.forEach(function(item) {
  7641. results.push(item[methodName].apply(item, args));
  7642. });
  7643. return results;
  7644. };
  7645. ;;
  7646. /* Toolbar with buttons and title
  7647. ----------------------------------------------------------------------------------------------------------------------*/
  7648. function Toolbar(calendar, toolbarOptions) {
  7649. var t = this;
  7650. // exports
  7651. t.setToolbarOptions = setToolbarOptions;
  7652. t.render = render;
  7653. t.removeElement = removeElement;
  7654. t.updateTitle = updateTitle;
  7655. t.activateButton = activateButton;
  7656. t.deactivateButton = deactivateButton;
  7657. t.disableButton = disableButton;
  7658. t.enableButton = enableButton;
  7659. t.getViewsWithButtons = getViewsWithButtons;
  7660. t.el = null; // mirrors local `el`
  7661. // locals
  7662. var el;
  7663. var viewsWithButtons = [];
  7664. var tm;
  7665. // method to update toolbar-specific options, not calendar-wide options
  7666. function setToolbarOptions(newToolbarOptions) {
  7667. toolbarOptions = newToolbarOptions;
  7668. }
  7669. // can be called repeatedly and will rerender
  7670. function render() {
  7671. var sections = toolbarOptions.layout;
  7672. tm = calendar.options.theme ? 'ui' : 'fc';
  7673. if (sections) {
  7674. if (!el) {
  7675. el = this.el = $("<div class='fc-toolbar "+ toolbarOptions.extraClasses + "'/>");
  7676. }
  7677. else {
  7678. el.empty();
  7679. }
  7680. el.append(renderSection('left'))
  7681. .append(renderSection('right'))
  7682. .append(renderSection('center'))
  7683. .append('<div class="fc-clear"/>');
  7684. }
  7685. else {
  7686. removeElement();
  7687. }
  7688. }
  7689. function removeElement() {
  7690. if (el) {
  7691. el.remove();
  7692. el = t.el = null;
  7693. }
  7694. }
  7695. function renderSection(position) {
  7696. var sectionEl = $('<div class="fc-' + position + '"/>');
  7697. var buttonStr = toolbarOptions.layout[position];
  7698. if (buttonStr) {
  7699. $.each(buttonStr.split(' '), function(i) {
  7700. var groupChildren = $();
  7701. var isOnlyButtons = true;
  7702. var groupEl;
  7703. $.each(this.split(','), function(j, buttonName) {
  7704. var customButtonProps;
  7705. var viewSpec;
  7706. var buttonClick;
  7707. var overrideText; // text explicitly set by calendar's constructor options. overcomes icons
  7708. var defaultText;
  7709. var themeIcon;
  7710. var normalIcon;
  7711. var innerHtml;
  7712. var classes;
  7713. var button; // the element
  7714. if (buttonName == 'title') {
  7715. groupChildren = groupChildren.add($('<h2>&nbsp;</h2>')); // we always want it to take up height
  7716. isOnlyButtons = false;
  7717. }
  7718. else {
  7719. if ((customButtonProps = (calendar.options.customButtons || {})[buttonName])) {
  7720. buttonClick = function(ev) {
  7721. if (customButtonProps.click) {
  7722. customButtonProps.click.call(button[0], ev);
  7723. }
  7724. };
  7725. overrideText = ''; // icons will override text
  7726. defaultText = customButtonProps.text;
  7727. }
  7728. else if ((viewSpec = calendar.getViewSpec(buttonName))) {
  7729. buttonClick = function() {
  7730. calendar.changeView(buttonName);
  7731. };
  7732. viewsWithButtons.push(buttonName);
  7733. overrideText = viewSpec.buttonTextOverride;
  7734. defaultText = viewSpec.buttonTextDefault;
  7735. }
  7736. else if (calendar[buttonName]) { // a calendar method
  7737. buttonClick = function() {
  7738. calendar[buttonName]();
  7739. };
  7740. overrideText = (calendar.overrides.buttonText || {})[buttonName];
  7741. defaultText = calendar.options.buttonText[buttonName]; // everything else is considered default
  7742. }
  7743. if (buttonClick) {
  7744. themeIcon =
  7745. customButtonProps ?
  7746. customButtonProps.themeIcon :
  7747. calendar.options.themeButtonIcons[buttonName];
  7748. normalIcon =
  7749. customButtonProps ?
  7750. customButtonProps.icon :
  7751. calendar.options.buttonIcons[buttonName];
  7752. if (overrideText) {
  7753. innerHtml = htmlEscape(overrideText);
  7754. }
  7755. else if (themeIcon && calendar.options.theme) {
  7756. innerHtml = "<span class='ui-icon ui-icon-" + themeIcon + "'></span>";
  7757. }
  7758. else if (normalIcon && !calendar.options.theme) {
  7759. innerHtml = "<span class='fc-icon fc-icon-" + normalIcon + "'></span>";
  7760. }
  7761. else {
  7762. innerHtml = htmlEscape(defaultText);
  7763. }
  7764. classes = [
  7765. 'fc-' + buttonName + '-button',
  7766. tm + '-button',
  7767. tm + '-state-default'
  7768. ];
  7769. button = $( // type="button" so that it doesn't submit a form
  7770. '<button type="button" class="' + classes.join(' ') + '">' +
  7771. innerHtml +
  7772. '</button>'
  7773. )
  7774. .click(function(ev) {
  7775. // don't process clicks for disabled buttons
  7776. if (!button.hasClass(tm + '-state-disabled')) {
  7777. buttonClick(ev);
  7778. // after the click action, if the button becomes the "active" tab, or disabled,
  7779. // it should never have a hover class, so remove it now.
  7780. if (
  7781. button.hasClass(tm + '-state-active') ||
  7782. button.hasClass(tm + '-state-disabled')
  7783. ) {
  7784. button.removeClass(tm + '-state-hover');
  7785. }
  7786. }
  7787. })
  7788. .mousedown(function() {
  7789. // the *down* effect (mouse pressed in).
  7790. // only on buttons that are not the "active" tab, or disabled
  7791. button
  7792. .not('.' + tm + '-state-active')
  7793. .not('.' + tm + '-state-disabled')
  7794. .addClass(tm + '-state-down');
  7795. })
  7796. .mouseup(function() {
  7797. // undo the *down* effect
  7798. button.removeClass(tm + '-state-down');
  7799. })
  7800. .hover(
  7801. function() {
  7802. // the *hover* effect.
  7803. // only on buttons that are not the "active" tab, or disabled
  7804. button
  7805. .not('.' + tm + '-state-active')
  7806. .not('.' + tm + '-state-disabled')
  7807. .addClass(tm + '-state-hover');
  7808. },
  7809. function() {
  7810. // undo the *hover* effect
  7811. button
  7812. .removeClass(tm + '-state-hover')
  7813. .removeClass(tm + '-state-down'); // if mouseleave happens before mouseup
  7814. }
  7815. );
  7816. groupChildren = groupChildren.add(button);
  7817. }
  7818. }
  7819. });
  7820. if (isOnlyButtons) {
  7821. groupChildren
  7822. .first().addClass(tm + '-corner-left').end()
  7823. .last().addClass(tm + '-corner-right').end();
  7824. }
  7825. if (groupChildren.length > 1) {
  7826. groupEl = $('<div/>');
  7827. if (isOnlyButtons) {
  7828. groupEl.addClass('fc-button-group');
  7829. }
  7830. groupEl.append(groupChildren);
  7831. sectionEl.append(groupEl);
  7832. }
  7833. else {
  7834. sectionEl.append(groupChildren); // 1 or 0 children
  7835. }
  7836. });
  7837. }
  7838. return sectionEl;
  7839. }
  7840. function updateTitle(text) {
  7841. if (el) {
  7842. el.find('h2').text(text);
  7843. }
  7844. }
  7845. function activateButton(buttonName) {
  7846. if (el) {
  7847. el.find('.fc-' + buttonName + '-button')
  7848. .addClass(tm + '-state-active');
  7849. }
  7850. }
  7851. function deactivateButton(buttonName) {
  7852. if (el) {
  7853. el.find('.fc-' + buttonName + '-button')
  7854. .removeClass(tm + '-state-active');
  7855. }
  7856. }
  7857. function disableButton(buttonName) {
  7858. if (el) {
  7859. el.find('.fc-' + buttonName + '-button')
  7860. .prop('disabled', true)
  7861. .addClass(tm + '-state-disabled');
  7862. }
  7863. }
  7864. function enableButton(buttonName) {
  7865. if (el) {
  7866. el.find('.fc-' + buttonName + '-button')
  7867. .prop('disabled', false)
  7868. .removeClass(tm + '-state-disabled');
  7869. }
  7870. }
  7871. function getViewsWithButtons() {
  7872. return viewsWithButtons;
  7873. }
  7874. }
  7875. ;;
  7876. var Calendar = FC.Calendar = Class.extend({
  7877. dirDefaults: null, // option defaults related to LTR or RTL
  7878. localeDefaults: null, // option defaults related to current locale
  7879. overrides: null, // option overrides given to the fullCalendar constructor
  7880. dynamicOverrides: null, // options set with dynamic setter method. higher precedence than view overrides.
  7881. options: null, // all defaults combined with overrides
  7882. viewSpecCache: null, // cache of view definitions
  7883. view: null, // current View object
  7884. header: null,
  7885. footer: null,
  7886. loadingLevel: 0, // number of simultaneous loading tasks
  7887. // a lot of this class' OOP logic is scoped within this constructor function,
  7888. // but in the future, write individual methods on the prototype.
  7889. constructor: Calendar_constructor,
  7890. // Subclasses can override this for initialization logic after the constructor has been called
  7891. initialize: function() {
  7892. },
  7893. // Computes the flattened options hash for the calendar and assigns to `this.options`.
  7894. // Assumes this.overrides and this.dynamicOverrides have already been initialized.
  7895. populateOptionsHash: function() {
  7896. var locale, localeDefaults;
  7897. var isRTL, dirDefaults;
  7898. locale = firstDefined( // explicit locale option given?
  7899. this.dynamicOverrides.locale,
  7900. this.overrides.locale
  7901. );
  7902. localeDefaults = localeOptionHash[locale];
  7903. if (!localeDefaults) { // explicit locale option not given or invalid?
  7904. locale = Calendar.defaults.locale;
  7905. localeDefaults = localeOptionHash[locale] || {};
  7906. }
  7907. isRTL = firstDefined( // based on options computed so far, is direction RTL?
  7908. this.dynamicOverrides.isRTL,
  7909. this.overrides.isRTL,
  7910. localeDefaults.isRTL,
  7911. Calendar.defaults.isRTL
  7912. );
  7913. dirDefaults = isRTL ? Calendar.rtlDefaults : {};
  7914. this.dirDefaults = dirDefaults;
  7915. this.localeDefaults = localeDefaults;
  7916. this.options = mergeOptions([ // merge defaults and overrides. lowest to highest precedence
  7917. Calendar.defaults, // global defaults
  7918. dirDefaults,
  7919. localeDefaults,
  7920. this.overrides,
  7921. this.dynamicOverrides
  7922. ]);
  7923. populateInstanceComputableOptions(this.options); // fill in gaps with computed options
  7924. },
  7925. // Gets information about how to create a view. Will use a cache.
  7926. getViewSpec: function(viewType) {
  7927. var cache = this.viewSpecCache;
  7928. return cache[viewType] || (cache[viewType] = this.buildViewSpec(viewType));
  7929. },
  7930. // Given a duration singular unit, like "week" or "day", finds a matching view spec.
  7931. // Preference is given to views that have corresponding buttons.
  7932. getUnitViewSpec: function(unit) {
  7933. var viewTypes;
  7934. var i;
  7935. var spec;
  7936. if ($.inArray(unit, intervalUnits) != -1) {
  7937. // put views that have buttons first. there will be duplicates, but oh well
  7938. viewTypes = this.header.getViewsWithButtons(); // TODO: include footer as well?
  7939. $.each(FC.views, function(viewType) { // all views
  7940. viewTypes.push(viewType);
  7941. });
  7942. for (i = 0; i < viewTypes.length; i++) {
  7943. spec = this.getViewSpec(viewTypes[i]);
  7944. if (spec) {
  7945. if (spec.singleUnit == unit) {
  7946. return spec;
  7947. }
  7948. }
  7949. }
  7950. }
  7951. },
  7952. // Builds an object with information on how to create a given view
  7953. buildViewSpec: function(requestedViewType) {
  7954. var viewOverrides = this.overrides.views || {};
  7955. var specChain = []; // for the view. lowest to highest priority
  7956. var defaultsChain = []; // for the view. lowest to highest priority
  7957. var overridesChain = []; // for the view. lowest to highest priority
  7958. var viewType = requestedViewType;
  7959. var spec; // for the view
  7960. var overrides; // for the view
  7961. var duration;
  7962. var unit;
  7963. // iterate from the specific view definition to a more general one until we hit an actual View class
  7964. while (viewType) {
  7965. spec = fcViews[viewType];
  7966. overrides = viewOverrides[viewType];
  7967. viewType = null; // clear. might repopulate for another iteration
  7968. if (typeof spec === 'function') { // TODO: deprecate
  7969. spec = { 'class': spec };
  7970. }
  7971. if (spec) {
  7972. specChain.unshift(spec);
  7973. defaultsChain.unshift(spec.defaults || {});
  7974. duration = duration || spec.duration;
  7975. viewType = viewType || spec.type;
  7976. }
  7977. if (overrides) {
  7978. overridesChain.unshift(overrides); // view-specific option hashes have options at zero-level
  7979. duration = duration || overrides.duration;
  7980. viewType = viewType || overrides.type;
  7981. }
  7982. }
  7983. spec = mergeProps(specChain);
  7984. spec.type = requestedViewType;
  7985. if (!spec['class']) {
  7986. return false;
  7987. }
  7988. if (duration) {
  7989. duration = moment.duration(duration);
  7990. if (duration.valueOf()) { // valid?
  7991. spec.duration = duration;
  7992. unit = computeIntervalUnit(duration);
  7993. // view is a single-unit duration, like "week" or "day"
  7994. // incorporate options for this. lowest priority
  7995. if (duration.as(unit) === 1) {
  7996. spec.singleUnit = unit;
  7997. overridesChain.unshift(viewOverrides[unit] || {});
  7998. }
  7999. }
  8000. }
  8001. spec.defaults = mergeOptions(defaultsChain);
  8002. spec.overrides = mergeOptions(overridesChain);
  8003. this.buildViewSpecOptions(spec);
  8004. this.buildViewSpecButtonText(spec, requestedViewType);
  8005. return spec;
  8006. },
  8007. // Builds and assigns a view spec's options object from its already-assigned defaults and overrides
  8008. buildViewSpecOptions: function(spec) {
  8009. spec.options = mergeOptions([ // lowest to highest priority
  8010. Calendar.defaults, // global defaults
  8011. spec.defaults, // view's defaults (from ViewSubclass.defaults)
  8012. this.dirDefaults,
  8013. this.localeDefaults, // locale and dir take precedence over view's defaults!
  8014. this.overrides, // calendar's overrides (options given to constructor)
  8015. spec.overrides, // view's overrides (view-specific options)
  8016. this.dynamicOverrides // dynamically set via setter. highest precedence
  8017. ]);
  8018. populateInstanceComputableOptions(spec.options);
  8019. },
  8020. // Computes and assigns a view spec's buttonText-related options
  8021. buildViewSpecButtonText: function(spec, requestedViewType) {
  8022. // given an options object with a possible `buttonText` hash, lookup the buttonText for the
  8023. // requested view, falling back to a generic unit entry like "week" or "day"
  8024. function queryButtonText(options) {
  8025. var buttonText = options.buttonText || {};
  8026. return buttonText[requestedViewType] ||
  8027. // view can decide to look up a certain key
  8028. (spec.buttonTextKey ? buttonText[spec.buttonTextKey] : null) ||
  8029. // a key like "month"
  8030. (spec.singleUnit ? buttonText[spec.singleUnit] : null);
  8031. }
  8032. // highest to lowest priority
  8033. spec.buttonTextOverride =
  8034. queryButtonText(this.dynamicOverrides) ||
  8035. queryButtonText(this.overrides) || // constructor-specified buttonText lookup hash takes precedence
  8036. spec.overrides.buttonText; // `buttonText` for view-specific options is a string
  8037. // highest to lowest priority. mirrors buildViewSpecOptions
  8038. spec.buttonTextDefault =
  8039. queryButtonText(this.localeDefaults) ||
  8040. queryButtonText(this.dirDefaults) ||
  8041. spec.defaults.buttonText || // a single string. from ViewSubclass.defaults
  8042. queryButtonText(Calendar.defaults) ||
  8043. (spec.duration ? this.humanizeDuration(spec.duration) : null) || // like "3 days"
  8044. requestedViewType; // fall back to given view name
  8045. },
  8046. // Given a view name for a custom view or a standard view, creates a ready-to-go View object
  8047. instantiateView: function(viewType) {
  8048. var spec = this.getViewSpec(viewType);
  8049. return new spec['class'](this, viewType, spec.options, spec.duration);
  8050. },
  8051. // Returns a boolean about whether the view is okay to instantiate at some point
  8052. isValidViewType: function(viewType) {
  8053. return Boolean(this.getViewSpec(viewType));
  8054. },
  8055. // Should be called when any type of async data fetching begins
  8056. pushLoading: function() {
  8057. if (!(this.loadingLevel++)) {
  8058. this.publiclyTrigger('loading', null, true, this.view);
  8059. }
  8060. },
  8061. // Should be called when any type of async data fetching completes
  8062. popLoading: function() {
  8063. if (!(--this.loadingLevel)) {
  8064. this.publiclyTrigger('loading', null, false, this.view);
  8065. }
  8066. },
  8067. // Given arguments to the select method in the API, returns a span (unzoned start/end and other info)
  8068. buildSelectSpan: function(zonedStartInput, zonedEndInput) {
  8069. var start = this.moment(zonedStartInput).stripZone();
  8070. var end;
  8071. if (zonedEndInput) {
  8072. end = this.moment(zonedEndInput).stripZone();
  8073. }
  8074. else if (start.hasTime()) {
  8075. end = start.clone().add(this.defaultTimedEventDuration);
  8076. }
  8077. else {
  8078. end = start.clone().add(this.defaultAllDayEventDuration);
  8079. }
  8080. return { start: start, end: end };
  8081. }
  8082. });
  8083. Calendar.mixin(EmitterMixin);
  8084. function Calendar_constructor(element, overrides) {
  8085. var t = this;
  8086. // declare the current calendar instance relies on GlobalEmitter. needed for garbage collection.
  8087. GlobalEmitter.needed();
  8088. // Exports
  8089. // -----------------------------------------------------------------------------------
  8090. t.render = render;
  8091. t.destroy = destroy;
  8092. t.rerenderEvents = rerenderEvents;
  8093. t.changeView = renderView; // `renderView` will switch to another view
  8094. t.select = select;
  8095. t.unselect = unselect;
  8096. t.prev = prev;
  8097. t.next = next;
  8098. t.prevYear = prevYear;
  8099. t.nextYear = nextYear;
  8100. t.today = today;
  8101. t.gotoDate = gotoDate;
  8102. t.incrementDate = incrementDate;
  8103. t.zoomTo = zoomTo;
  8104. t.getDate = getDate;
  8105. t.getCalendar = getCalendar;
  8106. t.getView = getView;
  8107. t.option = option; // getter/setter method
  8108. t.publiclyTrigger = publiclyTrigger;
  8109. // Options
  8110. // -----------------------------------------------------------------------------------
  8111. t.dynamicOverrides = {};
  8112. t.viewSpecCache = {};
  8113. t.optionHandlers = {}; // for Calendar.options.js
  8114. t.overrides = $.extend({}, overrides); // make a copy
  8115. t.populateOptionsHash(); // sets this.options
  8116. // Locale-data Internals
  8117. // -----------------------------------------------------------------------------------
  8118. // Apply overrides to the current locale's data
  8119. var localeData;
  8120. // Called immediately, and when any of the options change.
  8121. // Happens before any internal objects rebuild or rerender, because this is very core.
  8122. t.bindOptions([
  8123. 'locale', 'monthNames', 'monthNamesShort', 'dayNames', 'dayNamesShort', 'firstDay', 'weekNumberCalculation'
  8124. ], function(locale, monthNames, monthNamesShort, dayNames, dayNamesShort, firstDay, weekNumberCalculation) {
  8125. // normalize
  8126. if (weekNumberCalculation === 'iso') {
  8127. weekNumberCalculation = 'ISO'; // normalize
  8128. }
  8129. localeData = createObject( // make a cheap copy
  8130. getMomentLocaleData(locale) // will fall back to en
  8131. );
  8132. if (monthNames) {
  8133. localeData._months = monthNames;
  8134. }
  8135. if (monthNamesShort) {
  8136. localeData._monthsShort = monthNamesShort;
  8137. }
  8138. if (dayNames) {
  8139. localeData._weekdays = dayNames;
  8140. }
  8141. if (dayNamesShort) {
  8142. localeData._weekdaysShort = dayNamesShort;
  8143. }
  8144. if (firstDay == null && weekNumberCalculation === 'ISO') {
  8145. firstDay = 1;
  8146. }
  8147. if (firstDay != null) {
  8148. var _week = createObject(localeData._week); // _week: { dow: # }
  8149. _week.dow = firstDay;
  8150. localeData._week = _week;
  8151. }
  8152. if ( // whitelist certain kinds of input
  8153. weekNumberCalculation === 'ISO' ||
  8154. weekNumberCalculation === 'local' ||
  8155. typeof weekNumberCalculation === 'function'
  8156. ) {
  8157. localeData._fullCalendar_weekCalc = weekNumberCalculation; // moment-ext will know what to do with it
  8158. }
  8159. // If the internal current date object already exists, move to new locale.
  8160. // We do NOT need to do this technique for event dates, because this happens when converting to "segments".
  8161. if (date) {
  8162. localizeMoment(date); // sets to localeData
  8163. }
  8164. });
  8165. // Calendar-specific Date Utilities
  8166. // -----------------------------------------------------------------------------------
  8167. t.defaultAllDayEventDuration = moment.duration(t.options.defaultAllDayEventDuration);
  8168. t.defaultTimedEventDuration = moment.duration(t.options.defaultTimedEventDuration);
  8169. // Builds a moment using the settings of the current calendar: timezone and locale.
  8170. // Accepts anything the vanilla moment() constructor accepts.
  8171. t.moment = function() {
  8172. var mom;
  8173. if (t.options.timezone === 'local') {
  8174. mom = FC.moment.apply(null, arguments);
  8175. // Force the moment to be local, because FC.moment doesn't guarantee it.
  8176. if (mom.hasTime()) { // don't give ambiguously-timed moments a local zone
  8177. mom.local();
  8178. }
  8179. }
  8180. else if (t.options.timezone === 'UTC') {
  8181. mom = FC.moment.utc.apply(null, arguments); // process as UTC
  8182. }
  8183. else {
  8184. mom = FC.moment.parseZone.apply(null, arguments); // let the input decide the zone
  8185. }
  8186. localizeMoment(mom);
  8187. return mom;
  8188. };
  8189. // Updates the given moment's locale settings to the current calendar locale settings.
  8190. function localizeMoment(mom) {
  8191. mom._locale = localeData;
  8192. }
  8193. t.localizeMoment = localizeMoment;
  8194. // Returns a boolean about whether or not the calendar knows how to calculate
  8195. // the timezone offset of arbitrary dates in the current timezone.
  8196. t.getIsAmbigTimezone = function() {
  8197. return t.options.timezone !== 'local' && t.options.timezone !== 'UTC';
  8198. };
  8199. // Returns a copy of the given date in the current timezone. Has no effect on dates without times.
  8200. t.applyTimezone = function(date) {
  8201. if (!date.hasTime()) {
  8202. return date.clone();
  8203. }
  8204. var zonedDate = t.moment(date.toArray());
  8205. var timeAdjust = date.time() - zonedDate.time();
  8206. var adjustedZonedDate;
  8207. // Safari sometimes has problems with this coersion when near DST. Adjust if necessary. (bug #2396)
  8208. if (timeAdjust) { // is the time result different than expected?
  8209. adjustedZonedDate = zonedDate.clone().add(timeAdjust); // add milliseconds
  8210. if (date.time() - adjustedZonedDate.time() === 0) { // does it match perfectly now?
  8211. zonedDate = adjustedZonedDate;
  8212. }
  8213. }
  8214. return zonedDate;
  8215. };
  8216. // Returns a moment for the current date, as defined by the client's computer or from the `now` option.
  8217. // Will return an moment with an ambiguous timezone.
  8218. t.getNow = function() {
  8219. var now = t.options.now;
  8220. if (typeof now === 'function') {
  8221. now = now();
  8222. }
  8223. return t.moment(now).stripZone();
  8224. };
  8225. // Get an event's normalized end date. If not present, calculate it from the defaults.
  8226. t.getEventEnd = function(event) {
  8227. if (event.end) {
  8228. return event.end.clone();
  8229. }
  8230. else {
  8231. return t.getDefaultEventEnd(event.allDay, event.start);
  8232. }
  8233. };
  8234. // Given an event's allDay status and start date, return what its fallback end date should be.
  8235. // TODO: rename to computeDefaultEventEnd
  8236. t.getDefaultEventEnd = function(allDay, zonedStart) {
  8237. var end = zonedStart.clone();
  8238. if (allDay) {
  8239. end.stripTime().add(t.defaultAllDayEventDuration);
  8240. }
  8241. else {
  8242. end.add(t.defaultTimedEventDuration);
  8243. }
  8244. if (t.getIsAmbigTimezone()) {
  8245. end.stripZone(); // we don't know what the tzo should be
  8246. }
  8247. return end;
  8248. };
  8249. // Produces a human-readable string for the given duration.
  8250. // Side-effect: changes the locale of the given duration.
  8251. t.humanizeDuration = function(duration) {
  8252. return duration.locale(t.options.locale).humanize();
  8253. };
  8254. // Imports
  8255. // -----------------------------------------------------------------------------------
  8256. EventManager.call(t);
  8257. // Locals
  8258. // -----------------------------------------------------------------------------------
  8259. var _element = element[0];
  8260. var toolbarsManager;
  8261. var header;
  8262. var footer;
  8263. var content;
  8264. var tm; // for making theme classes
  8265. var currentView; // NOTE: keep this in sync with this.view
  8266. var viewsByType = {}; // holds all instantiated view instances, current or not
  8267. var suggestedViewHeight;
  8268. var windowResizeProxy; // wraps the windowResize function
  8269. var ignoreWindowResize = 0;
  8270. var date; // unzoned
  8271. // Main Rendering
  8272. // -----------------------------------------------------------------------------------
  8273. // compute the initial ambig-timezone date
  8274. if (t.options.defaultDate != null) {
  8275. date = t.moment(t.options.defaultDate).stripZone();
  8276. }
  8277. else {
  8278. date = t.getNow(); // getNow already returns unzoned
  8279. }
  8280. function render() {
  8281. if (!content) {
  8282. initialRender();
  8283. }
  8284. else if (elementVisible()) {
  8285. // mainly for the public API
  8286. calcSize();
  8287. renderView();
  8288. }
  8289. }
  8290. function initialRender() {
  8291. element.addClass('fc');
  8292. // event delegation for nav links
  8293. element.on('click.fc', 'a[data-goto]', function(ev) {
  8294. var anchorEl = $(this);
  8295. var gotoOptions = anchorEl.data('goto'); // will automatically parse JSON
  8296. var date = t.moment(gotoOptions.date);
  8297. var viewType = gotoOptions.type;
  8298. // property like "navLinkDayClick". might be a string or a function
  8299. var customAction = currentView.opt('navLink' + capitaliseFirstLetter(viewType) + 'Click');
  8300. if (typeof customAction === 'function') {
  8301. customAction(date, ev);
  8302. }
  8303. else {
  8304. if (typeof customAction === 'string') {
  8305. viewType = customAction;
  8306. }
  8307. zoomTo(date, viewType);
  8308. }
  8309. });
  8310. // called immediately, and upon option change
  8311. t.bindOption('theme', function(theme) {
  8312. tm = theme ? 'ui' : 'fc'; // affects a larger scope
  8313. element.toggleClass('ui-widget', theme);
  8314. element.toggleClass('fc-unthemed', !theme);
  8315. });
  8316. // called immediately, and upon option change.
  8317. // HACK: locale often affects isRTL, so we explicitly listen to that too.
  8318. t.bindOptions([ 'isRTL', 'locale' ], function(isRTL) {
  8319. element.toggleClass('fc-ltr', !isRTL);
  8320. element.toggleClass('fc-rtl', isRTL);
  8321. });
  8322. content = $("<div class='fc-view-container'/>").prependTo(element);
  8323. var toolbars = buildToolbars();
  8324. toolbarsManager = new Iterator(toolbars);
  8325. header = t.header = toolbars[0];
  8326. footer = t.footer = toolbars[1];
  8327. renderHeader();
  8328. renderFooter();
  8329. renderView(t.options.defaultView);
  8330. if (t.options.handleWindowResize) {
  8331. windowResizeProxy = debounce(windowResize, t.options.windowResizeDelay); // prevents rapid calls
  8332. $(window).resize(windowResizeProxy);
  8333. }
  8334. }
  8335. function destroy() {
  8336. if (currentView) {
  8337. currentView.removeElement();
  8338. // NOTE: don't null-out currentView/t.view in case API methods are called after destroy.
  8339. // It is still the "current" view, just not rendered.
  8340. }
  8341. toolbarsManager.proxyCall('removeElement');
  8342. content.remove();
  8343. element.removeClass('fc fc-ltr fc-rtl fc-unthemed ui-widget');
  8344. element.off('.fc'); // unbind nav link handlers
  8345. if (windowResizeProxy) {
  8346. $(window).unbind('resize', windowResizeProxy);
  8347. }
  8348. GlobalEmitter.unneeded();
  8349. }
  8350. function elementVisible() {
  8351. return element.is(':visible');
  8352. }
  8353. // View Rendering
  8354. // -----------------------------------------------------------------------------------
  8355. // Renders a view because of a date change, view-type change, or for the first time.
  8356. // If not given a viewType, keep the current view but render different dates.
  8357. // Accepts an optional scroll state to restore to.
  8358. function renderView(viewType, forcedScroll) {
  8359. ignoreWindowResize++;
  8360. var needsClearView = currentView && viewType && currentView.type !== viewType;
  8361. // if viewType is changing, remove the old view's rendering
  8362. if (needsClearView) {
  8363. freezeContentHeight(); // prevent a scroll jump when view element is removed
  8364. clearView();
  8365. }
  8366. // if viewType changed, or the view was never created, create a fresh view
  8367. if (!currentView && viewType) {
  8368. currentView = t.view =
  8369. viewsByType[viewType] ||
  8370. (viewsByType[viewType] = t.instantiateView(viewType));
  8371. currentView.setElement(
  8372. $("<div class='fc-view fc-" + viewType + "-view' />").appendTo(content)
  8373. );
  8374. toolbarsManager.proxyCall('activateButton', viewType);
  8375. }
  8376. if (currentView) {
  8377. // in case the view should render a period of time that is completely hidden
  8378. date = currentView.massageCurrentDate(date);
  8379. // render or rerender the view
  8380. if (
  8381. !currentView.isDateSet ||
  8382. !( // NOT within interval range signals an implicit date window change
  8383. date >= currentView.intervalStart &&
  8384. date < currentView.intervalEnd
  8385. )
  8386. ) {
  8387. if (elementVisible()) {
  8388. if (forcedScroll) {
  8389. currentView.captureInitialScroll(forcedScroll);
  8390. }
  8391. currentView.setDate(date, forcedScroll);
  8392. if (forcedScroll) {
  8393. currentView.releaseScroll();
  8394. }
  8395. // need to do this after View::render, so dates are calculated
  8396. // NOTE: view updates title text proactively
  8397. updateToolbarsTodayButton();
  8398. }
  8399. }
  8400. }
  8401. if (needsClearView) {
  8402. thawContentHeight();
  8403. }
  8404. ignoreWindowResize--;
  8405. }
  8406. // Unrenders the current view and reflects this change in the Header.
  8407. // Unregsiters the `currentView`, but does not remove from viewByType hash.
  8408. function clearView() {
  8409. toolbarsManager.proxyCall('deactivateButton', currentView.type);
  8410. currentView.removeElement();
  8411. currentView = t.view = null;
  8412. }
  8413. // Destroys the view, including the view object. Then, re-instantiates it and renders it.
  8414. // Maintains the same scroll state.
  8415. // TODO: maintain any other user-manipulated state.
  8416. function reinitView() {
  8417. ignoreWindowResize++;
  8418. freezeContentHeight();
  8419. var viewType = currentView.type;
  8420. var scrollState = currentView.queryScroll();
  8421. clearView();
  8422. calcSize();
  8423. renderView(viewType, scrollState);
  8424. thawContentHeight();
  8425. ignoreWindowResize--;
  8426. }
  8427. // Resizing
  8428. // -----------------------------------------------------------------------------------
  8429. t.getSuggestedViewHeight = function() {
  8430. if (suggestedViewHeight === undefined) {
  8431. calcSize();
  8432. }
  8433. return suggestedViewHeight;
  8434. };
  8435. t.isHeightAuto = function() {
  8436. return t.options.contentHeight === 'auto' || t.options.height === 'auto';
  8437. };
  8438. function updateSize(shouldRecalc) {
  8439. if (elementVisible()) {
  8440. if (shouldRecalc) {
  8441. _calcSize();
  8442. }
  8443. ignoreWindowResize++;
  8444. currentView.updateSize(true); // isResize=true. will poll getSuggestedViewHeight() and isHeightAuto()
  8445. ignoreWindowResize--;
  8446. return true; // signal success
  8447. }
  8448. }
  8449. function calcSize() {
  8450. if (elementVisible()) {
  8451. _calcSize();
  8452. }
  8453. }
  8454. function _calcSize() { // assumes elementVisible
  8455. var contentHeightInput = t.options.contentHeight;
  8456. var heightInput = t.options.height;
  8457. if (typeof contentHeightInput === 'number') { // exists and not 'auto'
  8458. suggestedViewHeight = contentHeightInput;
  8459. }
  8460. else if (typeof contentHeightInput === 'function') { // exists and is a function
  8461. suggestedViewHeight = contentHeightInput();
  8462. }
  8463. else if (typeof heightInput === 'number') { // exists and not 'auto'
  8464. suggestedViewHeight = heightInput - queryToolbarsHeight();
  8465. }
  8466. else if (typeof heightInput === 'function') { // exists and is a function
  8467. suggestedViewHeight = heightInput() - queryToolbarsHeight();
  8468. }
  8469. else if (heightInput === 'parent') { // set to height of parent element
  8470. suggestedViewHeight = element.parent().height() - queryToolbarsHeight();
  8471. }
  8472. else {
  8473. suggestedViewHeight = Math.round(content.width() / Math.max(t.options.aspectRatio, .5));
  8474. }
  8475. }
  8476. function queryToolbarsHeight() {
  8477. return toolbarsManager.items.reduce(function(accumulator, toolbar) {
  8478. var toolbarHeight = toolbar.el ? toolbar.el.outerHeight(true) : 0; // includes margin
  8479. return accumulator + toolbarHeight;
  8480. }, 0);
  8481. }
  8482. function windowResize(ev) {
  8483. if (
  8484. !ignoreWindowResize &&
  8485. ev.target === window && // so we don't process jqui "resize" events that have bubbled up
  8486. currentView.start // view has already been rendered
  8487. ) {
  8488. if (updateSize(true)) {
  8489. currentView.publiclyTrigger('windowResize', _element);
  8490. }
  8491. }
  8492. }
  8493. /* Event Rendering
  8494. -----------------------------------------------------------------------------*/
  8495. function rerenderEvents() { // API method. destroys old events if previously rendered.
  8496. if (elementVisible()) {
  8497. t.reportEventChange(); // will re-trasmit events to the view, causing a rerender
  8498. }
  8499. }
  8500. /* Toolbars
  8501. -----------------------------------------------------------------------------*/
  8502. function buildToolbars() {
  8503. return [
  8504. new Toolbar(t, computeHeaderOptions()),
  8505. new Toolbar(t, computeFooterOptions())
  8506. ];
  8507. }
  8508. function computeHeaderOptions() {
  8509. return {
  8510. extraClasses: 'fc-header-toolbar',
  8511. layout: t.options.header
  8512. };
  8513. }
  8514. function computeFooterOptions() {
  8515. return {
  8516. extraClasses: 'fc-footer-toolbar',
  8517. layout: t.options.footer
  8518. };
  8519. }
  8520. // can be called repeatedly and Header will rerender
  8521. function renderHeader() {
  8522. header.setToolbarOptions(computeHeaderOptions());
  8523. header.render();
  8524. if (header.el) {
  8525. element.prepend(header.el);
  8526. }
  8527. }
  8528. // can be called repeatedly and Footer will rerender
  8529. function renderFooter() {
  8530. footer.setToolbarOptions(computeFooterOptions());
  8531. footer.render();
  8532. if (footer.el) {
  8533. element.append(footer.el);
  8534. }
  8535. }
  8536. t.setToolbarsTitle = function(title) {
  8537. toolbarsManager.proxyCall('updateTitle', title);
  8538. };
  8539. function updateToolbarsTodayButton() {
  8540. var now = t.getNow();
  8541. if (now >= currentView.intervalStart && now < currentView.intervalEnd) {
  8542. toolbarsManager.proxyCall('disableButton', 'today');
  8543. }
  8544. else {
  8545. toolbarsManager.proxyCall('enableButton', 'today');
  8546. }
  8547. }
  8548. /* Selection
  8549. -----------------------------------------------------------------------------*/
  8550. // this public method receives start/end dates in any format, with any timezone
  8551. function select(zonedStartInput, zonedEndInput) {
  8552. currentView.select(
  8553. t.buildSelectSpan.apply(t, arguments)
  8554. );
  8555. }
  8556. function unselect() { // safe to be called before renderView
  8557. if (currentView) {
  8558. currentView.unselect();
  8559. }
  8560. }
  8561. /* Date
  8562. -----------------------------------------------------------------------------*/
  8563. function prev() {
  8564. date = currentView.computePrevDate(date);
  8565. renderView();
  8566. }
  8567. function next() {
  8568. date = currentView.computeNextDate(date);
  8569. renderView();
  8570. }
  8571. function prevYear() {
  8572. date.add(-1, 'years');
  8573. renderView();
  8574. }
  8575. function nextYear() {
  8576. date.add(1, 'years');
  8577. renderView();
  8578. }
  8579. function today() {
  8580. date = t.getNow();
  8581. renderView();
  8582. }
  8583. function gotoDate(zonedDateInput) {
  8584. date = t.moment(zonedDateInput).stripZone();
  8585. renderView();
  8586. }
  8587. function incrementDate(delta) {
  8588. date.add(moment.duration(delta));
  8589. renderView();
  8590. }
  8591. // Forces navigation to a view for the given date.
  8592. // `viewType` can be a specific view name or a generic one like "week" or "day".
  8593. function zoomTo(newDate, viewType) {
  8594. var spec;
  8595. viewType = viewType || 'day'; // day is default zoom
  8596. spec = t.getViewSpec(viewType) || t.getUnitViewSpec(viewType);
  8597. date = newDate.clone();
  8598. renderView(spec ? spec.type : null);
  8599. }
  8600. // for external API
  8601. function getDate() {
  8602. return t.applyTimezone(date); // infuse the calendar's timezone
  8603. }
  8604. /* Height "Freezing"
  8605. -----------------------------------------------------------------------------*/
  8606. t.freezeContentHeight = freezeContentHeight;
  8607. t.thawContentHeight = thawContentHeight;
  8608. var freezeContentHeightDepth = 0;
  8609. function freezeContentHeight() {
  8610. if (!(freezeContentHeightDepth++)) {
  8611. content.css({
  8612. width: '100%',
  8613. height: content.height(),
  8614. overflow: 'hidden'
  8615. });
  8616. }
  8617. }
  8618. function thawContentHeight() {
  8619. if (!(--freezeContentHeightDepth)) {
  8620. content.css({
  8621. width: '',
  8622. height: '',
  8623. overflow: ''
  8624. });
  8625. }
  8626. }
  8627. /* Misc
  8628. -----------------------------------------------------------------------------*/
  8629. function getCalendar() {
  8630. return t;
  8631. }
  8632. function getView() {
  8633. return currentView;
  8634. }
  8635. function option(name, value) {
  8636. var newOptionHash;
  8637. if (typeof name === 'string') {
  8638. if (value === undefined) { // getter
  8639. return t.options[name];
  8640. }
  8641. else { // setter for individual option
  8642. newOptionHash = {};
  8643. newOptionHash[name] = value;
  8644. setOptions(newOptionHash);
  8645. }
  8646. }
  8647. else if (typeof name === 'object') { // compound setter with object input
  8648. setOptions(name);
  8649. }
  8650. }
  8651. function setOptions(newOptionHash) {
  8652. var optionCnt = 0;
  8653. var optionName;
  8654. for (optionName in newOptionHash) {
  8655. t.dynamicOverrides[optionName] = newOptionHash[optionName];
  8656. }
  8657. t.viewSpecCache = {}; // the dynamic override invalidates the options in this cache, so just clear it
  8658. t.populateOptionsHash(); // this.options needs to be recomputed after the dynamic override
  8659. // trigger handlers after this.options has been updated
  8660. for (optionName in newOptionHash) {
  8661. t.triggerOptionHandlers(optionName); // recall bindOption/bindOptions
  8662. optionCnt++;
  8663. }
  8664. // special-case handling of single option change.
  8665. // if only one option change, `optionName` will be its name.
  8666. if (optionCnt === 1) {
  8667. if (optionName === 'height' || optionName === 'contentHeight' || optionName === 'aspectRatio') {
  8668. updateSize(true); // true = allow recalculation of height
  8669. return;
  8670. }
  8671. else if (optionName === 'defaultDate') {
  8672. return; // can't change date this way. use gotoDate instead
  8673. }
  8674. else if (optionName === 'businessHours') {
  8675. if (currentView) {
  8676. currentView.unrenderBusinessHours();
  8677. currentView.renderBusinessHours();
  8678. }
  8679. return;
  8680. }
  8681. else if (optionName === 'timezone') {
  8682. t.rezoneArrayEventSources();
  8683. t.refetchEvents();
  8684. return;
  8685. }
  8686. }
  8687. // catch-all. rerender the header and footer and rebuild/rerender the current view
  8688. renderHeader();
  8689. renderFooter();
  8690. viewsByType = {}; // even non-current views will be affected by this option change. do before rerender
  8691. reinitView();
  8692. }
  8693. function publiclyTrigger(name, thisObj) {
  8694. var args = Array.prototype.slice.call(arguments, 2);
  8695. thisObj = thisObj || _element;
  8696. this.triggerWith(name, thisObj, args); // Emitter's method
  8697. if (t.options[name]) {
  8698. return t.options[name].apply(thisObj, args);
  8699. }
  8700. }
  8701. t.initialize();
  8702. }
  8703. ;;
  8704. /*
  8705. Options binding/triggering system.
  8706. */
  8707. Calendar.mixin({
  8708. // A map of option names to arrays of handler objects. Initialized to {} in Calendar.
  8709. // Format for a handler object:
  8710. // {
  8711. // func // callback function to be called upon change
  8712. // names // option names whose values should be given to func
  8713. // }
  8714. optionHandlers: null,
  8715. // Calls handlerFunc immediately, and when the given option has changed.
  8716. // handlerFunc will be given the option value.
  8717. bindOption: function(optionName, handlerFunc) {
  8718. this.bindOptions([ optionName ], handlerFunc);
  8719. },
  8720. // Calls handlerFunc immediately, and when any of the given options change.
  8721. // handlerFunc will be given each option value as ordered function arguments.
  8722. bindOptions: function(optionNames, handlerFunc) {
  8723. var handlerObj = { func: handlerFunc, names: optionNames };
  8724. var i;
  8725. for (i = 0; i < optionNames.length; i++) {
  8726. this.registerOptionHandlerObj(optionNames[i], handlerObj);
  8727. }
  8728. this.triggerOptionHandlerObj(handlerObj);
  8729. },
  8730. // Puts the given handler object into the internal hash
  8731. registerOptionHandlerObj: function(optionName, handlerObj) {
  8732. (this.optionHandlers[optionName] || (this.optionHandlers[optionName] = []))
  8733. .push(handlerObj);
  8734. },
  8735. // Reports that the given option has changed, and calls all appropriate handlers.
  8736. triggerOptionHandlers: function(optionName) {
  8737. var handlerObjs = this.optionHandlers[optionName] || [];
  8738. var i;
  8739. for (i = 0; i < handlerObjs.length; i++) {
  8740. this.triggerOptionHandlerObj(handlerObjs[i]);
  8741. }
  8742. },
  8743. // Calls the callback for a specific handler object, passing in the appropriate arguments.
  8744. triggerOptionHandlerObj: function(handlerObj) {
  8745. var optionNames = handlerObj.names;
  8746. var optionValues = [];
  8747. var i;
  8748. for (i = 0; i < optionNames.length; i++) {
  8749. optionValues.push(this.options[optionNames[i]]);
  8750. }
  8751. handlerObj.func.apply(this, optionValues); // maintain the Calendar's `this` context
  8752. }
  8753. });
  8754. ;;
  8755. Calendar.defaults = {
  8756. titleRangeSeparator: ' \u2013 ', // en dash
  8757. monthYearFormat: 'MMMM YYYY', // required for en. other locales rely on datepicker computable option
  8758. defaultTimedEventDuration: '02:00:00',
  8759. defaultAllDayEventDuration: { days: 1 },
  8760. forceEventDuration: false,
  8761. nextDayThreshold: '09:00:00', // 9am
  8762. // display
  8763. defaultView: 'month',
  8764. aspectRatio: 1.35,
  8765. header: {
  8766. left: 'title',
  8767. center: '',
  8768. right: 'today prev,next'
  8769. },
  8770. weekends: true,
  8771. weekNumbers: false,
  8772. weekNumberTitle: 'W',
  8773. weekNumberCalculation: 'local',
  8774. //editable: false,
  8775. //nowIndicator: false,
  8776. scrollTime: '06:00:00',
  8777. // event ajax
  8778. lazyFetching: true,
  8779. startParam: 'start',
  8780. endParam: 'end',
  8781. timezoneParam: 'timezone',
  8782. timezone: false,
  8783. //allDayDefault: undefined,
  8784. // locale
  8785. isRTL: false,
  8786. buttonText: {
  8787. prev: "prev",
  8788. next: "next",
  8789. prevYear: "prev year",
  8790. nextYear: "next year",
  8791. year: 'year', // TODO: locale files need to specify this
  8792. today: 'today',
  8793. month: 'month',
  8794. week: 'week',
  8795. day: 'day'
  8796. },
  8797. buttonIcons: {
  8798. prev: 'left-single-arrow',
  8799. next: 'right-single-arrow',
  8800. prevYear: 'left-double-arrow',
  8801. nextYear: 'right-double-arrow'
  8802. },
  8803. allDayText: 'all-day',
  8804. // jquery-ui theming
  8805. theme: false,
  8806. themeButtonIcons: {
  8807. prev: 'circle-triangle-w',
  8808. next: 'circle-triangle-e',
  8809. prevYear: 'seek-prev',
  8810. nextYear: 'seek-next'
  8811. },
  8812. //eventResizableFromStart: false,
  8813. dragOpacity: .75,
  8814. dragRevertDuration: 500,
  8815. dragScroll: true,
  8816. //selectable: false,
  8817. unselectAuto: true,
  8818. //selectMinDistance: 0,
  8819. dropAccept: '*',
  8820. eventOrder: 'title',
  8821. //eventRenderWait: null,
  8822. eventLimit: false,
  8823. eventLimitText: 'more',
  8824. eventLimitClick: 'popover',
  8825. dayPopoverFormat: 'LL',
  8826. handleWindowResize: true,
  8827. windowResizeDelay: 100, // milliseconds before an updateSize happens
  8828. longPressDelay: 1000
  8829. };
  8830. Calendar.englishDefaults = { // used by locale.js
  8831. dayPopoverFormat: 'dddd, MMMM D'
  8832. };
  8833. Calendar.rtlDefaults = { // right-to-left defaults
  8834. header: { // TODO: smarter solution (first/center/last ?)
  8835. left: 'next,prev today',
  8836. center: '',
  8837. right: 'title'
  8838. },
  8839. buttonIcons: {
  8840. prev: 'right-single-arrow',
  8841. next: 'left-single-arrow',
  8842. prevYear: 'right-double-arrow',
  8843. nextYear: 'left-double-arrow'
  8844. },
  8845. themeButtonIcons: {
  8846. prev: 'circle-triangle-e',
  8847. next: 'circle-triangle-w',
  8848. nextYear: 'seek-prev',
  8849. prevYear: 'seek-next'
  8850. }
  8851. };
  8852. ;;
  8853. var localeOptionHash = FC.locales = {}; // initialize and expose
  8854. // TODO: document the structure and ordering of a FullCalendar locale file
  8855. // Initialize jQuery UI datepicker translations while using some of the translations
  8856. // Will set this as the default locales for datepicker.
  8857. FC.datepickerLocale = function(localeCode, dpLocaleCode, dpOptions) {
  8858. // get the FullCalendar internal option hash for this locale. create if necessary
  8859. var fcOptions = localeOptionHash[localeCode] || (localeOptionHash[localeCode] = {});
  8860. // transfer some simple options from datepicker to fc
  8861. fcOptions.isRTL = dpOptions.isRTL;
  8862. fcOptions.weekNumberTitle = dpOptions.weekHeader;
  8863. // compute some more complex options from datepicker
  8864. $.each(dpComputableOptions, function(name, func) {
  8865. fcOptions[name] = func(dpOptions);
  8866. });
  8867. // is jQuery UI Datepicker is on the page?
  8868. if ($.datepicker) {
  8869. // Register the locale data.
  8870. // FullCalendar and MomentJS use locale codes like "pt-br" but Datepicker
  8871. // does it like "pt-BR" or if it doesn't have the locale, maybe just "pt".
  8872. // Make an alias so the locale can be referenced either way.
  8873. $.datepicker.regional[dpLocaleCode] =
  8874. $.datepicker.regional[localeCode] = // alias
  8875. dpOptions;
  8876. // Alias 'en' to the default locale data. Do this every time.
  8877. $.datepicker.regional.en = $.datepicker.regional[''];
  8878. // Set as Datepicker's global defaults.
  8879. $.datepicker.setDefaults(dpOptions);
  8880. }
  8881. };
  8882. // Sets FullCalendar-specific translations. Will set the locales as the global default.
  8883. FC.locale = function(localeCode, newFcOptions) {
  8884. var fcOptions;
  8885. var momOptions;
  8886. // get the FullCalendar internal option hash for this locale. create if necessary
  8887. fcOptions = localeOptionHash[localeCode] || (localeOptionHash[localeCode] = {});
  8888. // provided new options for this locales? merge them in
  8889. if (newFcOptions) {
  8890. fcOptions = localeOptionHash[localeCode] = mergeOptions([ fcOptions, newFcOptions ]);
  8891. }
  8892. // compute locale options that weren't defined.
  8893. // always do this. newFcOptions can be undefined when initializing from i18n file,
  8894. // so no way to tell if this is an initialization or a default-setting.
  8895. momOptions = getMomentLocaleData(localeCode); // will fall back to en
  8896. $.each(momComputableOptions, function(name, func) {
  8897. if (fcOptions[name] == null) {
  8898. fcOptions[name] = func(momOptions, fcOptions);
  8899. }
  8900. });
  8901. // set it as the default locale for FullCalendar
  8902. Calendar.defaults.locale = localeCode;
  8903. };
  8904. // NOTE: can't guarantee any of these computations will run because not every locale has datepicker
  8905. // configs, so make sure there are English fallbacks for these in the defaults file.
  8906. var dpComputableOptions = {
  8907. buttonText: function(dpOptions) {
  8908. return {
  8909. // the translations sometimes wrongly contain HTML entities
  8910. prev: stripHtmlEntities(dpOptions.prevText),
  8911. next: stripHtmlEntities(dpOptions.nextText),
  8912. today: stripHtmlEntities(dpOptions.currentText)
  8913. };
  8914. },
  8915. // Produces format strings like "MMMM YYYY" -> "September 2014"
  8916. monthYearFormat: function(dpOptions) {
  8917. return dpOptions.showMonthAfterYear ?
  8918. 'YYYY[' + dpOptions.yearSuffix + '] MMMM' :
  8919. 'MMMM YYYY[' + dpOptions.yearSuffix + ']';
  8920. }
  8921. };
  8922. var momComputableOptions = {
  8923. // Produces format strings like "ddd M/D" -> "Fri 9/15"
  8924. dayOfMonthFormat: function(momOptions, fcOptions) {
  8925. var format = momOptions.longDateFormat('l'); // for the format like "M/D/YYYY"
  8926. // strip the year off the edge, as well as other misc non-whitespace chars
  8927. format = format.replace(/^Y+[^\w\s]*|[^\w\s]*Y+$/g, '');
  8928. if (fcOptions.isRTL) {
  8929. format += ' ddd'; // for RTL, add day-of-week to end
  8930. }
  8931. else {
  8932. format = 'ddd ' + format; // for LTR, add day-of-week to beginning
  8933. }
  8934. return format;
  8935. },
  8936. // Produces format strings like "h:mma" -> "6:00pm"
  8937. mediumTimeFormat: function(momOptions) { // can't be called `timeFormat` because collides with option
  8938. return momOptions.longDateFormat('LT')
  8939. .replace(/\s*a$/i, 'a'); // convert AM/PM/am/pm to lowercase. remove any spaces beforehand
  8940. },
  8941. // Produces format strings like "h(:mm)a" -> "6pm" / "6:30pm"
  8942. smallTimeFormat: function(momOptions) {
  8943. return momOptions.longDateFormat('LT')
  8944. .replace(':mm', '(:mm)')
  8945. .replace(/(\Wmm)$/, '($1)') // like above, but for foreign locales
  8946. .replace(/\s*a$/i, 'a'); // convert AM/PM/am/pm to lowercase. remove any spaces beforehand
  8947. },
  8948. // Produces format strings like "h(:mm)t" -> "6p" / "6:30p"
  8949. extraSmallTimeFormat: function(momOptions) {
  8950. return momOptions.longDateFormat('LT')
  8951. .replace(':mm', '(:mm)')
  8952. .replace(/(\Wmm)$/, '($1)') // like above, but for foreign locales
  8953. .replace(/\s*a$/i, 't'); // convert to AM/PM/am/pm to lowercase one-letter. remove any spaces beforehand
  8954. },
  8955. // Produces format strings like "ha" / "H" -> "6pm" / "18"
  8956. hourFormat: function(momOptions) {
  8957. return momOptions.longDateFormat('LT')
  8958. .replace(':mm', '')
  8959. .replace(/(\Wmm)$/, '') // like above, but for foreign locales
  8960. .replace(/\s*a$/i, 'a'); // convert AM/PM/am/pm to lowercase. remove any spaces beforehand
  8961. },
  8962. // Produces format strings like "h:mm" -> "6:30" (with no AM/PM)
  8963. noMeridiemTimeFormat: function(momOptions) {
  8964. return momOptions.longDateFormat('LT')
  8965. .replace(/\s*a$/i, ''); // remove trailing AM/PM
  8966. }
  8967. };
  8968. // options that should be computed off live calendar options (considers override options)
  8969. // TODO: best place for this? related to locale?
  8970. // TODO: flipping text based on isRTL is a bad idea because the CSS `direction` might want to handle it
  8971. var instanceComputableOptions = {
  8972. // Produces format strings for results like "Mo 16"
  8973. smallDayDateFormat: function(options) {
  8974. return options.isRTL ?
  8975. 'D dd' :
  8976. 'dd D';
  8977. },
  8978. // Produces format strings for results like "Wk 5"
  8979. weekFormat: function(options) {
  8980. return options.isRTL ?
  8981. 'w[ ' + options.weekNumberTitle + ']' :
  8982. '[' + options.weekNumberTitle + ' ]w';
  8983. },
  8984. // Produces format strings for results like "Wk5"
  8985. smallWeekFormat: function(options) {
  8986. return options.isRTL ?
  8987. 'w[' + options.weekNumberTitle + ']' :
  8988. '[' + options.weekNumberTitle + ']w';
  8989. }
  8990. };
  8991. function populateInstanceComputableOptions(options) {
  8992. $.each(instanceComputableOptions, function(name, func) {
  8993. if (options[name] == null) {
  8994. options[name] = func(options);
  8995. }
  8996. });
  8997. }
  8998. // Returns moment's internal locale data. If doesn't exist, returns English.
  8999. function getMomentLocaleData(localeCode) {
  9000. return moment.localeData(localeCode) || moment.localeData('en');
  9001. }
  9002. // Initialize English by forcing computation of moment-derived options.
  9003. // Also, sets it as the default.
  9004. FC.locale('en', Calendar.englishDefaults);
  9005. ;;
  9006. FC.sourceNormalizers = [];
  9007. FC.sourceFetchers = [];
  9008. var ajaxDefaults = {
  9009. dataType: 'json',
  9010. cache: false
  9011. };
  9012. var eventGUID = 1;
  9013. function EventManager() { // assumed to be a calendar
  9014. var t = this;
  9015. // exports
  9016. t.requestEvents = requestEvents;
  9017. t.reportEventChange = reportEventChange;
  9018. t.isFetchNeeded = isFetchNeeded;
  9019. t.fetchEvents = fetchEvents;
  9020. t.fetchEventSources = fetchEventSources;
  9021. t.refetchEvents = refetchEvents;
  9022. t.refetchEventSources = refetchEventSources;
  9023. t.getEventSources = getEventSources;
  9024. t.getEventSourceById = getEventSourceById;
  9025. t.addEventSource = addEventSource;
  9026. t.removeEventSource = removeEventSource;
  9027. t.removeEventSources = removeEventSources;
  9028. t.updateEvent = updateEvent;
  9029. t.updateEvents = updateEvents;
  9030. t.renderEvent = renderEvent;
  9031. t.renderEvents = renderEvents;
  9032. t.removeEvents = removeEvents;
  9033. t.clientEvents = clientEvents;
  9034. t.mutateEvent = mutateEvent;
  9035. t.normalizeEventDates = normalizeEventDates;
  9036. t.normalizeEventTimes = normalizeEventTimes;
  9037. // locals
  9038. var stickySource = { events: [] };
  9039. var sources = [ stickySource ];
  9040. var rangeStart, rangeEnd;
  9041. var pendingSourceCnt = 0; // outstanding fetch requests, max one per source
  9042. var cache = []; // holds events that have already been expanded
  9043. var prunedCache; // like cache, but only events that intersect with rangeStart/rangeEnd
  9044. $.each(
  9045. (t.options.events ? [ t.options.events ] : []).concat(t.options.eventSources || []),
  9046. function(i, sourceInput) {
  9047. var source = buildEventSource(sourceInput);
  9048. if (source) {
  9049. sources.push(source);
  9050. }
  9051. }
  9052. );
  9053. function requestEvents(start, end) {
  9054. if (!t.options.lazyFetching || isFetchNeeded(start, end)) {
  9055. return fetchEvents(start, end);
  9056. }
  9057. else {
  9058. return Promise.resolve(prunedCache);
  9059. }
  9060. }
  9061. function reportEventChange() {
  9062. prunedCache = filterEventsWithinRange(cache);
  9063. t.trigger('eventsReset', prunedCache);
  9064. }
  9065. function filterEventsWithinRange(events) {
  9066. var filteredEvents = [];
  9067. var i, event;
  9068. for (i = 0; i < events.length; i++) {
  9069. event = events[i];
  9070. if (
  9071. event.start.clone().stripZone() < rangeEnd &&
  9072. t.getEventEnd(event).stripZone() > rangeStart
  9073. ) {
  9074. filteredEvents.push(event);
  9075. }
  9076. }
  9077. return filteredEvents;
  9078. }
  9079. t.getEventCache = function() {
  9080. return cache;
  9081. };
  9082. t.getPrunedEventCache = function() {
  9083. return prunedCache;
  9084. };
  9085. /* Fetching
  9086. -----------------------------------------------------------------------------*/
  9087. // start and end are assumed to be unzoned
  9088. function isFetchNeeded(start, end) {
  9089. return !rangeStart || // nothing has been fetched yet?
  9090. start < rangeStart || end > rangeEnd; // is part of the new range outside of the old range?
  9091. }
  9092. function fetchEvents(start, end) {
  9093. rangeStart = start;
  9094. rangeEnd = end;
  9095. return refetchEvents();
  9096. }
  9097. // poorly named. fetches all sources with current `rangeStart` and `rangeEnd`.
  9098. function refetchEvents() {
  9099. return fetchEventSources(sources, 'reset');
  9100. }
  9101. // poorly named. fetches a subset of event sources.
  9102. function refetchEventSources(matchInputs) {
  9103. return fetchEventSources(getEventSourcesByMatchArray(matchInputs));
  9104. }
  9105. // expects an array of event source objects (the originals, not copies)
  9106. // `specialFetchType` is an optimization parameter that affects purging of the event cache.
  9107. function fetchEventSources(specificSources, specialFetchType) {
  9108. var i, source;
  9109. if (specialFetchType === 'reset') {
  9110. cache = [];
  9111. }
  9112. else if (specialFetchType !== 'add') {
  9113. cache = excludeEventsBySources(cache, specificSources);
  9114. }
  9115. for (i = 0; i < specificSources.length; i++) {
  9116. source = specificSources[i];
  9117. // already-pending sources have already been accounted for in pendingSourceCnt
  9118. if (source._status !== 'pending') {
  9119. pendingSourceCnt++;
  9120. }
  9121. source._fetchId = (source._fetchId || 0) + 1;
  9122. source._status = 'pending';
  9123. }
  9124. for (i = 0; i < specificSources.length; i++) {
  9125. source = specificSources[i];
  9126. tryFetchEventSource(source, source._fetchId);
  9127. }
  9128. if (pendingSourceCnt) {
  9129. return new Promise(function(resolve) {
  9130. t.one('eventsReceived', resolve); // will send prunedCache
  9131. });
  9132. }
  9133. else { // executed all synchronously, or no sources at all
  9134. return Promise.resolve(prunedCache);
  9135. }
  9136. }
  9137. // fetches an event source and processes its result ONLY if it is still the current fetch.
  9138. // caller is responsible for incrementing pendingSourceCnt first.
  9139. function tryFetchEventSource(source, fetchId) {
  9140. _fetchEventSource(source, function(eventInputs) {
  9141. var isArraySource = $.isArray(source.events);
  9142. var i, eventInput;
  9143. var abstractEvent;
  9144. if (
  9145. // is this the source's most recent fetch?
  9146. // if not, rely on an upcoming fetch of this source to decrement pendingSourceCnt
  9147. fetchId === source._fetchId &&
  9148. // event source no longer valid?
  9149. source._status !== 'rejected'
  9150. ) {
  9151. source._status = 'resolved';
  9152. if (eventInputs) {
  9153. for (i = 0; i < eventInputs.length; i++) {
  9154. eventInput = eventInputs[i];
  9155. if (isArraySource) { // array sources have already been convert to Event Objects
  9156. abstractEvent = eventInput;
  9157. }
  9158. else {
  9159. abstractEvent = buildEventFromInput(eventInput, source);
  9160. }
  9161. if (abstractEvent) { // not false (an invalid event)
  9162. cache.push.apply( // append
  9163. cache,
  9164. expandEvent(abstractEvent) // add individual expanded events to the cache
  9165. );
  9166. }
  9167. }
  9168. }
  9169. decrementPendingSourceCnt();
  9170. }
  9171. });
  9172. }
  9173. function rejectEventSource(source) {
  9174. var wasPending = source._status === 'pending';
  9175. source._status = 'rejected';
  9176. if (wasPending) {
  9177. decrementPendingSourceCnt();
  9178. }
  9179. }
  9180. function decrementPendingSourceCnt() {
  9181. pendingSourceCnt--;
  9182. if (!pendingSourceCnt) {
  9183. reportEventChange(cache); // updates prunedCache
  9184. t.trigger('eventsReceived', prunedCache);
  9185. }
  9186. }
  9187. function _fetchEventSource(source, callback) {
  9188. var i;
  9189. var fetchers = FC.sourceFetchers;
  9190. var res;
  9191. for (i=0; i<fetchers.length; i++) {
  9192. res = fetchers[i].call(
  9193. t, // this, the Calendar object
  9194. source,
  9195. rangeStart.clone(),
  9196. rangeEnd.clone(),
  9197. t.options.timezone,
  9198. callback
  9199. );
  9200. if (res === true) {
  9201. // the fetcher is in charge. made its own async request
  9202. return;
  9203. }
  9204. else if (typeof res == 'object') {
  9205. // the fetcher returned a new source. process it
  9206. _fetchEventSource(res, callback);
  9207. return;
  9208. }
  9209. }
  9210. var events = source.events;
  9211. if (events) {
  9212. if ($.isFunction(events)) {
  9213. t.pushLoading();
  9214. events.call(
  9215. t, // this, the Calendar object
  9216. rangeStart.clone(),
  9217. rangeEnd.clone(),
  9218. t.options.timezone,
  9219. function(events) {
  9220. callback(events);
  9221. t.popLoading();
  9222. }
  9223. );
  9224. }
  9225. else if ($.isArray(events)) {
  9226. callback(events);
  9227. }
  9228. else {
  9229. callback();
  9230. }
  9231. }else{
  9232. var url = source.url;
  9233. if (url) {
  9234. var success = source.success;
  9235. var error = source.error;
  9236. var complete = source.complete;
  9237. // retrieve any outbound GET/POST $.ajax data from the options
  9238. var customData;
  9239. if ($.isFunction(source.data)) {
  9240. // supplied as a function that returns a key/value object
  9241. customData = source.data();
  9242. }
  9243. else {
  9244. // supplied as a straight key/value object
  9245. customData = source.data;
  9246. }
  9247. // use a copy of the custom data so we can modify the parameters
  9248. // and not affect the passed-in object.
  9249. var data = $.extend({}, customData || {});
  9250. var startParam = firstDefined(source.startParam, t.options.startParam);
  9251. var endParam = firstDefined(source.endParam, t.options.endParam);
  9252. var timezoneParam = firstDefined(source.timezoneParam, t.options.timezoneParam);
  9253. if (startParam) {
  9254. data[startParam] = rangeStart.format();
  9255. }
  9256. if (endParam) {
  9257. data[endParam] = rangeEnd.format();
  9258. }
  9259. if (t.options.timezone && t.options.timezone != 'local') {
  9260. data[timezoneParam] = t.options.timezone;
  9261. }
  9262. t.pushLoading();
  9263. $.ajax($.extend({}, ajaxDefaults, source, {
  9264. data: data,
  9265. success: function(events) {
  9266. events = events || [];
  9267. var res = applyAll(success, this, arguments);
  9268. if ($.isArray(res)) {
  9269. events = res;
  9270. }
  9271. callback(events);
  9272. },
  9273. error: function() {
  9274. applyAll(error, this, arguments);
  9275. callback();
  9276. },
  9277. complete: function() {
  9278. applyAll(complete, this, arguments);
  9279. t.popLoading();
  9280. }
  9281. }));
  9282. }else{
  9283. callback();
  9284. }
  9285. }
  9286. }
  9287. /* Sources
  9288. -----------------------------------------------------------------------------*/
  9289. function addEventSource(sourceInput) {
  9290. var source = buildEventSource(sourceInput);
  9291. if (source) {
  9292. sources.push(source);
  9293. fetchEventSources([ source ], 'add'); // will eventually call reportEventChange
  9294. }
  9295. }
  9296. function buildEventSource(sourceInput) { // will return undefined if invalid source
  9297. var normalizers = FC.sourceNormalizers;
  9298. var source;
  9299. var i;
  9300. if ($.isFunction(sourceInput) || $.isArray(sourceInput)) {
  9301. source = { events: sourceInput };
  9302. }
  9303. else if (typeof sourceInput === 'string') {
  9304. source = { url: sourceInput };
  9305. }
  9306. else if (typeof sourceInput === 'object') {
  9307. source = $.extend({}, sourceInput); // shallow copy
  9308. }
  9309. if (source) {
  9310. // TODO: repeat code, same code for event classNames
  9311. if (source.className) {
  9312. if (typeof source.className === 'string') {
  9313. source.className = source.className.split(/\s+/);
  9314. }
  9315. // otherwise, assumed to be an array
  9316. }
  9317. else {
  9318. source.className = [];
  9319. }
  9320. // for array sources, we convert to standard Event Objects up front
  9321. if ($.isArray(source.events)) {
  9322. source.origArray = source.events; // for removeEventSource
  9323. source.events = $.map(source.events, function(eventInput) {
  9324. return buildEventFromInput(eventInput, source);
  9325. });
  9326. }
  9327. for (i=0; i<normalizers.length; i++) {
  9328. normalizers[i].call(t, source);
  9329. }
  9330. return source;
  9331. }
  9332. }
  9333. function removeEventSource(matchInput) {
  9334. removeSpecificEventSources(
  9335. getEventSourcesByMatch(matchInput)
  9336. );
  9337. }
  9338. // if called with no arguments, removes all.
  9339. function removeEventSources(matchInputs) {
  9340. if (matchInputs == null) {
  9341. removeSpecificEventSources(sources, true); // isAll=true
  9342. }
  9343. else {
  9344. removeSpecificEventSources(
  9345. getEventSourcesByMatchArray(matchInputs)
  9346. );
  9347. }
  9348. }
  9349. function removeSpecificEventSources(targetSources, isAll) {
  9350. var i;
  9351. // cancel pending requests
  9352. for (i = 0; i < targetSources.length; i++) {
  9353. rejectEventSource(targetSources[i]);
  9354. }
  9355. if (isAll) { // an optimization
  9356. sources = [];
  9357. cache = [];
  9358. }
  9359. else {
  9360. // remove from persisted source list
  9361. sources = $.grep(sources, function(source) {
  9362. for (i = 0; i < targetSources.length; i++) {
  9363. if (source === targetSources[i]) {
  9364. return false; // exclude
  9365. }
  9366. }
  9367. return true; // include
  9368. });
  9369. cache = excludeEventsBySources(cache, targetSources);
  9370. }
  9371. reportEventChange();
  9372. }
  9373. function getEventSources() {
  9374. return sources.slice(1); // returns a shallow copy of sources with stickySource removed
  9375. }
  9376. function getEventSourceById(id) {
  9377. return $.grep(sources, function(source) {
  9378. return source.id && source.id === id;
  9379. })[0];
  9380. }
  9381. // like getEventSourcesByMatch, but accepts multple match criteria (like multiple IDs)
  9382. function getEventSourcesByMatchArray(matchInputs) {
  9383. // coerce into an array
  9384. if (!matchInputs) {
  9385. matchInputs = [];
  9386. }
  9387. else if (!$.isArray(matchInputs)) {
  9388. matchInputs = [ matchInputs ];
  9389. }
  9390. var matchingSources = [];
  9391. var i;
  9392. // resolve raw inputs to real event source objects
  9393. for (i = 0; i < matchInputs.length; i++) {
  9394. matchingSources.push.apply( // append
  9395. matchingSources,
  9396. getEventSourcesByMatch(matchInputs[i])
  9397. );
  9398. }
  9399. return matchingSources;
  9400. }
  9401. // matchInput can either by a real event source object, an ID, or the function/URL for the source.
  9402. // returns an array of matching source objects.
  9403. function getEventSourcesByMatch(matchInput) {
  9404. var i, source;
  9405. // given an proper event source object
  9406. for (i = 0; i < sources.length; i++) {
  9407. source = sources[i];
  9408. if (source === matchInput) {
  9409. return [ source ];
  9410. }
  9411. }
  9412. // an ID match
  9413. source = getEventSourceById(matchInput);
  9414. if (source) {
  9415. return [ source ];
  9416. }
  9417. return $.grep(sources, function(source) {
  9418. return isSourcesEquivalent(matchInput, source);
  9419. });
  9420. }
  9421. function isSourcesEquivalent(source1, source2) {
  9422. return source1 && source2 && getSourcePrimitive(source1) == getSourcePrimitive(source2);
  9423. }
  9424. function getSourcePrimitive(source) {
  9425. return (
  9426. (typeof source === 'object') ? // a normalized event source?
  9427. (source.origArray || source.googleCalendarId || source.url || source.events) : // get the primitive
  9428. null
  9429. ) ||
  9430. source; // the given argument *is* the primitive
  9431. }
  9432. // util
  9433. // returns a filtered array without events that are part of any of the given sources
  9434. function excludeEventsBySources(specificEvents, specificSources) {
  9435. return $.grep(specificEvents, function(event) {
  9436. for (var i = 0; i < specificSources.length; i++) {
  9437. if (event.source === specificSources[i]) {
  9438. return false; // exclude
  9439. }
  9440. }
  9441. return true; // keep
  9442. });
  9443. }
  9444. /* Manipulation
  9445. -----------------------------------------------------------------------------*/
  9446. // Only ever called from the externally-facing API
  9447. function updateEvent(event) {
  9448. updateEvents([ event ]);
  9449. }
  9450. // Only ever called from the externally-facing API
  9451. function updateEvents(events) {
  9452. var i, event;
  9453. for (i = 0; i < events.length; i++) {
  9454. event = events[i];
  9455. // massage start/end values, even if date string values
  9456. event.start = t.moment(event.start);
  9457. if (event.end) {
  9458. event.end = t.moment(event.end);
  9459. }
  9460. else {
  9461. event.end = null;
  9462. }
  9463. mutateEvent(event, getMiscEventProps(event)); // will handle start/end/allDay normalization
  9464. }
  9465. reportEventChange(); // reports event modifications (so we can redraw)
  9466. }
  9467. // Returns a hash of misc event properties that should be copied over to related events.
  9468. function getMiscEventProps(event) {
  9469. var props = {};
  9470. $.each(event, function(name, val) {
  9471. if (isMiscEventPropName(name)) {
  9472. if (val !== undefined && isAtomic(val)) { // a defined non-object
  9473. props[name] = val;
  9474. }
  9475. }
  9476. });
  9477. return props;
  9478. }
  9479. // non-date-related, non-id-related, non-secret
  9480. function isMiscEventPropName(name) {
  9481. return !/^_|^(id|allDay|start|end)$/.test(name);
  9482. }
  9483. // returns the expanded events that were created
  9484. function renderEvent(eventInput, stick) {
  9485. return renderEvents([ eventInput ], stick);
  9486. }
  9487. // returns the expanded events that were created
  9488. function renderEvents(eventInputs, stick) {
  9489. var renderedEvents = [];
  9490. var renderableEvents;
  9491. var abstractEvent;
  9492. var i, j, event;
  9493. for (i = 0; i < eventInputs.length; i++) {
  9494. abstractEvent = buildEventFromInput(eventInputs[i]);
  9495. if (abstractEvent) { // not false (a valid input)
  9496. renderableEvents = expandEvent(abstractEvent);
  9497. for (j = 0; j < renderableEvents.length; j++) {
  9498. event = renderableEvents[j];
  9499. if (!event.source) {
  9500. if (stick) {
  9501. stickySource.events.push(event);
  9502. event.source = stickySource;
  9503. }
  9504. cache.push(event);
  9505. }
  9506. }
  9507. renderedEvents = renderedEvents.concat(renderableEvents);
  9508. }
  9509. }
  9510. if (renderedEvents.length) { // any new events rendered?
  9511. reportEventChange();
  9512. }
  9513. return renderedEvents;
  9514. }
  9515. function removeEvents(filter) {
  9516. var eventID;
  9517. var i;
  9518. if (filter == null) { // null or undefined. remove all events
  9519. filter = function() { return true; }; // will always match
  9520. }
  9521. else if (!$.isFunction(filter)) { // an event ID
  9522. eventID = filter + '';
  9523. filter = function(event) {
  9524. return event._id == eventID;
  9525. };
  9526. }
  9527. // Purge event(s) from our local cache
  9528. cache = $.grep(cache, filter, true); // inverse=true
  9529. // Remove events from array sources.
  9530. // This works because they have been converted to official Event Objects up front.
  9531. // (and as a result, event._id has been calculated).
  9532. for (i=0; i<sources.length; i++) {
  9533. if ($.isArray(sources[i].events)) {
  9534. sources[i].events = $.grep(sources[i].events, filter, true);
  9535. }
  9536. }
  9537. reportEventChange();
  9538. }
  9539. function clientEvents(filter) {
  9540. if ($.isFunction(filter)) {
  9541. return $.grep(cache, filter);
  9542. }
  9543. else if (filter != null) { // not null, not undefined. an event ID
  9544. filter += '';
  9545. return $.grep(cache, function(e) {
  9546. return e._id == filter;
  9547. });
  9548. }
  9549. return cache; // else, return all
  9550. }
  9551. // Makes sure all array event sources have their internal event objects
  9552. // converted over to the Calendar's current timezone.
  9553. t.rezoneArrayEventSources = function() {
  9554. var i;
  9555. var events;
  9556. var j;
  9557. for (i = 0; i < sources.length; i++) {
  9558. events = sources[i].events;
  9559. if ($.isArray(events)) {
  9560. for (j = 0; j < events.length; j++) {
  9561. rezoneEventDates(events[j]);
  9562. }
  9563. }
  9564. }
  9565. };
  9566. function rezoneEventDates(event) {
  9567. event.start = t.moment(event.start);
  9568. if (event.end) {
  9569. event.end = t.moment(event.end);
  9570. }
  9571. backupEventDates(event);
  9572. }
  9573. /* Event Normalization
  9574. -----------------------------------------------------------------------------*/
  9575. // Given a raw object with key/value properties, returns an "abstract" Event object.
  9576. // An "abstract" event is an event that, if recurring, will not have been expanded yet.
  9577. // Will return `false` when input is invalid.
  9578. // `source` is optional
  9579. function buildEventFromInput(input, source) {
  9580. var out = {};
  9581. var start, end;
  9582. var allDay;
  9583. if (t.options.eventDataTransform) {
  9584. input = t.options.eventDataTransform(input);
  9585. }
  9586. if (source && source.eventDataTransform) {
  9587. input = source.eventDataTransform(input);
  9588. }
  9589. // Copy all properties over to the resulting object.
  9590. // The special-case properties will be copied over afterwards.
  9591. $.extend(out, input);
  9592. if (source) {
  9593. out.source = source;
  9594. }
  9595. out._id = input._id || (input.id === undefined ? '_fc' + eventGUID++ : input.id + '');
  9596. if (input.className) {
  9597. if (typeof input.className == 'string') {
  9598. out.className = input.className.split(/\s+/);
  9599. }
  9600. else { // assumed to be an array
  9601. out.className = input.className;
  9602. }
  9603. }
  9604. else {
  9605. out.className = [];
  9606. }
  9607. start = input.start || input.date; // "date" is an alias for "start"
  9608. end = input.end;
  9609. // parse as a time (Duration) if applicable
  9610. if (isTimeString(start)) {
  9611. start = moment.duration(start);
  9612. }
  9613. if (isTimeString(end)) {
  9614. end = moment.duration(end);
  9615. }
  9616. if (input.dow || moment.isDuration(start) || moment.isDuration(end)) {
  9617. // the event is "abstract" (recurring) so don't calculate exact start/end dates just yet
  9618. out.start = start ? moment.duration(start) : null; // will be a Duration or null
  9619. out.end = end ? moment.duration(end) : null; // will be a Duration or null
  9620. out._recurring = true; // our internal marker
  9621. }
  9622. else {
  9623. if (start) {
  9624. start = t.moment(start);
  9625. if (!start.isValid()) {
  9626. return false;
  9627. }
  9628. }
  9629. if (end) {
  9630. end = t.moment(end);
  9631. if (!end.isValid()) {
  9632. end = null; // let defaults take over
  9633. }
  9634. }
  9635. allDay = input.allDay;
  9636. if (allDay === undefined) { // still undefined? fallback to default
  9637. allDay = firstDefined(
  9638. source ? source.allDayDefault : undefined,
  9639. t.options.allDayDefault
  9640. );
  9641. // still undefined? normalizeEventDates will calculate it
  9642. }
  9643. assignDatesToEvent(start, end, allDay, out);
  9644. }
  9645. t.normalizeEvent(out); // hook for external use. a prototype method
  9646. return out;
  9647. }
  9648. t.buildEventFromInput = buildEventFromInput;
  9649. // Normalizes and assigns the given dates to the given partially-formed event object.
  9650. // NOTE: mutates the given start/end moments. does not make a copy.
  9651. function assignDatesToEvent(start, end, allDay, event) {
  9652. event.start = start;
  9653. event.end = end;
  9654. event.allDay = allDay;
  9655. normalizeEventDates(event);
  9656. backupEventDates(event);
  9657. }
  9658. // Ensures proper values for allDay/start/end. Accepts an Event object, or a plain object with event-ish properties.
  9659. // NOTE: Will modify the given object.
  9660. function normalizeEventDates(eventProps) {
  9661. normalizeEventTimes(eventProps);
  9662. if (eventProps.end && !eventProps.end.isAfter(eventProps.start)) {
  9663. eventProps.end = null;
  9664. }
  9665. if (!eventProps.end) {
  9666. if (t.options.forceEventDuration) {
  9667. eventProps.end = t.getDefaultEventEnd(eventProps.allDay, eventProps.start);
  9668. }
  9669. else {
  9670. eventProps.end = null;
  9671. }
  9672. }
  9673. }
  9674. // Ensures the allDay property exists and the timeliness of the start/end dates are consistent
  9675. function normalizeEventTimes(eventProps) {
  9676. if (eventProps.allDay == null) {
  9677. eventProps.allDay = !(eventProps.start.hasTime() || (eventProps.end && eventProps.end.hasTime()));
  9678. }
  9679. if (eventProps.allDay) {
  9680. eventProps.start.stripTime();
  9681. if (eventProps.end) {
  9682. // TODO: consider nextDayThreshold here? If so, will require a lot of testing and adjustment
  9683. eventProps.end.stripTime();
  9684. }
  9685. }
  9686. else {
  9687. if (!eventProps.start.hasTime()) {
  9688. eventProps.start = t.applyTimezone(eventProps.start.time(0)); // will assign a 00:00 time
  9689. }
  9690. if (eventProps.end && !eventProps.end.hasTime()) {
  9691. eventProps.end = t.applyTimezone(eventProps.end.time(0)); // will assign a 00:00 time
  9692. }
  9693. }
  9694. }
  9695. // If the given event is a recurring event, break it down into an array of individual instances.
  9696. // If not a recurring event, return an array with the single original event.
  9697. // If given a falsy input (probably because of a failed buildEventFromInput call), returns an empty array.
  9698. // HACK: can override the recurring window by providing custom rangeStart/rangeEnd (for businessHours).
  9699. function expandEvent(abstractEvent, _rangeStart, _rangeEnd) {
  9700. var events = [];
  9701. var dowHash;
  9702. var dow;
  9703. var i;
  9704. var date;
  9705. var startTime, endTime;
  9706. var start, end;
  9707. var event;
  9708. _rangeStart = _rangeStart || rangeStart;
  9709. _rangeEnd = _rangeEnd || rangeEnd;
  9710. if (abstractEvent) {
  9711. if (abstractEvent._recurring) {
  9712. // make a boolean hash as to whether the event occurs on each day-of-week
  9713. if ((dow = abstractEvent.dow)) {
  9714. dowHash = {};
  9715. for (i = 0; i < dow.length; i++) {
  9716. dowHash[dow[i]] = true;
  9717. }
  9718. }
  9719. // iterate through every day in the current range
  9720. date = _rangeStart.clone().stripTime(); // holds the date of the current day
  9721. while (date.isBefore(_rangeEnd)) {
  9722. if (!dowHash || dowHash[date.day()]) { // if everyday, or this particular day-of-week
  9723. startTime = abstractEvent.start; // the stored start and end properties are times (Durations)
  9724. endTime = abstractEvent.end; // "
  9725. start = date.clone();
  9726. end = null;
  9727. if (startTime) {
  9728. start = start.time(startTime);
  9729. }
  9730. if (endTime) {
  9731. end = date.clone().time(endTime);
  9732. }
  9733. event = $.extend({}, abstractEvent); // make a copy of the original
  9734. assignDatesToEvent(
  9735. start, end,
  9736. !startTime && !endTime, // allDay?
  9737. event
  9738. );
  9739. events.push(event);
  9740. }
  9741. date.add(1, 'days');
  9742. }
  9743. }
  9744. else {
  9745. events.push(abstractEvent); // return the original event. will be a one-item array
  9746. }
  9747. }
  9748. return events;
  9749. }
  9750. t.expandEvent = expandEvent;
  9751. /* Event Modification Math
  9752. -----------------------------------------------------------------------------------------*/
  9753. // Modifies an event and all related events by applying the given properties.
  9754. // Special date-diffing logic is used for manipulation of dates.
  9755. // If `props` does not contain start/end dates, the updated values are assumed to be the event's current start/end.
  9756. // All date comparisons are done against the event's pristine _start and _end dates.
  9757. // Returns an object with delta information and a function to undo all operations.
  9758. // For making computations in a granularity greater than day/time, specify largeUnit.
  9759. // NOTE: The given `newProps` might be mutated for normalization purposes.
  9760. function mutateEvent(event, newProps, largeUnit) {
  9761. var miscProps = {};
  9762. var oldProps;
  9763. var clearEnd;
  9764. var startDelta;
  9765. var endDelta;
  9766. var durationDelta;
  9767. var undoFunc;
  9768. // diffs the dates in the appropriate way, returning a duration
  9769. function diffDates(date1, date0) { // date1 - date0
  9770. if (largeUnit) {
  9771. return diffByUnit(date1, date0, largeUnit);
  9772. }
  9773. else if (newProps.allDay) {
  9774. return diffDay(date1, date0);
  9775. }
  9776. else {
  9777. return diffDayTime(date1, date0);
  9778. }
  9779. }
  9780. newProps = newProps || {};
  9781. // normalize new date-related properties
  9782. if (!newProps.start) {
  9783. newProps.start = event.start.clone();
  9784. }
  9785. if (newProps.end === undefined) {
  9786. newProps.end = event.end ? event.end.clone() : null;
  9787. }
  9788. if (newProps.allDay == null) { // is null or undefined?
  9789. newProps.allDay = event.allDay;
  9790. }
  9791. normalizeEventDates(newProps);
  9792. // create normalized versions of the original props to compare against
  9793. // need a real end value, for diffing
  9794. oldProps = {
  9795. start: event._start.clone(),
  9796. end: event._end ? event._end.clone() : t.getDefaultEventEnd(event._allDay, event._start),
  9797. allDay: newProps.allDay // normalize the dates in the same regard as the new properties
  9798. };
  9799. normalizeEventDates(oldProps);
  9800. // need to clear the end date if explicitly changed to null
  9801. clearEnd = event._end !== null && newProps.end === null;
  9802. // compute the delta for moving the start date
  9803. startDelta = diffDates(newProps.start, oldProps.start);
  9804. // compute the delta for moving the end date
  9805. if (newProps.end) {
  9806. endDelta = diffDates(newProps.end, oldProps.end);
  9807. durationDelta = endDelta.subtract(startDelta);
  9808. }
  9809. else {
  9810. durationDelta = null;
  9811. }
  9812. // gather all non-date-related properties
  9813. $.each(newProps, function(name, val) {
  9814. if (isMiscEventPropName(name)) {
  9815. if (val !== undefined) {
  9816. miscProps[name] = val;
  9817. }
  9818. }
  9819. });
  9820. // apply the operations to the event and all related events
  9821. undoFunc = mutateEvents(
  9822. clientEvents(event._id), // get events with this ID
  9823. clearEnd,
  9824. newProps.allDay,
  9825. startDelta,
  9826. durationDelta,
  9827. miscProps
  9828. );
  9829. return {
  9830. dateDelta: startDelta,
  9831. durationDelta: durationDelta,
  9832. undo: undoFunc
  9833. };
  9834. }
  9835. // Modifies an array of events in the following ways (operations are in order):
  9836. // - clear the event's `end`
  9837. // - convert the event to allDay
  9838. // - add `dateDelta` to the start and end
  9839. // - add `durationDelta` to the event's duration
  9840. // - assign `miscProps` to the event
  9841. //
  9842. // Returns a function that can be called to undo all the operations.
  9843. //
  9844. // TODO: don't use so many closures. possible memory issues when lots of events with same ID.
  9845. //
  9846. function mutateEvents(events, clearEnd, allDay, dateDelta, durationDelta, miscProps) {
  9847. var isAmbigTimezone = t.getIsAmbigTimezone();
  9848. var undoFunctions = [];
  9849. // normalize zero-length deltas to be null
  9850. if (dateDelta && !dateDelta.valueOf()) { dateDelta = null; }
  9851. if (durationDelta && !durationDelta.valueOf()) { durationDelta = null; }
  9852. $.each(events, function(i, event) {
  9853. var oldProps;
  9854. var newProps;
  9855. // build an object holding all the old values, both date-related and misc.
  9856. // for the undo function.
  9857. oldProps = {
  9858. start: event.start.clone(),
  9859. end: event.end ? event.end.clone() : null,
  9860. allDay: event.allDay
  9861. };
  9862. $.each(miscProps, function(name) {
  9863. oldProps[name] = event[name];
  9864. });
  9865. // new date-related properties. work off the original date snapshot.
  9866. // ok to use references because they will be thrown away when backupEventDates is called.
  9867. newProps = {
  9868. start: event._start,
  9869. end: event._end,
  9870. allDay: allDay // normalize the dates in the same regard as the new properties
  9871. };
  9872. normalizeEventDates(newProps); // massages start/end/allDay
  9873. // strip or ensure the end date
  9874. if (clearEnd) {
  9875. newProps.end = null;
  9876. }
  9877. else if (durationDelta && !newProps.end) { // the duration translation requires an end date
  9878. newProps.end = t.getDefaultEventEnd(newProps.allDay, newProps.start);
  9879. }
  9880. if (dateDelta) {
  9881. newProps.start.add(dateDelta);
  9882. if (newProps.end) {
  9883. newProps.end.add(dateDelta);
  9884. }
  9885. }
  9886. if (durationDelta) {
  9887. newProps.end.add(durationDelta); // end already ensured above
  9888. }
  9889. // if the dates have changed, and we know it is impossible to recompute the
  9890. // timezone offsets, strip the zone.
  9891. if (
  9892. isAmbigTimezone &&
  9893. !newProps.allDay &&
  9894. (dateDelta || durationDelta)
  9895. ) {
  9896. newProps.start.stripZone();
  9897. if (newProps.end) {
  9898. newProps.end.stripZone();
  9899. }
  9900. }
  9901. $.extend(event, miscProps, newProps); // copy over misc props, then date-related props
  9902. backupEventDates(event); // regenerate internal _start/_end/_allDay
  9903. undoFunctions.push(function() {
  9904. $.extend(event, oldProps);
  9905. backupEventDates(event); // regenerate internal _start/_end/_allDay
  9906. });
  9907. });
  9908. return function() {
  9909. for (var i = 0; i < undoFunctions.length; i++) {
  9910. undoFunctions[i]();
  9911. }
  9912. };
  9913. }
  9914. }
  9915. // returns an undo function
  9916. Calendar.prototype.mutateSeg = function(seg, newProps) {
  9917. return this.mutateEvent(seg.event, newProps);
  9918. };
  9919. // hook for external libs to manipulate event properties upon creation.
  9920. // should manipulate the event in-place.
  9921. Calendar.prototype.normalizeEvent = function(event) {
  9922. };
  9923. // Does the given span (start, end, and other location information)
  9924. // fully contain the other?
  9925. Calendar.prototype.spanContainsSpan = function(outerSpan, innerSpan) {
  9926. var eventStart = outerSpan.start.clone().stripZone();
  9927. var eventEnd = this.getEventEnd(outerSpan).stripZone();
  9928. return innerSpan.start >= eventStart && innerSpan.end <= eventEnd;
  9929. };
  9930. // Returns a list of events that the given event should be compared against when being considered for a move to
  9931. // the specified span. Attached to the Calendar's prototype because EventManager is a mixin for a Calendar.
  9932. Calendar.prototype.getPeerEvents = function(span, event) {
  9933. var cache = this.getEventCache();
  9934. var peerEvents = [];
  9935. var i, otherEvent;
  9936. for (i = 0; i < cache.length; i++) {
  9937. otherEvent = cache[i];
  9938. if (
  9939. !event ||
  9940. event._id !== otherEvent._id // don't compare the event to itself or other related [repeating] events
  9941. ) {
  9942. peerEvents.push(otherEvent);
  9943. }
  9944. }
  9945. return peerEvents;
  9946. };
  9947. // updates the "backup" properties, which are preserved in order to compute diffs later on.
  9948. function backupEventDates(event) {
  9949. event._allDay = event.allDay;
  9950. event._start = event.start.clone();
  9951. event._end = event.end ? event.end.clone() : null;
  9952. }
  9953. /* Overlapping / Constraining
  9954. -----------------------------------------------------------------------------------------*/
  9955. // Determines if the given event can be relocated to the given span (unzoned start/end with other misc data)
  9956. Calendar.prototype.isEventSpanAllowed = function(span, event) {
  9957. var source = event.source || {};
  9958. var constraint = firstDefined(
  9959. event.constraint,
  9960. source.constraint,
  9961. this.options.eventConstraint
  9962. );
  9963. var overlap = firstDefined(
  9964. event.overlap,
  9965. source.overlap,
  9966. this.options.eventOverlap
  9967. );
  9968. return this.isSpanAllowed(span, constraint, overlap, event) &&
  9969. (!this.options.eventAllow || this.options.eventAllow(span, event) !== false);
  9970. };
  9971. // Determines if an external event can be relocated to the given span (unzoned start/end with other misc data)
  9972. Calendar.prototype.isExternalSpanAllowed = function(eventSpan, eventLocation, eventProps) {
  9973. var eventInput;
  9974. var event;
  9975. // note: very similar logic is in View's reportExternalDrop
  9976. if (eventProps) {
  9977. eventInput = $.extend({}, eventProps, eventLocation);
  9978. event = this.expandEvent(
  9979. this.buildEventFromInput(eventInput)
  9980. )[0];
  9981. }
  9982. if (event) {
  9983. return this.isEventSpanAllowed(eventSpan, event);
  9984. }
  9985. else { // treat it as a selection
  9986. return this.isSelectionSpanAllowed(eventSpan);
  9987. }
  9988. };
  9989. // Determines the given span (unzoned start/end with other misc data) can be selected.
  9990. Calendar.prototype.isSelectionSpanAllowed = function(span) {
  9991. return this.isSpanAllowed(span, this.options.selectConstraint, this.options.selectOverlap) &&
  9992. (!this.options.selectAllow || this.options.selectAllow(span) !== false);
  9993. };
  9994. // Returns true if the given span (caused by an event drop/resize or a selection) is allowed to exist
  9995. // according to the constraint/overlap settings.
  9996. // `event` is not required if checking a selection.
  9997. Calendar.prototype.isSpanAllowed = function(span, constraint, overlap, event) {
  9998. var constraintEvents;
  9999. var anyContainment;
  10000. var peerEvents;
  10001. var i, peerEvent;
  10002. var peerOverlap;
  10003. // the range must be fully contained by at least one of produced constraint events
  10004. if (constraint != null) {
  10005. // not treated as an event! intermediate data structure
  10006. // TODO: use ranges in the future
  10007. constraintEvents = this.constraintToEvents(constraint);
  10008. if (constraintEvents) { // not invalid
  10009. anyContainment = false;
  10010. for (i = 0; i < constraintEvents.length; i++) {
  10011. if (this.spanContainsSpan(constraintEvents[i], span)) {
  10012. anyContainment = true;
  10013. break;
  10014. }
  10015. }
  10016. if (!anyContainment) {
  10017. return false;
  10018. }
  10019. }
  10020. }
  10021. peerEvents = this.getPeerEvents(span, event);
  10022. for (i = 0; i < peerEvents.length; i++) {
  10023. peerEvent = peerEvents[i];
  10024. // there needs to be an actual intersection before disallowing anything
  10025. if (this.eventIntersectsRange(peerEvent, span)) {
  10026. // evaluate overlap for the given range and short-circuit if necessary
  10027. if (overlap === false) {
  10028. return false;
  10029. }
  10030. // if the event's overlap is a test function, pass the peer event in question as the first param
  10031. else if (typeof overlap === 'function' && !overlap(peerEvent, event)) {
  10032. return false;
  10033. }
  10034. // if we are computing if the given range is allowable for an event, consider the other event's
  10035. // EventObject-specific or Source-specific `overlap` property
  10036. if (event) {
  10037. peerOverlap = firstDefined(
  10038. peerEvent.overlap,
  10039. (peerEvent.source || {}).overlap
  10040. // we already considered the global `eventOverlap`
  10041. );
  10042. if (peerOverlap === false) {
  10043. return false;
  10044. }
  10045. // if the peer event's overlap is a test function, pass the subject event as the first param
  10046. if (typeof peerOverlap === 'function' && !peerOverlap(event, peerEvent)) {
  10047. return false;
  10048. }
  10049. }
  10050. }
  10051. }
  10052. return true;
  10053. };
  10054. // Given an event input from the API, produces an array of event objects. Possible event inputs:
  10055. // 'businessHours'
  10056. // An event ID (number or string)
  10057. // An object with specific start/end dates or a recurring event (like what businessHours accepts)
  10058. Calendar.prototype.constraintToEvents = function(constraintInput) {
  10059. if (constraintInput === 'businessHours') {
  10060. return this.getCurrentBusinessHourEvents();
  10061. }
  10062. if (typeof constraintInput === 'object') {
  10063. if (constraintInput.start != null) { // needs to be event-like input
  10064. return this.expandEvent(this.buildEventFromInput(constraintInput));
  10065. }
  10066. else {
  10067. return null; // invalid
  10068. }
  10069. }
  10070. return this.clientEvents(constraintInput); // probably an ID
  10071. };
  10072. // Does the event's date range intersect with the given range?
  10073. // start/end already assumed to have stripped zones :(
  10074. Calendar.prototype.eventIntersectsRange = function(event, range) {
  10075. var eventStart = event.start.clone().stripZone();
  10076. var eventEnd = this.getEventEnd(event).stripZone();
  10077. return range.start < eventEnd && range.end > eventStart;
  10078. };
  10079. /* Business Hours
  10080. -----------------------------------------------------------------------------------------*/
  10081. var BUSINESS_HOUR_EVENT_DEFAULTS = {
  10082. id: '_fcBusinessHours', // will relate events from different calls to expandEvent
  10083. start: '09:00',
  10084. end: '17:00',
  10085. dow: [ 1, 2, 3, 4, 5 ], // monday - friday
  10086. rendering: 'inverse-background'
  10087. // classNames are defined in businessHoursSegClasses
  10088. };
  10089. // Return events objects for business hours within the current view.
  10090. // Abuse of our event system :(
  10091. Calendar.prototype.getCurrentBusinessHourEvents = function(wholeDay) {
  10092. return this.computeBusinessHourEvents(wholeDay, this.options.businessHours);
  10093. };
  10094. // Given a raw input value from options, return events objects for business hours within the current view.
  10095. Calendar.prototype.computeBusinessHourEvents = function(wholeDay, input) {
  10096. if (input === true) {
  10097. return this.expandBusinessHourEvents(wholeDay, [ {} ]);
  10098. }
  10099. else if ($.isPlainObject(input)) {
  10100. return this.expandBusinessHourEvents(wholeDay, [ input ]);
  10101. }
  10102. else if ($.isArray(input)) {
  10103. return this.expandBusinessHourEvents(wholeDay, input, true);
  10104. }
  10105. else {
  10106. return [];
  10107. }
  10108. };
  10109. // inputs expected to be an array of objects.
  10110. // if ignoreNoDow is true, will ignore entries that don't specify a day-of-week (dow) key.
  10111. Calendar.prototype.expandBusinessHourEvents = function(wholeDay, inputs, ignoreNoDow) {
  10112. var view = this.getView();
  10113. var events = [];
  10114. var i, input;
  10115. for (i = 0; i < inputs.length; i++) {
  10116. input = inputs[i];
  10117. if (ignoreNoDow && !input.dow) {
  10118. continue;
  10119. }
  10120. // give defaults. will make a copy
  10121. input = $.extend({}, BUSINESS_HOUR_EVENT_DEFAULTS, input);
  10122. // if a whole-day series is requested, clear the start/end times
  10123. if (wholeDay) {
  10124. input.start = null;
  10125. input.end = null;
  10126. }
  10127. events.push.apply(events, // append
  10128. this.expandEvent(
  10129. this.buildEventFromInput(input),
  10130. view.start,
  10131. view.end
  10132. )
  10133. );
  10134. }
  10135. return events;
  10136. };
  10137. ;;
  10138. /* An abstract class for the "basic" views, as well as month view. Renders one or more rows of day cells.
  10139. ----------------------------------------------------------------------------------------------------------------------*/
  10140. // It is a manager for a DayGrid subcomponent, which does most of the heavy lifting.
  10141. // It is responsible for managing width/height.
  10142. var BasicView = FC.BasicView = View.extend({
  10143. scroller: null,
  10144. dayGridClass: DayGrid, // class the dayGrid will be instantiated from (overridable by subclasses)
  10145. dayGrid: null, // the main subcomponent that does most of the heavy lifting
  10146. dayNumbersVisible: false, // display day numbers on each day cell?
  10147. colWeekNumbersVisible: false, // display week numbers along the side?
  10148. cellWeekNumbersVisible: false, // display week numbers in day cell?
  10149. weekNumberWidth: null, // width of all the week-number cells running down the side
  10150. headContainerEl: null, // div that hold's the dayGrid's rendered date header
  10151. headRowEl: null, // the fake row element of the day-of-week header
  10152. initialize: function() {
  10153. this.dayGrid = this.instantiateDayGrid();
  10154. this.scroller = new Scroller({
  10155. overflowX: 'hidden',
  10156. overflowY: 'auto'
  10157. });
  10158. },
  10159. // Generates the DayGrid object this view needs. Draws from this.dayGridClass
  10160. instantiateDayGrid: function() {
  10161. // generate a subclass on the fly with BasicView-specific behavior
  10162. // TODO: cache this subclass
  10163. var subclass = this.dayGridClass.extend(basicDayGridMethods);
  10164. return new subclass(this);
  10165. },
  10166. // Sets the display range and computes all necessary dates
  10167. setRange: function(range) {
  10168. View.prototype.setRange.call(this, range); // call the super-method
  10169. this.dayGrid.breakOnWeeks = /year|month|week/.test(this.intervalUnit); // do before setRange
  10170. this.dayGrid.setRange(range);
  10171. },
  10172. // Compute the value to feed into setRange. Overrides superclass.
  10173. computeRange: function(date) {
  10174. var range = View.prototype.computeRange.call(this, date); // get value from the super-method
  10175. // year and month views should be aligned with weeks. this is already done for week
  10176. if (/year|month/.test(range.intervalUnit)) {
  10177. range.start.startOf('week');
  10178. range.start = this.skipHiddenDays(range.start);
  10179. // make end-of-week if not already
  10180. if (range.end.weekday()) {
  10181. range.end.add(1, 'week').startOf('week');
  10182. range.end = this.skipHiddenDays(range.end, -1, true); // exclusively move backwards
  10183. }
  10184. }
  10185. return range;
  10186. },
  10187. // Renders the view into `this.el`, which should already be assigned
  10188. renderDates: function() {
  10189. this.dayNumbersVisible = this.dayGrid.rowCnt > 1; // TODO: make grid responsible
  10190. if (this.opt('weekNumbers')) {
  10191. if (this.opt('weekNumbersWithinDays')) {
  10192. this.cellWeekNumbersVisible = true;
  10193. this.colWeekNumbersVisible = false;
  10194. }
  10195. else {
  10196. this.cellWeekNumbersVisible = false;
  10197. this.colWeekNumbersVisible = true;
  10198. };
  10199. }
  10200. this.dayGrid.numbersVisible = this.dayNumbersVisible ||
  10201. this.cellWeekNumbersVisible || this.colWeekNumbersVisible;
  10202. this.el.addClass('fc-basic-view').html(this.renderSkeletonHtml());
  10203. this.renderHead();
  10204. this.scroller.render();
  10205. var dayGridContainerEl = this.scroller.el.addClass('fc-day-grid-container');
  10206. var dayGridEl = $('<div class="fc-day-grid" />').appendTo(dayGridContainerEl);
  10207. this.el.find('.fc-body > tr > td').append(dayGridContainerEl);
  10208. this.dayGrid.setElement(dayGridEl);
  10209. this.dayGrid.renderDates(this.hasRigidRows());
  10210. },
  10211. // render the day-of-week headers
  10212. renderHead: function() {
  10213. this.headContainerEl =
  10214. this.el.find('.fc-head-container')
  10215. .html(this.dayGrid.renderHeadHtml());
  10216. this.headRowEl = this.headContainerEl.find('.fc-row');
  10217. },
  10218. // Unrenders the content of the view. Since we haven't separated skeleton rendering from date rendering,
  10219. // always completely kill the dayGrid's rendering.
  10220. unrenderDates: function() {
  10221. this.dayGrid.unrenderDates();
  10222. this.dayGrid.removeElement();
  10223. this.scroller.destroy();
  10224. },
  10225. renderBusinessHours: function() {
  10226. this.dayGrid.renderBusinessHours();
  10227. },
  10228. unrenderBusinessHours: function() {
  10229. this.dayGrid.unrenderBusinessHours();
  10230. },
  10231. // Builds the HTML skeleton for the view.
  10232. // The day-grid component will render inside of a container defined by this HTML.
  10233. renderSkeletonHtml: function() {
  10234. return '' +
  10235. '<table>' +
  10236. '<thead class="fc-head">' +
  10237. '<tr>' +
  10238. '<td class="fc-head-container ' + this.widgetHeaderClass + '"></td>' +
  10239. '</tr>' +
  10240. '</thead>' +
  10241. '<tbody class="fc-body">' +
  10242. '<tr>' +
  10243. '<td class="' + this.widgetContentClass + '"></td>' +
  10244. '</tr>' +
  10245. '</tbody>' +
  10246. '</table>';
  10247. },
  10248. // Generates an HTML attribute string for setting the width of the week number column, if it is known
  10249. weekNumberStyleAttr: function() {
  10250. if (this.weekNumberWidth !== null) {
  10251. return 'style="width:' + this.weekNumberWidth + 'px"';
  10252. }
  10253. return '';
  10254. },
  10255. // Determines whether each row should have a constant height
  10256. hasRigidRows: function() {
  10257. var eventLimit = this.opt('eventLimit');
  10258. return eventLimit && typeof eventLimit !== 'number';
  10259. },
  10260. /* Dimensions
  10261. ------------------------------------------------------------------------------------------------------------------*/
  10262. // Refreshes the horizontal dimensions of the view
  10263. updateWidth: function() {
  10264. if (this.colWeekNumbersVisible) {
  10265. // Make sure all week number cells running down the side have the same width.
  10266. // Record the width for cells created later.
  10267. this.weekNumberWidth = matchCellWidths(
  10268. this.el.find('.fc-week-number')
  10269. );
  10270. }
  10271. },
  10272. // Adjusts the vertical dimensions of the view to the specified values
  10273. setHeight: function(totalHeight, isAuto) {
  10274. var eventLimit = this.opt('eventLimit');
  10275. var scrollerHeight;
  10276. var scrollbarWidths;
  10277. // reset all heights to be natural
  10278. this.scroller.clear();
  10279. uncompensateScroll(this.headRowEl);
  10280. this.dayGrid.removeSegPopover(); // kill the "more" popover if displayed
  10281. // is the event limit a constant level number?
  10282. if (eventLimit && typeof eventLimit === 'number') {
  10283. this.dayGrid.limitRows(eventLimit); // limit the levels first so the height can redistribute after
  10284. }
  10285. // distribute the height to the rows
  10286. // (totalHeight is a "recommended" value if isAuto)
  10287. scrollerHeight = this.computeScrollerHeight(totalHeight);
  10288. this.setGridHeight(scrollerHeight, isAuto);
  10289. // is the event limit dynamically calculated?
  10290. if (eventLimit && typeof eventLimit !== 'number') {
  10291. this.dayGrid.limitRows(eventLimit); // limit the levels after the grid's row heights have been set
  10292. }
  10293. if (!isAuto) { // should we force dimensions of the scroll container?
  10294. this.scroller.setHeight(scrollerHeight);
  10295. scrollbarWidths = this.scroller.getScrollbarWidths();
  10296. if (scrollbarWidths.left || scrollbarWidths.right) { // using scrollbars?
  10297. compensateScroll(this.headRowEl, scrollbarWidths);
  10298. // doing the scrollbar compensation might have created text overflow which created more height. redo
  10299. scrollerHeight = this.computeScrollerHeight(totalHeight);
  10300. this.scroller.setHeight(scrollerHeight);
  10301. }
  10302. // guarantees the same scrollbar widths
  10303. this.scroller.lockOverflow(scrollbarWidths);
  10304. }
  10305. },
  10306. // given a desired total height of the view, returns what the height of the scroller should be
  10307. computeScrollerHeight: function(totalHeight) {
  10308. return totalHeight -
  10309. subtractInnerElHeight(this.el, this.scroller.el); // everything that's NOT the scroller
  10310. },
  10311. // Sets the height of just the DayGrid component in this view
  10312. setGridHeight: function(height, isAuto) {
  10313. if (isAuto) {
  10314. undistributeHeight(this.dayGrid.rowEls); // let the rows be their natural height with no expanding
  10315. }
  10316. else {
  10317. distributeHeight(this.dayGrid.rowEls, height, true); // true = compensate for height-hogging rows
  10318. }
  10319. },
  10320. /* Scroll
  10321. ------------------------------------------------------------------------------------------------------------------*/
  10322. computeInitialScroll: function() {
  10323. return { top: 0 };
  10324. },
  10325. queryScroll: function() {
  10326. return { top: this.scroller.getScrollTop() };
  10327. },
  10328. setScroll: function(scroll) {
  10329. this.scroller.setScrollTop(scroll.top);
  10330. },
  10331. /* Hit Areas
  10332. ------------------------------------------------------------------------------------------------------------------*/
  10333. // forward all hit-related method calls to dayGrid
  10334. hitsNeeded: function() {
  10335. this.dayGrid.hitsNeeded();
  10336. },
  10337. hitsNotNeeded: function() {
  10338. this.dayGrid.hitsNotNeeded();
  10339. },
  10340. prepareHits: function() {
  10341. this.dayGrid.prepareHits();
  10342. },
  10343. releaseHits: function() {
  10344. this.dayGrid.releaseHits();
  10345. },
  10346. queryHit: function(left, top) {
  10347. return this.dayGrid.queryHit(left, top);
  10348. },
  10349. getHitSpan: function(hit) {
  10350. return this.dayGrid.getHitSpan(hit);
  10351. },
  10352. getHitEl: function(hit) {
  10353. return this.dayGrid.getHitEl(hit);
  10354. },
  10355. /* Events
  10356. ------------------------------------------------------------------------------------------------------------------*/
  10357. // Renders the given events onto the view and populates the segments array
  10358. renderEvents: function(events) {
  10359. this.dayGrid.renderEvents(events);
  10360. this.updateHeight(); // must compensate for events that overflow the row
  10361. },
  10362. // Retrieves all segment objects that are rendered in the view
  10363. getEventSegs: function() {
  10364. return this.dayGrid.getEventSegs();
  10365. },
  10366. // Unrenders all event elements and clears internal segment data
  10367. unrenderEvents: function() {
  10368. this.dayGrid.unrenderEvents();
  10369. // we DON'T need to call updateHeight() because
  10370. // a renderEvents() call always happens after this, which will eventually call updateHeight()
  10371. },
  10372. /* Dragging (for both events and external elements)
  10373. ------------------------------------------------------------------------------------------------------------------*/
  10374. // A returned value of `true` signals that a mock "helper" event has been rendered.
  10375. renderDrag: function(dropLocation, seg) {
  10376. return this.dayGrid.renderDrag(dropLocation, seg);
  10377. },
  10378. unrenderDrag: function() {
  10379. this.dayGrid.unrenderDrag();
  10380. },
  10381. /* Selection
  10382. ------------------------------------------------------------------------------------------------------------------*/
  10383. // Renders a visual indication of a selection
  10384. renderSelection: function(span) {
  10385. this.dayGrid.renderSelection(span);
  10386. },
  10387. // Unrenders a visual indications of a selection
  10388. unrenderSelection: function() {
  10389. this.dayGrid.unrenderSelection();
  10390. }
  10391. });
  10392. // Methods that will customize the rendering behavior of the BasicView's dayGrid
  10393. var basicDayGridMethods = {
  10394. // Generates the HTML that will go before the day-of week header cells
  10395. renderHeadIntroHtml: function() {
  10396. var view = this.view;
  10397. if (view.colWeekNumbersVisible) {
  10398. return '' +
  10399. '<th class="fc-week-number ' + view.widgetHeaderClass + '" ' + view.weekNumberStyleAttr() + '>' +
  10400. '<span>' + // needed for matchCellWidths
  10401. htmlEscape(view.opt('weekNumberTitle')) +
  10402. '</span>' +
  10403. '</th>';
  10404. }
  10405. return '';
  10406. },
  10407. // Generates the HTML that will go before content-skeleton cells that display the day/week numbers
  10408. renderNumberIntroHtml: function(row) {
  10409. var view = this.view;
  10410. var weekStart = this.getCellDate(row, 0);
  10411. if (view.colWeekNumbersVisible) {
  10412. return '' +
  10413. '<td class="fc-week-number" ' + view.weekNumberStyleAttr() + '>' +
  10414. view.buildGotoAnchorHtml( // aside from link, important for matchCellWidths
  10415. { date: weekStart, type: 'week', forceOff: this.colCnt === 1 },
  10416. weekStart.format('w') // inner HTML
  10417. ) +
  10418. '</td>';
  10419. }
  10420. return '';
  10421. },
  10422. // Generates the HTML that goes before the day bg cells for each day-row
  10423. renderBgIntroHtml: function() {
  10424. var view = this.view;
  10425. if (view.colWeekNumbersVisible) {
  10426. return '<td class="fc-week-number ' + view.widgetContentClass + '" ' +
  10427. view.weekNumberStyleAttr() + '></td>';
  10428. }
  10429. return '';
  10430. },
  10431. // Generates the HTML that goes before every other type of row generated by DayGrid.
  10432. // Affects helper-skeleton and highlight-skeleton rows.
  10433. renderIntroHtml: function() {
  10434. var view = this.view;
  10435. if (view.colWeekNumbersVisible) {
  10436. return '<td class="fc-week-number" ' + view.weekNumberStyleAttr() + '></td>';
  10437. }
  10438. return '';
  10439. }
  10440. };
  10441. ;;
  10442. /* A month view with day cells running in rows (one-per-week) and columns
  10443. ----------------------------------------------------------------------------------------------------------------------*/
  10444. var MonthView = FC.MonthView = BasicView.extend({
  10445. // Produces information about what range to display
  10446. computeRange: function(date) {
  10447. var range = BasicView.prototype.computeRange.call(this, date); // get value from super-method
  10448. var rowCnt;
  10449. // ensure 6 weeks
  10450. if (this.isFixedWeeks()) {
  10451. rowCnt = Math.ceil(range.end.diff(range.start, 'weeks', true)); // could be partial weeks due to hiddenDays
  10452. range.end.add(6 - rowCnt, 'weeks');
  10453. }
  10454. return range;
  10455. },
  10456. // Overrides the default BasicView behavior to have special multi-week auto-height logic
  10457. setGridHeight: function(height, isAuto) {
  10458. // if auto, make the height of each row the height that it would be if there were 6 weeks
  10459. if (isAuto) {
  10460. height *= this.rowCnt / 6;
  10461. }
  10462. distributeHeight(this.dayGrid.rowEls, height, !isAuto); // if auto, don't compensate for height-hogging rows
  10463. },
  10464. isFixedWeeks: function() {
  10465. return this.opt('fixedWeekCount');
  10466. }
  10467. });
  10468. ;;
  10469. fcViews.basic = {
  10470. 'class': BasicView
  10471. };
  10472. fcViews.basicDay = {
  10473. type: 'basic',
  10474. duration: { days: 1 }
  10475. };
  10476. fcViews.basicWeek = {
  10477. type: 'basic',
  10478. duration: { weeks: 1 }
  10479. };
  10480. fcViews.month = {
  10481. 'class': MonthView,
  10482. duration: { months: 1 }, // important for prev/next
  10483. defaults: {
  10484. fixedWeekCount: true
  10485. }
  10486. };
  10487. ;;
  10488. /* An abstract class for all agenda-related views. Displays one more columns with time slots running vertically.
  10489. ----------------------------------------------------------------------------------------------------------------------*/
  10490. // Is a manager for the TimeGrid subcomponent and possibly the DayGrid subcomponent (if allDaySlot is on).
  10491. // Responsible for managing width/height.
  10492. var AgendaView = FC.AgendaView = View.extend({
  10493. scroller: null,
  10494. timeGridClass: TimeGrid, // class used to instantiate the timeGrid. subclasses can override
  10495. timeGrid: null, // the main time-grid subcomponent of this view
  10496. dayGridClass: DayGrid, // class used to instantiate the dayGrid. subclasses can override
  10497. dayGrid: null, // the "all-day" subcomponent. if all-day is turned off, this will be null
  10498. axisWidth: null, // the width of the time axis running down the side
  10499. headContainerEl: null, // div that hold's the timeGrid's rendered date header
  10500. noScrollRowEls: null, // set of fake row elements that must compensate when scroller has scrollbars
  10501. // when the time-grid isn't tall enough to occupy the given height, we render an <hr> underneath
  10502. bottomRuleEl: null,
  10503. initialize: function() {
  10504. this.timeGrid = this.instantiateTimeGrid();
  10505. if (this.opt('allDaySlot')) { // should we display the "all-day" area?
  10506. this.dayGrid = this.instantiateDayGrid(); // the all-day subcomponent of this view
  10507. }
  10508. this.scroller = new Scroller({
  10509. overflowX: 'hidden',
  10510. overflowY: 'auto'
  10511. });
  10512. },
  10513. // Instantiates the TimeGrid object this view needs. Draws from this.timeGridClass
  10514. instantiateTimeGrid: function() {
  10515. var subclass = this.timeGridClass.extend(agendaTimeGridMethods);
  10516. return new subclass(this);
  10517. },
  10518. // Instantiates the DayGrid object this view might need. Draws from this.dayGridClass
  10519. instantiateDayGrid: function() {
  10520. var subclass = this.dayGridClass.extend(agendaDayGridMethods);
  10521. return new subclass(this);
  10522. },
  10523. /* Rendering
  10524. ------------------------------------------------------------------------------------------------------------------*/
  10525. // Sets the display range and computes all necessary dates
  10526. setRange: function(range) {
  10527. View.prototype.setRange.call(this, range); // call the super-method
  10528. this.timeGrid.setRange(range);
  10529. if (this.dayGrid) {
  10530. this.dayGrid.setRange(range);
  10531. }
  10532. },
  10533. // Renders the view into `this.el`, which has already been assigned
  10534. renderDates: function() {
  10535. this.el.addClass('fc-agenda-view').html(this.renderSkeletonHtml());
  10536. this.renderHead();
  10537. this.scroller.render();
  10538. var timeGridWrapEl = this.scroller.el.addClass('fc-time-grid-container');
  10539. var timeGridEl = $('<div class="fc-time-grid" />').appendTo(timeGridWrapEl);
  10540. this.el.find('.fc-body > tr > td').append(timeGridWrapEl);
  10541. this.timeGrid.setElement(timeGridEl);
  10542. this.timeGrid.renderDates();
  10543. // the <hr> that sometimes displays under the time-grid
  10544. this.bottomRuleEl = $('<hr class="fc-divider ' + this.widgetHeaderClass + '"/>')
  10545. .appendTo(this.timeGrid.el); // inject it into the time-grid
  10546. if (this.dayGrid) {
  10547. this.dayGrid.setElement(this.el.find('.fc-day-grid'));
  10548. this.dayGrid.renderDates();
  10549. // have the day-grid extend it's coordinate area over the <hr> dividing the two grids
  10550. this.dayGrid.bottomCoordPadding = this.dayGrid.el.next('hr').outerHeight();
  10551. }
  10552. this.noScrollRowEls = this.el.find('.fc-row:not(.fc-scroller *)'); // fake rows not within the scroller
  10553. },
  10554. // render the day-of-week headers
  10555. renderHead: function() {
  10556. this.headContainerEl =
  10557. this.el.find('.fc-head-container')
  10558. .html(this.timeGrid.renderHeadHtml());
  10559. },
  10560. // Unrenders the content of the view. Since we haven't separated skeleton rendering from date rendering,
  10561. // always completely kill each grid's rendering.
  10562. unrenderDates: function() {
  10563. this.timeGrid.unrenderDates();
  10564. this.timeGrid.removeElement();
  10565. if (this.dayGrid) {
  10566. this.dayGrid.unrenderDates();
  10567. this.dayGrid.removeElement();
  10568. }
  10569. this.scroller.destroy();
  10570. },
  10571. // Builds the HTML skeleton for the view.
  10572. // The day-grid and time-grid components will render inside containers defined by this HTML.
  10573. renderSkeletonHtml: function() {
  10574. return '' +
  10575. '<table>' +
  10576. '<thead class="fc-head">' +
  10577. '<tr>' +
  10578. '<td class="fc-head-container ' + this.widgetHeaderClass + '"></td>' +
  10579. '</tr>' +
  10580. '</thead>' +
  10581. '<tbody class="fc-body">' +
  10582. '<tr>' +
  10583. '<td class="' + this.widgetContentClass + '">' +
  10584. (this.dayGrid ?
  10585. '<div class="fc-day-grid"/>' +
  10586. '<hr class="fc-divider ' + this.widgetHeaderClass + '"/>' :
  10587. ''
  10588. ) +
  10589. '</td>' +
  10590. '</tr>' +
  10591. '</tbody>' +
  10592. '</table>';
  10593. },
  10594. // Generates an HTML attribute string for setting the width of the axis, if it is known
  10595. axisStyleAttr: function() {
  10596. if (this.axisWidth !== null) {
  10597. return 'style="width:' + this.axisWidth + 'px"';
  10598. }
  10599. return '';
  10600. },
  10601. /* Business Hours
  10602. ------------------------------------------------------------------------------------------------------------------*/
  10603. renderBusinessHours: function() {
  10604. this.timeGrid.renderBusinessHours();
  10605. if (this.dayGrid) {
  10606. this.dayGrid.renderBusinessHours();
  10607. }
  10608. },
  10609. unrenderBusinessHours: function() {
  10610. this.timeGrid.unrenderBusinessHours();
  10611. if (this.dayGrid) {
  10612. this.dayGrid.unrenderBusinessHours();
  10613. }
  10614. },
  10615. /* Now Indicator
  10616. ------------------------------------------------------------------------------------------------------------------*/
  10617. getNowIndicatorUnit: function() {
  10618. return this.timeGrid.getNowIndicatorUnit();
  10619. },
  10620. renderNowIndicator: function(date) {
  10621. this.timeGrid.renderNowIndicator(date);
  10622. },
  10623. unrenderNowIndicator: function() {
  10624. this.timeGrid.unrenderNowIndicator();
  10625. },
  10626. /* Dimensions
  10627. ------------------------------------------------------------------------------------------------------------------*/
  10628. updateSize: function(isResize) {
  10629. this.timeGrid.updateSize(isResize);
  10630. View.prototype.updateSize.call(this, isResize); // call the super-method
  10631. },
  10632. // Refreshes the horizontal dimensions of the view
  10633. updateWidth: function() {
  10634. // make all axis cells line up, and record the width so newly created axis cells will have it
  10635. this.axisWidth = matchCellWidths(this.el.find('.fc-axis'));
  10636. },
  10637. // Adjusts the vertical dimensions of the view to the specified values
  10638. setHeight: function(totalHeight, isAuto) {
  10639. var eventLimit;
  10640. var scrollerHeight;
  10641. var scrollbarWidths;
  10642. // reset all dimensions back to the original state
  10643. this.bottomRuleEl.hide(); // .show() will be called later if this <hr> is necessary
  10644. this.scroller.clear(); // sets height to 'auto' and clears overflow
  10645. uncompensateScroll(this.noScrollRowEls);
  10646. // limit number of events in the all-day area
  10647. if (this.dayGrid) {
  10648. this.dayGrid.removeSegPopover(); // kill the "more" popover if displayed
  10649. eventLimit = this.opt('eventLimit');
  10650. if (eventLimit && typeof eventLimit !== 'number') {
  10651. eventLimit = AGENDA_ALL_DAY_EVENT_LIMIT; // make sure "auto" goes to a real number
  10652. }
  10653. if (eventLimit) {
  10654. this.dayGrid.limitRows(eventLimit);
  10655. }
  10656. }
  10657. if (!isAuto) { // should we force dimensions of the scroll container?
  10658. scrollerHeight = this.computeScrollerHeight(totalHeight);
  10659. this.scroller.setHeight(scrollerHeight);
  10660. scrollbarWidths = this.scroller.getScrollbarWidths();
  10661. if (scrollbarWidths.left || scrollbarWidths.right) { // using scrollbars?
  10662. // make the all-day and header rows lines up
  10663. compensateScroll(this.noScrollRowEls, scrollbarWidths);
  10664. // the scrollbar compensation might have changed text flow, which might affect height, so recalculate
  10665. // and reapply the desired height to the scroller.
  10666. scrollerHeight = this.computeScrollerHeight(totalHeight);
  10667. this.scroller.setHeight(scrollerHeight);
  10668. }
  10669. // guarantees the same scrollbar widths
  10670. this.scroller.lockOverflow(scrollbarWidths);
  10671. // if there's any space below the slats, show the horizontal rule.
  10672. // this won't cause any new overflow, because lockOverflow already called.
  10673. if (this.timeGrid.getTotalSlatHeight() < scrollerHeight) {
  10674. this.bottomRuleEl.show();
  10675. }
  10676. }
  10677. },
  10678. // given a desired total height of the view, returns what the height of the scroller should be
  10679. computeScrollerHeight: function(totalHeight) {
  10680. return totalHeight -
  10681. subtractInnerElHeight(this.el, this.scroller.el); // everything that's NOT the scroller
  10682. },
  10683. /* Scroll
  10684. ------------------------------------------------------------------------------------------------------------------*/
  10685. // Computes the initial pre-configured scroll state prior to allowing the user to change it
  10686. computeInitialScroll: function() {
  10687. var scrollTime = moment.duration(this.opt('scrollTime'));
  10688. var top = this.timeGrid.computeTimeTop(scrollTime);
  10689. // zoom can give weird floating-point values. rather scroll a little bit further
  10690. top = Math.ceil(top);
  10691. if (top) {
  10692. top++; // to overcome top border that slots beyond the first have. looks better
  10693. }
  10694. return { top: top };
  10695. },
  10696. queryScroll: function() {
  10697. return { top: this.scroller.getScrollTop() };
  10698. },
  10699. setScroll: function(scroll) {
  10700. this.scroller.setScrollTop(scroll.top);
  10701. },
  10702. /* Hit Areas
  10703. ------------------------------------------------------------------------------------------------------------------*/
  10704. // forward all hit-related method calls to the grids (dayGrid might not be defined)
  10705. hitsNeeded: function() {
  10706. this.timeGrid.hitsNeeded();
  10707. if (this.dayGrid) {
  10708. this.dayGrid.hitsNeeded();
  10709. }
  10710. },
  10711. hitsNotNeeded: function() {
  10712. this.timeGrid.hitsNotNeeded();
  10713. if (this.dayGrid) {
  10714. this.dayGrid.hitsNotNeeded();
  10715. }
  10716. },
  10717. prepareHits: function() {
  10718. this.timeGrid.prepareHits();
  10719. if (this.dayGrid) {
  10720. this.dayGrid.prepareHits();
  10721. }
  10722. },
  10723. releaseHits: function() {
  10724. this.timeGrid.releaseHits();
  10725. if (this.dayGrid) {
  10726. this.dayGrid.releaseHits();
  10727. }
  10728. },
  10729. queryHit: function(left, top) {
  10730. var hit = this.timeGrid.queryHit(left, top);
  10731. if (!hit && this.dayGrid) {
  10732. hit = this.dayGrid.queryHit(left, top);
  10733. }
  10734. return hit;
  10735. },
  10736. getHitSpan: function(hit) {
  10737. // TODO: hit.component is set as a hack to identify where the hit came from
  10738. return hit.component.getHitSpan(hit);
  10739. },
  10740. getHitEl: function(hit) {
  10741. // TODO: hit.component is set as a hack to identify where the hit came from
  10742. return hit.component.getHitEl(hit);
  10743. },
  10744. /* Events
  10745. ------------------------------------------------------------------------------------------------------------------*/
  10746. // Renders events onto the view and populates the View's segment array
  10747. renderEvents: function(events) {
  10748. var dayEvents = [];
  10749. var timedEvents = [];
  10750. var daySegs = [];
  10751. var timedSegs;
  10752. var i;
  10753. // separate the events into all-day and timed
  10754. for (i = 0; i < events.length; i++) {
  10755. if (events[i].allDay) {
  10756. dayEvents.push(events[i]);
  10757. }
  10758. else {
  10759. timedEvents.push(events[i]);
  10760. }
  10761. }
  10762. // render the events in the subcomponents
  10763. timedSegs = this.timeGrid.renderEvents(timedEvents);
  10764. if (this.dayGrid) {
  10765. daySegs = this.dayGrid.renderEvents(dayEvents);
  10766. }
  10767. // the all-day area is flexible and might have a lot of events, so shift the height
  10768. this.updateHeight();
  10769. },
  10770. // Retrieves all segment objects that are rendered in the view
  10771. getEventSegs: function() {
  10772. return this.timeGrid.getEventSegs().concat(
  10773. this.dayGrid ? this.dayGrid.getEventSegs() : []
  10774. );
  10775. },
  10776. // Unrenders all event elements and clears internal segment data
  10777. unrenderEvents: function() {
  10778. // unrender the events in the subcomponents
  10779. this.timeGrid.unrenderEvents();
  10780. if (this.dayGrid) {
  10781. this.dayGrid.unrenderEvents();
  10782. }
  10783. // we DON'T need to call updateHeight() because
  10784. // a renderEvents() call always happens after this, which will eventually call updateHeight()
  10785. },
  10786. /* Dragging (for events and external elements)
  10787. ------------------------------------------------------------------------------------------------------------------*/
  10788. // A returned value of `true` signals that a mock "helper" event has been rendered.
  10789. renderDrag: function(dropLocation, seg) {
  10790. if (dropLocation.start.hasTime()) {
  10791. return this.timeGrid.renderDrag(dropLocation, seg);
  10792. }
  10793. else if (this.dayGrid) {
  10794. return this.dayGrid.renderDrag(dropLocation, seg);
  10795. }
  10796. },
  10797. unrenderDrag: function() {
  10798. this.timeGrid.unrenderDrag();
  10799. if (this.dayGrid) {
  10800. this.dayGrid.unrenderDrag();
  10801. }
  10802. },
  10803. /* Selection
  10804. ------------------------------------------------------------------------------------------------------------------*/
  10805. // Renders a visual indication of a selection
  10806. renderSelection: function(span) {
  10807. if (span.start.hasTime() || span.end.hasTime()) {
  10808. this.timeGrid.renderSelection(span);
  10809. }
  10810. else if (this.dayGrid) {
  10811. this.dayGrid.renderSelection(span);
  10812. }
  10813. },
  10814. // Unrenders a visual indications of a selection
  10815. unrenderSelection: function() {
  10816. this.timeGrid.unrenderSelection();
  10817. if (this.dayGrid) {
  10818. this.dayGrid.unrenderSelection();
  10819. }
  10820. }
  10821. });
  10822. // Methods that will customize the rendering behavior of the AgendaView's timeGrid
  10823. // TODO: move into TimeGrid
  10824. var agendaTimeGridMethods = {
  10825. // Generates the HTML that will go before the day-of week header cells
  10826. renderHeadIntroHtml: function() {
  10827. var view = this.view;
  10828. var weekText;
  10829. if (view.opt('weekNumbers')) {
  10830. weekText = this.start.format(view.opt('smallWeekFormat'));
  10831. return '' +
  10832. '<th class="fc-axis fc-week-number ' + view.widgetHeaderClass + '" ' + view.axisStyleAttr() + '>' +
  10833. view.buildGotoAnchorHtml( // aside from link, important for matchCellWidths
  10834. { date: this.start, type: 'week', forceOff: this.colCnt > 1 },
  10835. htmlEscape(weekText) // inner HTML
  10836. ) +
  10837. '</th>';
  10838. }
  10839. else {
  10840. return '<th class="fc-axis ' + view.widgetHeaderClass + '" ' + view.axisStyleAttr() + '></th>';
  10841. }
  10842. },
  10843. // Generates the HTML that goes before the bg of the TimeGrid slot area. Long vertical column.
  10844. renderBgIntroHtml: function() {
  10845. var view = this.view;
  10846. return '<td class="fc-axis ' + view.widgetContentClass + '" ' + view.axisStyleAttr() + '></td>';
  10847. },
  10848. // Generates the HTML that goes before all other types of cells.
  10849. // Affects content-skeleton, helper-skeleton, highlight-skeleton for both the time-grid and day-grid.
  10850. renderIntroHtml: function() {
  10851. var view = this.view;
  10852. return '<td class="fc-axis" ' + view.axisStyleAttr() + '></td>';
  10853. }
  10854. };
  10855. // Methods that will customize the rendering behavior of the AgendaView's dayGrid
  10856. var agendaDayGridMethods = {
  10857. // Generates the HTML that goes before the all-day cells
  10858. renderBgIntroHtml: function() {
  10859. var view = this.view;
  10860. return '' +
  10861. '<td class="fc-axis ' + view.widgetContentClass + '" ' + view.axisStyleAttr() + '>' +
  10862. '<span>' + // needed for matchCellWidths
  10863. view.getAllDayHtml() +
  10864. '</span>' +
  10865. '</td>';
  10866. },
  10867. // Generates the HTML that goes before all other types of cells.
  10868. // Affects content-skeleton, helper-skeleton, highlight-skeleton for both the time-grid and day-grid.
  10869. renderIntroHtml: function() {
  10870. var view = this.view;
  10871. return '<td class="fc-axis" ' + view.axisStyleAttr() + '></td>';
  10872. }
  10873. };
  10874. ;;
  10875. var AGENDA_ALL_DAY_EVENT_LIMIT = 5;
  10876. // potential nice values for the slot-duration and interval-duration
  10877. // from largest to smallest
  10878. var AGENDA_STOCK_SUB_DURATIONS = [
  10879. { hours: 1 },
  10880. { minutes: 30 },
  10881. { minutes: 15 },
  10882. { seconds: 30 },
  10883. { seconds: 15 }
  10884. ];
  10885. fcViews.agenda = {
  10886. 'class': AgendaView,
  10887. defaults: {
  10888. allDaySlot: true,
  10889. slotDuration: '00:30:00',
  10890. minTime: '00:00:00',
  10891. maxTime: '24:00:00',
  10892. slotEventOverlap: true // a bad name. confused with overlap/constraint system
  10893. }
  10894. };
  10895. fcViews.agendaDay = {
  10896. type: 'agenda',
  10897. duration: { days: 1 }
  10898. };
  10899. fcViews.agendaWeek = {
  10900. type: 'agenda',
  10901. duration: { weeks: 1 }
  10902. };
  10903. ;;
  10904. /*
  10905. Responsible for the scroller, and forwarding event-related actions into the "grid"
  10906. */
  10907. var ListView = View.extend({
  10908. grid: null,
  10909. scroller: null,
  10910. initialize: function() {
  10911. this.grid = new ListViewGrid(this);
  10912. this.scroller = new Scroller({
  10913. overflowX: 'hidden',
  10914. overflowY: 'auto'
  10915. });
  10916. },
  10917. setRange: function(range) {
  10918. View.prototype.setRange.call(this, range); // super
  10919. this.grid.setRange(range); // needs to process range-related options
  10920. },
  10921. renderSkeleton: function() {
  10922. this.el.addClass(
  10923. 'fc-list-view ' +
  10924. this.widgetContentClass
  10925. );
  10926. this.scroller.render();
  10927. this.scroller.el.appendTo(this.el);
  10928. this.grid.setElement(this.scroller.scrollEl);
  10929. },
  10930. unrenderSkeleton: function() {
  10931. this.scroller.destroy(); // will remove the Grid too
  10932. },
  10933. setHeight: function(totalHeight, isAuto) {
  10934. this.scroller.setHeight(this.computeScrollerHeight(totalHeight));
  10935. },
  10936. computeScrollerHeight: function(totalHeight) {
  10937. return totalHeight -
  10938. subtractInnerElHeight(this.el, this.scroller.el); // everything that's NOT the scroller
  10939. },
  10940. renderEvents: function(events) {
  10941. this.grid.renderEvents(events);
  10942. },
  10943. unrenderEvents: function() {
  10944. this.grid.unrenderEvents();
  10945. },
  10946. isEventResizable: function(event) {
  10947. return false;
  10948. },
  10949. isEventDraggable: function(event) {
  10950. return false;
  10951. }
  10952. });
  10953. /*
  10954. Responsible for event rendering and user-interaction.
  10955. Its "el" is the inner-content of the above view's scroller.
  10956. */
  10957. var ListViewGrid = Grid.extend({
  10958. segSelector: '.fc-list-item', // which elements accept event actions
  10959. hasDayInteractions: false, // no day selection or day clicking
  10960. // slices by day
  10961. spanToSegs: function(span) {
  10962. var view = this.view;
  10963. var dayStart = view.start.clone().time(0); // timed, so segs get times!
  10964. var dayIndex = 0;
  10965. var seg;
  10966. var segs = [];
  10967. while (dayStart < view.end) {
  10968. seg = intersectRanges(span, {
  10969. start: dayStart,
  10970. end: dayStart.clone().add(1, 'day')
  10971. });
  10972. if (seg) {
  10973. seg.dayIndex = dayIndex;
  10974. segs.push(seg);
  10975. }
  10976. dayStart.add(1, 'day');
  10977. dayIndex++;
  10978. // detect when span won't go fully into the next day,
  10979. // and mutate the latest seg to the be the end.
  10980. if (
  10981. seg && !seg.isEnd && span.end.hasTime() &&
  10982. span.end < dayStart.clone().add(this.view.nextDayThreshold)
  10983. ) {
  10984. seg.end = span.end.clone();
  10985. seg.isEnd = true;
  10986. break;
  10987. }
  10988. }
  10989. return segs;
  10990. },
  10991. // like "4:00am"
  10992. computeEventTimeFormat: function() {
  10993. return this.view.opt('mediumTimeFormat');
  10994. },
  10995. // for events with a url, the whole <tr> should be clickable,
  10996. // but it's impossible to wrap with an <a> tag. simulate this.
  10997. handleSegClick: function(seg, ev) {
  10998. var url;
  10999. Grid.prototype.handleSegClick.apply(this, arguments); // super. might prevent the default action
  11000. // not clicking on or within an <a> with an href
  11001. if (!$(ev.target).closest('a[href]').length) {
  11002. url = seg.event.url;
  11003. if (url && !ev.isDefaultPrevented()) { // jsEvent not cancelled in handler
  11004. window.location.href = url; // simulate link click
  11005. }
  11006. }
  11007. },
  11008. // returns list of foreground segs that were actually rendered
  11009. renderFgSegs: function(segs) {
  11010. segs = this.renderFgSegEls(segs); // might filter away hidden events
  11011. if (!segs.length) {
  11012. this.renderEmptyMessage();
  11013. }
  11014. else {
  11015. this.renderSegList(segs);
  11016. }
  11017. return segs;
  11018. },
  11019. renderEmptyMessage: function() {
  11020. this.el.html(
  11021. '<div class="fc-list-empty-wrap2">' + // TODO: try less wraps
  11022. '<div class="fc-list-empty-wrap1">' +
  11023. '<div class="fc-list-empty">' +
  11024. htmlEscape(this.view.opt('noEventsMessage')) +
  11025. '</div>' +
  11026. '</div>' +
  11027. '</div>'
  11028. );
  11029. },
  11030. // render the event segments in the view
  11031. renderSegList: function(allSegs) {
  11032. var segsByDay = this.groupSegsByDay(allSegs); // sparse array
  11033. var dayIndex;
  11034. var daySegs;
  11035. var i;
  11036. var tableEl = $('<table class="fc-list-table"><tbody/></table>');
  11037. var tbodyEl = tableEl.find('tbody');
  11038. for (dayIndex = 0; dayIndex < segsByDay.length; dayIndex++) {
  11039. daySegs = segsByDay[dayIndex];
  11040. if (daySegs) { // sparse array, so might be undefined
  11041. // append a day header
  11042. tbodyEl.append(this.dayHeaderHtml(
  11043. this.view.start.clone().add(dayIndex, 'days')
  11044. ));
  11045. this.sortEventSegs(daySegs);
  11046. for (i = 0; i < daySegs.length; i++) {
  11047. tbodyEl.append(daySegs[i].el); // append event row
  11048. }
  11049. }
  11050. }
  11051. this.el.empty().append(tableEl);
  11052. },
  11053. // Returns a sparse array of arrays, segs grouped by their dayIndex
  11054. groupSegsByDay: function(segs) {
  11055. var segsByDay = []; // sparse array
  11056. var i, seg;
  11057. for (i = 0; i < segs.length; i++) {
  11058. seg = segs[i];
  11059. (segsByDay[seg.dayIndex] || (segsByDay[seg.dayIndex] = []))
  11060. .push(seg);
  11061. }
  11062. return segsByDay;
  11063. },
  11064. // generates the HTML for the day headers that live amongst the event rows
  11065. dayHeaderHtml: function(dayDate) {
  11066. var view = this.view;
  11067. var mainFormat = view.opt('listDayFormat');
  11068. var altFormat = view.opt('listDayAltFormat');
  11069. return '<tr class="fc-list-heading" data-date="' + dayDate.format('YYYY-MM-DD') + '">' +
  11070. '<td class="' + view.widgetHeaderClass + '" colspan="3">' +
  11071. (mainFormat ?
  11072. view.buildGotoAnchorHtml(
  11073. dayDate,
  11074. { 'class': 'fc-list-heading-main' },
  11075. htmlEscape(dayDate.format(mainFormat)) // inner HTML
  11076. ) :
  11077. '') +
  11078. (altFormat ?
  11079. view.buildGotoAnchorHtml(
  11080. dayDate,
  11081. { 'class': 'fc-list-heading-alt' },
  11082. htmlEscape(dayDate.format(altFormat)) // inner HTML
  11083. ) :
  11084. '') +
  11085. '</td>' +
  11086. '</tr>';
  11087. },
  11088. // generates the HTML for a single event row
  11089. fgSegHtml: function(seg) {
  11090. var view = this.view;
  11091. var classes = [ 'fc-list-item' ].concat(this.getSegCustomClasses(seg));
  11092. var bgColor = this.getSegBackgroundColor(seg);
  11093. var event = seg.event;
  11094. var url = event.url;
  11095. var timeHtml;
  11096. if (event.allDay) {
  11097. timeHtml = view.getAllDayHtml();
  11098. }
  11099. else if (view.isMultiDayEvent(event)) { // if the event appears to span more than one day
  11100. if (seg.isStart || seg.isEnd) { // outer segment that probably lasts part of the day
  11101. timeHtml = htmlEscape(this.getEventTimeText(seg));
  11102. }
  11103. else { // inner segment that lasts the whole day
  11104. timeHtml = view.getAllDayHtml();
  11105. }
  11106. }
  11107. else {
  11108. // Display the normal time text for the *event's* times
  11109. timeHtml = htmlEscape(this.getEventTimeText(event));
  11110. }
  11111. if (url) {
  11112. classes.push('fc-has-url');
  11113. }
  11114. return '<tr class="' + classes.join(' ') + '">' +
  11115. (this.displayEventTime ?
  11116. '<td class="fc-list-item-time ' + view.widgetContentClass + '">' +
  11117. (timeHtml || '') +
  11118. '</td>' :
  11119. '') +
  11120. '<td class="fc-list-item-marker ' + view.widgetContentClass + '">' +
  11121. '<span class="fc-event-dot"' +
  11122. (bgColor ?
  11123. ' style="background-color:' + bgColor + '"' :
  11124. '') +
  11125. '></span>' +
  11126. '</td>' +
  11127. '<td class="fc-list-item-title ' + view.widgetContentClass + '">' +
  11128. '<a' + (url ? ' href="' + htmlEscape(url) + '"' : '') + '>' +
  11129. htmlEscape(seg.event.title || '') +
  11130. '</a>' +
  11131. '</td>' +
  11132. '</tr>';
  11133. }
  11134. });
  11135. ;;
  11136. fcViews.list = {
  11137. 'class': ListView,
  11138. buttonTextKey: 'list', // what to lookup in locale files
  11139. defaults: {
  11140. buttonText: 'list', // text to display for English
  11141. listDayFormat: 'LL', // like "January 1, 2016"
  11142. noEventsMessage: 'No events to display'
  11143. }
  11144. };
  11145. fcViews.listDay = {
  11146. type: 'list',
  11147. duration: { days: 1 },
  11148. defaults: {
  11149. listDayFormat: 'dddd' // day-of-week is all we need. full date is probably in header
  11150. }
  11151. };
  11152. fcViews.listWeek = {
  11153. type: 'list',
  11154. duration: { weeks: 1 },
  11155. defaults: {
  11156. listDayFormat: 'dddd', // day-of-week is more important
  11157. listDayAltFormat: 'LL'
  11158. }
  11159. };
  11160. fcViews.listMonth = {
  11161. type: 'list',
  11162. duration: { month: 1 },
  11163. defaults: {
  11164. listDayAltFormat: 'dddd' // day-of-week is nice-to-have
  11165. }
  11166. };
  11167. fcViews.listYear = {
  11168. type: 'list',
  11169. duration: { year: 1 },
  11170. defaults: {
  11171. listDayAltFormat: 'dddd' // day-of-week is nice-to-have
  11172. }
  11173. };
  11174. ;;
  11175. return FC; // export for Node/CommonJS
  11176. });