fullcalendar.js 416 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591
  1. /*!
  2. * FullCalendar v3.4.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.4.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: 9
  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. // WARNING: given element can't have borders
  224. // NOTE: should use clientLeft/clientTop, but very unreliable cross-browser.
  225. function getClientRect(el, origin) {
  226. var offset = el.offset();
  227. var scrollbarWidths = getScrollbarWidths(el);
  228. var left = offset.left + getCssFloat(el, 'border-left-width') + scrollbarWidths.left - (origin ? origin.left : 0);
  229. var top = offset.top + getCssFloat(el, 'border-top-width') + scrollbarWidths.top - (origin ? origin.top : 0);
  230. return {
  231. left: left,
  232. right: left + el[0].clientWidth, // clientWidth includes padding but NOT scrollbars
  233. top: top,
  234. bottom: top + el[0].clientHeight // clientHeight includes padding but NOT scrollbars
  235. };
  236. }
  237. // Queries the area within the margin/border/padding of a jQuery element. Assumed not to have scrollbars.
  238. // Returns a rectangle with absolute coordinates: left, right (exclusive), top, bottom (exclusive).
  239. // Origin is optional.
  240. function getContentRect(el, origin) {
  241. var offset = el.offset(); // just outside of border, margin not included
  242. var left = offset.left + getCssFloat(el, 'border-left-width') + getCssFloat(el, 'padding-left') -
  243. (origin ? origin.left : 0);
  244. var top = offset.top + getCssFloat(el, 'border-top-width') + getCssFloat(el, 'padding-top') -
  245. (origin ? origin.top : 0);
  246. return {
  247. left: left,
  248. right: left + el.width(),
  249. top: top,
  250. bottom: top + el.height()
  251. };
  252. }
  253. // Returns the computed left/right/top/bottom scrollbar widths for the given jQuery element.
  254. // WARNING: given element can't have borders (which will cause offsetWidth/offsetHeight to be larger).
  255. // NOTE: should use clientLeft/clientTop, but very unreliable cross-browser.
  256. function getScrollbarWidths(el) {
  257. var leftRightWidth = el[0].offsetWidth - el[0].clientWidth;
  258. var bottomWidth = el[0].offsetHeight - el[0].clientHeight;
  259. var widths;
  260. leftRightWidth = sanitizeScrollbarWidth(leftRightWidth);
  261. bottomWidth = sanitizeScrollbarWidth(bottomWidth);
  262. widths = { left: 0, right: 0, top: 0, bottom: bottomWidth };
  263. if (getIsLeftRtlScrollbars() && el.css('direction') == 'rtl') { // is the scrollbar on the left side?
  264. widths.left = leftRightWidth;
  265. }
  266. else {
  267. widths.right = leftRightWidth;
  268. }
  269. return widths;
  270. }
  271. // The scrollbar width computations in getScrollbarWidths are sometimes flawed when it comes to
  272. // retina displays, rounding, and IE11. Massage them into a usable value.
  273. function sanitizeScrollbarWidth(width) {
  274. width = Math.max(0, width); // no negatives
  275. width = Math.round(width);
  276. return width;
  277. }
  278. // Logic for determining if, when the element is right-to-left, the scrollbar appears on the left side
  279. var _isLeftRtlScrollbars = null;
  280. function getIsLeftRtlScrollbars() { // responsible for caching the computation
  281. if (_isLeftRtlScrollbars === null) {
  282. _isLeftRtlScrollbars = computeIsLeftRtlScrollbars();
  283. }
  284. return _isLeftRtlScrollbars;
  285. }
  286. function computeIsLeftRtlScrollbars() { // creates an offscreen test element, then removes it
  287. var el = $('<div><div/></div>')
  288. .css({
  289. position: 'absolute',
  290. top: -1000,
  291. left: 0,
  292. border: 0,
  293. padding: 0,
  294. overflow: 'scroll',
  295. direction: 'rtl'
  296. })
  297. .appendTo('body');
  298. var innerEl = el.children();
  299. var res = innerEl.offset().left > el.offset().left; // is the inner div shifted to accommodate a left scrollbar?
  300. el.remove();
  301. return res;
  302. }
  303. // Retrieves a jQuery element's computed CSS value as a floating-point number.
  304. // If the queried value is non-numeric (ex: IE can return "medium" for border width), will just return zero.
  305. function getCssFloat(el, prop) {
  306. return parseFloat(el.css(prop)) || 0;
  307. }
  308. /* Mouse / Touch Utilities
  309. ----------------------------------------------------------------------------------------------------------------------*/
  310. FC.preventDefault = preventDefault;
  311. // Returns a boolean whether this was a left mouse click and no ctrl key (which means right click on Mac)
  312. function isPrimaryMouseButton(ev) {
  313. return ev.which == 1 && !ev.ctrlKey;
  314. }
  315. function getEvX(ev) {
  316. var touches = ev.originalEvent.touches;
  317. // on mobile FF, pageX for touch events is present, but incorrect,
  318. // so, look at touch coordinates first.
  319. if (touches && touches.length) {
  320. return touches[0].pageX;
  321. }
  322. return ev.pageX;
  323. }
  324. function getEvY(ev) {
  325. var touches = ev.originalEvent.touches;
  326. // on mobile FF, pageX for touch events is present, but incorrect,
  327. // so, look at touch coordinates first.
  328. if (touches && touches.length) {
  329. return touches[0].pageY;
  330. }
  331. return ev.pageY;
  332. }
  333. function getEvIsTouch(ev) {
  334. return /^touch/.test(ev.type);
  335. }
  336. function preventSelection(el) {
  337. el.addClass('fc-unselectable')
  338. .on('selectstart', preventDefault);
  339. }
  340. function allowSelection(el) {
  341. el.removeClass('fc-unselectable')
  342. .off('selectstart', preventDefault);
  343. }
  344. // Stops a mouse/touch event from doing it's native browser action
  345. function preventDefault(ev) {
  346. ev.preventDefault();
  347. }
  348. /* General Geometry Utils
  349. ----------------------------------------------------------------------------------------------------------------------*/
  350. FC.intersectRects = intersectRects;
  351. // Returns a new rectangle that is the intersection of the two rectangles. If they don't intersect, returns false
  352. function intersectRects(rect1, rect2) {
  353. var res = {
  354. left: Math.max(rect1.left, rect2.left),
  355. right: Math.min(rect1.right, rect2.right),
  356. top: Math.max(rect1.top, rect2.top),
  357. bottom: Math.min(rect1.bottom, rect2.bottom)
  358. };
  359. if (res.left < res.right && res.top < res.bottom) {
  360. return res;
  361. }
  362. return false;
  363. }
  364. // Returns a new point that will have been moved to reside within the given rectangle
  365. function constrainPoint(point, rect) {
  366. return {
  367. left: Math.min(Math.max(point.left, rect.left), rect.right),
  368. top: Math.min(Math.max(point.top, rect.top), rect.bottom)
  369. };
  370. }
  371. // Returns a point that is the center of the given rectangle
  372. function getRectCenter(rect) {
  373. return {
  374. left: (rect.left + rect.right) / 2,
  375. top: (rect.top + rect.bottom) / 2
  376. };
  377. }
  378. // Subtracts point2's coordinates from point1's coordinates, returning a delta
  379. function diffPoints(point1, point2) {
  380. return {
  381. left: point1.left - point2.left,
  382. top: point1.top - point2.top
  383. };
  384. }
  385. /* Object Ordering by Field
  386. ----------------------------------------------------------------------------------------------------------------------*/
  387. FC.parseFieldSpecs = parseFieldSpecs;
  388. FC.compareByFieldSpecs = compareByFieldSpecs;
  389. FC.compareByFieldSpec = compareByFieldSpec;
  390. FC.flexibleCompare = flexibleCompare;
  391. function parseFieldSpecs(input) {
  392. var specs = [];
  393. var tokens = [];
  394. var i, token;
  395. if (typeof input === 'string') {
  396. tokens = input.split(/\s*,\s*/);
  397. }
  398. else if (typeof input === 'function') {
  399. tokens = [ input ];
  400. }
  401. else if ($.isArray(input)) {
  402. tokens = input;
  403. }
  404. for (i = 0; i < tokens.length; i++) {
  405. token = tokens[i];
  406. if (typeof token === 'string') {
  407. specs.push(
  408. token.charAt(0) == '-' ?
  409. { field: token.substring(1), order: -1 } :
  410. { field: token, order: 1 }
  411. );
  412. }
  413. else if (typeof token === 'function') {
  414. specs.push({ func: token });
  415. }
  416. }
  417. return specs;
  418. }
  419. function compareByFieldSpecs(obj1, obj2, fieldSpecs) {
  420. var i;
  421. var cmp;
  422. for (i = 0; i < fieldSpecs.length; i++) {
  423. cmp = compareByFieldSpec(obj1, obj2, fieldSpecs[i]);
  424. if (cmp) {
  425. return cmp;
  426. }
  427. }
  428. return 0;
  429. }
  430. function compareByFieldSpec(obj1, obj2, fieldSpec) {
  431. if (fieldSpec.func) {
  432. return fieldSpec.func(obj1, obj2);
  433. }
  434. return flexibleCompare(obj1[fieldSpec.field], obj2[fieldSpec.field]) *
  435. (fieldSpec.order || 1);
  436. }
  437. function flexibleCompare(a, b) {
  438. if (!a && !b) {
  439. return 0;
  440. }
  441. if (b == null) {
  442. return -1;
  443. }
  444. if (a == null) {
  445. return 1;
  446. }
  447. if ($.type(a) === 'string' || $.type(b) === 'string') {
  448. return String(a).localeCompare(String(b));
  449. }
  450. return a - b;
  451. }
  452. /* FullCalendar-specific Misc Utilities
  453. ----------------------------------------------------------------------------------------------------------------------*/
  454. // Computes the intersection of the two ranges. Will return fresh date clones in a range.
  455. // Returns undefined if no intersection.
  456. // Expects all dates to be normalized to the same timezone beforehand.
  457. // TODO: move to date section?
  458. function intersectRanges(subjectRange, constraintRange) {
  459. var subjectStart = subjectRange.start;
  460. var subjectEnd = subjectRange.end;
  461. var constraintStart = constraintRange.start;
  462. var constraintEnd = constraintRange.end;
  463. var segStart, segEnd;
  464. var isStart, isEnd;
  465. if (subjectEnd > constraintStart && subjectStart < constraintEnd) { // in bounds at all?
  466. if (subjectStart >= constraintStart) {
  467. segStart = subjectStart.clone();
  468. isStart = true;
  469. }
  470. else {
  471. segStart = constraintStart.clone();
  472. isStart = false;
  473. }
  474. if (subjectEnd <= constraintEnd) {
  475. segEnd = subjectEnd.clone();
  476. isEnd = true;
  477. }
  478. else {
  479. segEnd = constraintEnd.clone();
  480. isEnd = false;
  481. }
  482. return {
  483. start: segStart,
  484. end: segEnd,
  485. isStart: isStart,
  486. isEnd: isEnd
  487. };
  488. }
  489. }
  490. /* Date Utilities
  491. ----------------------------------------------------------------------------------------------------------------------*/
  492. FC.computeGreatestUnit = computeGreatestUnit;
  493. FC.divideRangeByDuration = divideRangeByDuration;
  494. FC.divideDurationByDuration = divideDurationByDuration;
  495. FC.multiplyDuration = multiplyDuration;
  496. FC.durationHasTime = durationHasTime;
  497. var dayIDs = [ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ];
  498. var unitsDesc = [ 'year', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond' ]; // descending
  499. // Diffs the two moments into a Duration where full-days are recorded first, then the remaining time.
  500. // Moments will have their timezones normalized.
  501. function diffDayTime(a, b) {
  502. return moment.duration({
  503. days: a.clone().stripTime().diff(b.clone().stripTime(), 'days'),
  504. ms: a.time() - b.time() // time-of-day from day start. disregards timezone
  505. });
  506. }
  507. // Diffs the two moments via their start-of-day (regardless of timezone). Produces whole-day durations.
  508. function diffDay(a, b) {
  509. return moment.duration({
  510. days: a.clone().stripTime().diff(b.clone().stripTime(), 'days')
  511. });
  512. }
  513. // Diffs two moments, producing a duration, made of a whole-unit-increment of the given unit. Uses rounding.
  514. function diffByUnit(a, b, unit) {
  515. return moment.duration(
  516. Math.round(a.diff(b, unit, true)), // returnFloat=true
  517. unit
  518. );
  519. }
  520. // Computes the unit name of the largest whole-unit period of time.
  521. // For example, 48 hours will be "days" whereas 49 hours will be "hours".
  522. // Accepts start/end, a range object, or an original duration object.
  523. function computeGreatestUnit(start, end) {
  524. var i, unit;
  525. var val;
  526. for (i = 0; i < unitsDesc.length; i++) {
  527. unit = unitsDesc[i];
  528. val = computeRangeAs(unit, start, end);
  529. if (val >= 1 && isInt(val)) {
  530. break;
  531. }
  532. }
  533. return unit; // will be "milliseconds" if nothing else matches
  534. }
  535. // like computeGreatestUnit, but has special abilities to interpret the source input for clues
  536. function computeDurationGreatestUnit(duration, durationInput) {
  537. var unit = computeGreatestUnit(duration);
  538. // prevent days:7 from being interpreted as a week
  539. if (unit === 'week' && typeof durationInput === 'object' && durationInput.days) {
  540. unit = 'day';
  541. }
  542. return unit;
  543. }
  544. // Computes the number of units (like "hours") in the given range.
  545. // Range can be a {start,end} object, separate start/end args, or a Duration.
  546. // Results are based on Moment's .as() and .diff() methods, so results can depend on internal handling
  547. // of month-diffing logic (which tends to vary from version to version).
  548. function computeRangeAs(unit, start, end) {
  549. if (end != null) { // given start, end
  550. return end.diff(start, unit, true);
  551. }
  552. else if (moment.isDuration(start)) { // given duration
  553. return start.as(unit);
  554. }
  555. else { // given { start, end } range object
  556. return start.end.diff(start.start, unit, true);
  557. }
  558. }
  559. // Intelligently divides a range (specified by a start/end params) by a duration
  560. function divideRangeByDuration(start, end, dur) {
  561. var months;
  562. if (durationHasTime(dur)) {
  563. return (end - start) / dur;
  564. }
  565. months = dur.asMonths();
  566. if (Math.abs(months) >= 1 && isInt(months)) {
  567. return end.diff(start, 'months', true) / months;
  568. }
  569. return end.diff(start, 'days', true) / dur.asDays();
  570. }
  571. // Intelligently divides one duration by another
  572. function divideDurationByDuration(dur1, dur2) {
  573. var months1, months2;
  574. if (durationHasTime(dur1) || durationHasTime(dur2)) {
  575. return dur1 / dur2;
  576. }
  577. months1 = dur1.asMonths();
  578. months2 = dur2.asMonths();
  579. if (
  580. Math.abs(months1) >= 1 && isInt(months1) &&
  581. Math.abs(months2) >= 1 && isInt(months2)
  582. ) {
  583. return months1 / months2;
  584. }
  585. return dur1.asDays() / dur2.asDays();
  586. }
  587. // Intelligently multiplies a duration by a number
  588. function multiplyDuration(dur, n) {
  589. var months;
  590. if (durationHasTime(dur)) {
  591. return moment.duration(dur * n);
  592. }
  593. months = dur.asMonths();
  594. if (Math.abs(months) >= 1 && isInt(months)) {
  595. return moment.duration({ months: months * n });
  596. }
  597. return moment.duration({ days: dur.asDays() * n });
  598. }
  599. function cloneRange(range) {
  600. return {
  601. start: range.start.clone(),
  602. end: range.end.clone()
  603. };
  604. }
  605. // Trims the beginning and end of inner range to be completely within outerRange.
  606. // Returns a new range object.
  607. function constrainRange(innerRange, outerRange) {
  608. innerRange = cloneRange(innerRange);
  609. if (outerRange.start) {
  610. // needs to be inclusively before outerRange's end
  611. innerRange.start = constrainDate(innerRange.start, outerRange);
  612. }
  613. if (outerRange.end) {
  614. innerRange.end = minMoment(innerRange.end, outerRange.end);
  615. }
  616. return innerRange;
  617. }
  618. // If the given date is not within the given range, move it inside.
  619. // (If it's past the end, make it one millisecond before the end).
  620. // Always returns a new moment.
  621. function constrainDate(date, range) {
  622. date = date.clone();
  623. if (range.start) {
  624. date = maxMoment(date, range.start);
  625. }
  626. if (range.end && date >= range.end) {
  627. date = range.end.clone().subtract(1);
  628. }
  629. return date;
  630. }
  631. function isDateWithinRange(date, range) {
  632. return (!range.start || date >= range.start) &&
  633. (!range.end || date < range.end);
  634. }
  635. // TODO: deal with repeat code in intersectRanges
  636. // constraintRange can have unspecified start/end, an open-ended range.
  637. function doRangesIntersect(subjectRange, constraintRange) {
  638. return (!constraintRange.start || subjectRange.end >= constraintRange.start) &&
  639. (!constraintRange.end || subjectRange.start < constraintRange.end);
  640. }
  641. function isRangeWithinRange(innerRange, outerRange) {
  642. return (!outerRange.start || innerRange.start >= outerRange.start) &&
  643. (!outerRange.end || innerRange.end <= outerRange.end);
  644. }
  645. function isRangesEqual(range0, range1) {
  646. return ((range0.start && range1.start && range0.start.isSame(range1.start)) || (!range0.start && !range1.start)) &&
  647. ((range0.end && range1.end && range0.end.isSame(range1.end)) || (!range0.end && !range1.end));
  648. }
  649. // Returns the moment that's earlier in time. Always a copy.
  650. function minMoment(mom1, mom2) {
  651. return (mom1.isBefore(mom2) ? mom1 : mom2).clone();
  652. }
  653. // Returns the moment that's later in time. Always a copy.
  654. function maxMoment(mom1, mom2) {
  655. return (mom1.isAfter(mom2) ? mom1 : mom2).clone();
  656. }
  657. // Returns a boolean about whether the given duration has any time parts (hours/minutes/seconds/ms)
  658. function durationHasTime(dur) {
  659. return Boolean(dur.hours() || dur.minutes() || dur.seconds() || dur.milliseconds());
  660. }
  661. function isNativeDate(input) {
  662. return Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date;
  663. }
  664. // Returns a boolean about whether the given input is a time string, like "06:40:00" or "06:00"
  665. function isTimeString(str) {
  666. return /^\d+\:\d+(?:\:\d+\.?(?:\d{3})?)?$/.test(str);
  667. }
  668. /* Logging and Debug
  669. ----------------------------------------------------------------------------------------------------------------------*/
  670. FC.log = function() {
  671. var console = window.console;
  672. if (console && console.log) {
  673. return console.log.apply(console, arguments);
  674. }
  675. };
  676. FC.warn = function() {
  677. var console = window.console;
  678. if (console && console.warn) {
  679. return console.warn.apply(console, arguments);
  680. }
  681. else {
  682. return FC.log.apply(FC, arguments);
  683. }
  684. };
  685. /* General Utilities
  686. ----------------------------------------------------------------------------------------------------------------------*/
  687. var hasOwnPropMethod = {}.hasOwnProperty;
  688. // Merges an array of objects into a single object.
  689. // The second argument allows for an array of property names who's object values will be merged together.
  690. function mergeProps(propObjs, complexProps) {
  691. var dest = {};
  692. var i, name;
  693. var complexObjs;
  694. var j, val;
  695. var props;
  696. if (complexProps) {
  697. for (i = 0; i < complexProps.length; i++) {
  698. name = complexProps[i];
  699. complexObjs = [];
  700. // collect the trailing object values, stopping when a non-object is discovered
  701. for (j = propObjs.length - 1; j >= 0; j--) {
  702. val = propObjs[j][name];
  703. if (typeof val === 'object') {
  704. complexObjs.unshift(val);
  705. }
  706. else if (val !== undefined) {
  707. dest[name] = val; // if there were no objects, this value will be used
  708. break;
  709. }
  710. }
  711. // if the trailing values were objects, use the merged value
  712. if (complexObjs.length) {
  713. dest[name] = mergeProps(complexObjs);
  714. }
  715. }
  716. }
  717. // copy values into the destination, going from last to first
  718. for (i = propObjs.length - 1; i >= 0; i--) {
  719. props = propObjs[i];
  720. for (name in props) {
  721. if (!(name in dest)) { // if already assigned by previous props or complex props, don't reassign
  722. dest[name] = props[name];
  723. }
  724. }
  725. }
  726. return dest;
  727. }
  728. // Create an object that has the given prototype. Just like Object.create
  729. function createObject(proto) {
  730. var f = function() {};
  731. f.prototype = proto;
  732. return new f();
  733. }
  734. FC.createObject = createObject;
  735. function copyOwnProps(src, dest) {
  736. for (var name in src) {
  737. if (hasOwnProp(src, name)) {
  738. dest[name] = src[name];
  739. }
  740. }
  741. }
  742. function hasOwnProp(obj, name) {
  743. return hasOwnPropMethod.call(obj, name);
  744. }
  745. // Is the given value a non-object non-function value?
  746. function isAtomic(val) {
  747. return /undefined|null|boolean|number|string/.test($.type(val));
  748. }
  749. function applyAll(functions, thisObj, args) {
  750. if ($.isFunction(functions)) {
  751. functions = [ functions ];
  752. }
  753. if (functions) {
  754. var i;
  755. var ret;
  756. for (i=0; i<functions.length; i++) {
  757. ret = functions[i].apply(thisObj, args) || ret;
  758. }
  759. return ret;
  760. }
  761. }
  762. function firstDefined() {
  763. for (var i=0; i<arguments.length; i++) {
  764. if (arguments[i] !== undefined) {
  765. return arguments[i];
  766. }
  767. }
  768. }
  769. function htmlEscape(s) {
  770. return (s + '').replace(/&/g, '&amp;')
  771. .replace(/</g, '&lt;')
  772. .replace(/>/g, '&gt;')
  773. .replace(/'/g, '&#039;')
  774. .replace(/"/g, '&quot;')
  775. .replace(/\n/g, '<br />');
  776. }
  777. function stripHtmlEntities(text) {
  778. return text.replace(/&.*?;/g, '');
  779. }
  780. // Given a hash of CSS properties, returns a string of CSS.
  781. // Uses property names as-is (no camel-case conversion). Will not make statements for null/undefined values.
  782. function cssToStr(cssProps) {
  783. var statements = [];
  784. $.each(cssProps, function(name, val) {
  785. if (val != null) {
  786. statements.push(name + ':' + val);
  787. }
  788. });
  789. return statements.join(';');
  790. }
  791. // Given an object hash of HTML attribute names to values,
  792. // generates a string that can be injected between < > in HTML
  793. function attrsToStr(attrs) {
  794. var parts = [];
  795. $.each(attrs, function(name, val) {
  796. if (val != null) {
  797. parts.push(name + '="' + htmlEscape(val) + '"');
  798. }
  799. });
  800. return parts.join(' ');
  801. }
  802. function capitaliseFirstLetter(str) {
  803. return str.charAt(0).toUpperCase() + str.slice(1);
  804. }
  805. function compareNumbers(a, b) { // for .sort()
  806. return a - b;
  807. }
  808. function isInt(n) {
  809. return n % 1 === 0;
  810. }
  811. // Returns a method bound to the given object context.
  812. // Just like one of the jQuery.proxy signatures, but without the undesired behavior of treating the same method with
  813. // different contexts as identical when binding/unbinding events.
  814. function proxy(obj, methodName) {
  815. var method = obj[methodName];
  816. return function() {
  817. return method.apply(obj, arguments);
  818. };
  819. }
  820. // Returns a function, that, as long as it continues to be invoked, will not
  821. // be triggered. The function will be called after it stops being called for
  822. // N milliseconds. If `immediate` is passed, trigger the function on the
  823. // leading edge, instead of the trailing.
  824. // https://github.com/jashkenas/underscore/blob/1.6.0/underscore.js#L714
  825. function debounce(func, wait, immediate) {
  826. var timeout, args, context, timestamp, result;
  827. var later = function() {
  828. var last = +new Date() - timestamp;
  829. if (last < wait) {
  830. timeout = setTimeout(later, wait - last);
  831. }
  832. else {
  833. timeout = null;
  834. if (!immediate) {
  835. result = func.apply(context, args);
  836. context = args = null;
  837. }
  838. }
  839. };
  840. return function() {
  841. context = this;
  842. args = arguments;
  843. timestamp = +new Date();
  844. var callNow = immediate && !timeout;
  845. if (!timeout) {
  846. timeout = setTimeout(later, wait);
  847. }
  848. if (callNow) {
  849. result = func.apply(context, args);
  850. context = args = null;
  851. }
  852. return result;
  853. };
  854. }
  855. ;;
  856. /*
  857. GENERAL NOTE on moments throughout the *entire rest* of the codebase:
  858. All moments are assumed to be ambiguously-zoned unless otherwise noted,
  859. with the NOTABLE EXCEOPTION of start/end dates that live on *Event Objects*.
  860. Ambiguously-TIMED moments are assumed to be ambiguously-zoned by nature.
  861. */
  862. var ambigDateOfMonthRegex = /^\s*\d{4}-\d\d$/;
  863. var ambigTimeOrZoneRegex =
  864. /^\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+)?)?)?)?)?$/;
  865. var newMomentProto = moment.fn; // where we will attach our new methods
  866. var oldMomentProto = $.extend({}, newMomentProto); // copy of original moment methods
  867. // tell momentjs to transfer these properties upon clone
  868. var momentProperties = moment.momentProperties;
  869. momentProperties.push('_fullCalendar');
  870. momentProperties.push('_ambigTime');
  871. momentProperties.push('_ambigZone');
  872. // Creating
  873. // -------------------------------------------------------------------------------------------------
  874. // Creates a new moment, similar to the vanilla moment(...) constructor, but with
  875. // extra features (ambiguous time, enhanced formatting). When given an existing moment,
  876. // it will function as a clone (and retain the zone of the moment). Anything else will
  877. // result in a moment in the local zone.
  878. FC.moment = function() {
  879. return makeMoment(arguments);
  880. };
  881. // Sames as FC.moment, but forces the resulting moment to be in the UTC timezone.
  882. FC.moment.utc = function() {
  883. var mom = makeMoment(arguments, true);
  884. // Force it into UTC because makeMoment doesn't guarantee it
  885. // (if given a pre-existing moment for example)
  886. if (mom.hasTime()) { // don't give ambiguously-timed moments a UTC zone
  887. mom.utc();
  888. }
  889. return mom;
  890. };
  891. // Same as FC.moment, but when given an ISO8601 string, the timezone offset is preserved.
  892. // ISO8601 strings with no timezone offset will become ambiguously zoned.
  893. FC.moment.parseZone = function() {
  894. return makeMoment(arguments, true, true);
  895. };
  896. // Builds an enhanced moment from args. When given an existing moment, it clones. When given a
  897. // native Date, or called with no arguments (the current time), the resulting moment will be local.
  898. // Anything else needs to be "parsed" (a string or an array), and will be affected by:
  899. // parseAsUTC - if there is no zone information, should we parse the input in UTC?
  900. // parseZone - if there is zone information, should we force the zone of the moment?
  901. function makeMoment(args, parseAsUTC, parseZone) {
  902. var input = args[0];
  903. var isSingleString = args.length == 1 && typeof input === 'string';
  904. var isAmbigTime;
  905. var isAmbigZone;
  906. var ambigMatch;
  907. var mom;
  908. if (moment.isMoment(input) || isNativeDate(input) || input === undefined) {
  909. mom = moment.apply(null, args);
  910. }
  911. else { // "parsing" is required
  912. isAmbigTime = false;
  913. isAmbigZone = false;
  914. if (isSingleString) {
  915. if (ambigDateOfMonthRegex.test(input)) {
  916. // accept strings like '2014-05', but convert to the first of the month
  917. input += '-01';
  918. args = [ input ]; // for when we pass it on to moment's constructor
  919. isAmbigTime = true;
  920. isAmbigZone = true;
  921. }
  922. else if ((ambigMatch = ambigTimeOrZoneRegex.exec(input))) {
  923. isAmbigTime = !ambigMatch[5]; // no time part?
  924. isAmbigZone = true;
  925. }
  926. }
  927. else if ($.isArray(input)) {
  928. // arrays have no timezone information, so assume ambiguous zone
  929. isAmbigZone = true;
  930. }
  931. // otherwise, probably a string with a format
  932. if (parseAsUTC || isAmbigTime) {
  933. mom = moment.utc.apply(moment, args);
  934. }
  935. else {
  936. mom = moment.apply(null, args);
  937. }
  938. if (isAmbigTime) {
  939. mom._ambigTime = true;
  940. mom._ambigZone = true; // ambiguous time always means ambiguous zone
  941. }
  942. else if (parseZone) { // let's record the inputted zone somehow
  943. if (isAmbigZone) {
  944. mom._ambigZone = true;
  945. }
  946. else if (isSingleString) {
  947. mom.utcOffset(input); // if not a valid zone, will assign UTC
  948. }
  949. }
  950. }
  951. mom._fullCalendar = true; // flag for extended functionality
  952. return mom;
  953. }
  954. // Week Number
  955. // -------------------------------------------------------------------------------------------------
  956. // Returns the week number, considering the locale's custom week number calcuation
  957. // `weeks` is an alias for `week`
  958. newMomentProto.week = newMomentProto.weeks = function(input) {
  959. var weekCalc = this._locale._fullCalendar_weekCalc;
  960. if (input == null && typeof weekCalc === 'function') { // custom function only works for getter
  961. return weekCalc(this);
  962. }
  963. else if (weekCalc === 'ISO') {
  964. return oldMomentProto.isoWeek.apply(this, arguments); // ISO getter/setter
  965. }
  966. return oldMomentProto.week.apply(this, arguments); // local getter/setter
  967. };
  968. // Time-of-day
  969. // -------------------------------------------------------------------------------------------------
  970. // GETTER
  971. // Returns a Duration with the hours/minutes/seconds/ms values of the moment.
  972. // If the moment has an ambiguous time, a duration of 00:00 will be returned.
  973. //
  974. // SETTER
  975. // You can supply a Duration, a Moment, or a Duration-like argument.
  976. // When setting the time, and the moment has an ambiguous time, it then becomes unambiguous.
  977. newMomentProto.time = function(time) {
  978. // Fallback to the original method (if there is one) if this moment wasn't created via FullCalendar.
  979. // `time` is a generic enough method name where this precaution is necessary to avoid collisions w/ other plugins.
  980. if (!this._fullCalendar) {
  981. return oldMomentProto.time.apply(this, arguments);
  982. }
  983. if (time == null) { // getter
  984. return moment.duration({
  985. hours: this.hours(),
  986. minutes: this.minutes(),
  987. seconds: this.seconds(),
  988. milliseconds: this.milliseconds()
  989. });
  990. }
  991. else { // setter
  992. this._ambigTime = false; // mark that the moment now has a time
  993. if (!moment.isDuration(time) && !moment.isMoment(time)) {
  994. time = moment.duration(time);
  995. }
  996. // The day value should cause overflow (so 24 hours becomes 00:00:00 of next day).
  997. // Only for Duration times, not Moment times.
  998. var dayHours = 0;
  999. if (moment.isDuration(time)) {
  1000. dayHours = Math.floor(time.asDays()) * 24;
  1001. }
  1002. // We need to set the individual fields.
  1003. // Can't use startOf('day') then add duration. In case of DST at start of day.
  1004. return this.hours(dayHours + time.hours())
  1005. .minutes(time.minutes())
  1006. .seconds(time.seconds())
  1007. .milliseconds(time.milliseconds());
  1008. }
  1009. };
  1010. // Converts the moment to UTC, stripping out its time-of-day and timezone offset,
  1011. // but preserving its YMD. A moment with a stripped time will display no time
  1012. // nor timezone offset when .format() is called.
  1013. newMomentProto.stripTime = function() {
  1014. if (!this._ambigTime) {
  1015. this.utc(true); // keepLocalTime=true (for keeping *date* value)
  1016. // set time to zero
  1017. this.set({
  1018. hours: 0,
  1019. minutes: 0,
  1020. seconds: 0,
  1021. ms: 0
  1022. });
  1023. // Mark the time as ambiguous. This needs to happen after the .utc() call, which might call .utcOffset(),
  1024. // which clears all ambig flags.
  1025. this._ambigTime = true;
  1026. this._ambigZone = true; // if ambiguous time, also ambiguous timezone offset
  1027. }
  1028. return this; // for chaining
  1029. };
  1030. // Returns if the moment has a non-ambiguous time (boolean)
  1031. newMomentProto.hasTime = function() {
  1032. return !this._ambigTime;
  1033. };
  1034. // Timezone
  1035. // -------------------------------------------------------------------------------------------------
  1036. // Converts the moment to UTC, stripping out its timezone offset, but preserving its
  1037. // YMD and time-of-day. A moment with a stripped timezone offset will display no
  1038. // timezone offset when .format() is called.
  1039. newMomentProto.stripZone = function() {
  1040. var wasAmbigTime;
  1041. if (!this._ambigZone) {
  1042. wasAmbigTime = this._ambigTime;
  1043. this.utc(true); // keepLocalTime=true (for keeping date and time values)
  1044. // the above call to .utc()/.utcOffset() unfortunately might clear the ambig flags, so restore
  1045. this._ambigTime = wasAmbigTime || false;
  1046. // Mark the zone as ambiguous. This needs to happen after the .utc() call, which might call .utcOffset(),
  1047. // which clears the ambig flags.
  1048. this._ambigZone = true;
  1049. }
  1050. return this; // for chaining
  1051. };
  1052. // Returns of the moment has a non-ambiguous timezone offset (boolean)
  1053. newMomentProto.hasZone = function() {
  1054. return !this._ambigZone;
  1055. };
  1056. // implicitly marks a zone
  1057. newMomentProto.local = function(keepLocalTime) {
  1058. // for when converting from ambiguously-zoned to local,
  1059. // keep the time values when converting from UTC -> local
  1060. oldMomentProto.local.call(this, this._ambigZone || keepLocalTime);
  1061. // ensure non-ambiguous
  1062. // this probably already happened via local() -> utcOffset(), but don't rely on Moment's internals
  1063. this._ambigTime = false;
  1064. this._ambigZone = false;
  1065. return this; // for chaining
  1066. };
  1067. // implicitly marks a zone
  1068. newMomentProto.utc = function(keepLocalTime) {
  1069. oldMomentProto.utc.call(this, keepLocalTime);
  1070. // ensure non-ambiguous
  1071. // this probably already happened via utc() -> utcOffset(), but don't rely on Moment's internals
  1072. this._ambigTime = false;
  1073. this._ambigZone = false;
  1074. return this;
  1075. };
  1076. // implicitly marks a zone (will probably get called upon .utc() and .local())
  1077. newMomentProto.utcOffset = function(tzo) {
  1078. if (tzo != null) { // setter
  1079. // these assignments needs to happen before the original zone method is called.
  1080. // I forget why, something to do with a browser crash.
  1081. this._ambigTime = false;
  1082. this._ambigZone = false;
  1083. }
  1084. return oldMomentProto.utcOffset.apply(this, arguments);
  1085. };
  1086. // Formatting
  1087. // -------------------------------------------------------------------------------------------------
  1088. newMomentProto.format = function() {
  1089. if (this._fullCalendar && arguments[0]) { // an enhanced moment? and a format string provided?
  1090. return formatDate(this, arguments[0]); // our extended formatting
  1091. }
  1092. if (this._ambigTime) {
  1093. return oldMomentFormat(englishMoment(this), 'YYYY-MM-DD');
  1094. }
  1095. if (this._ambigZone) {
  1096. return oldMomentFormat(englishMoment(this), 'YYYY-MM-DD[T]HH:mm:ss');
  1097. }
  1098. if (this._fullCalendar) { // enhanced non-ambig moment?
  1099. // moment.format() doesn't ensure english, but we want to.
  1100. return oldMomentFormat(englishMoment(this));
  1101. }
  1102. return oldMomentProto.format.apply(this, arguments);
  1103. };
  1104. newMomentProto.toISOString = function() {
  1105. if (this._ambigTime) {
  1106. return oldMomentFormat(englishMoment(this), 'YYYY-MM-DD');
  1107. }
  1108. if (this._ambigZone) {
  1109. return oldMomentFormat(englishMoment(this), 'YYYY-MM-DD[T]HH:mm:ss');
  1110. }
  1111. if (this._fullCalendar) { // enhanced non-ambig moment?
  1112. // depending on browser, moment might not output english. ensure english.
  1113. // https://github.com/moment/moment/blob/2.18.1/src/lib/moment/format.js#L22
  1114. return oldMomentProto.toISOString.apply(englishMoment(this), arguments);
  1115. }
  1116. return oldMomentProto.toISOString.apply(this, arguments);
  1117. };
  1118. function englishMoment(mom) {
  1119. if (mom.locale() !== 'en') {
  1120. return mom.clone().locale('en');
  1121. }
  1122. return mom;
  1123. }
  1124. ;;
  1125. (function() {
  1126. // exports
  1127. FC.formatDate = formatDate;
  1128. FC.formatRange = formatRange;
  1129. FC.oldMomentFormat = oldMomentFormat;
  1130. FC.queryMostGranularFormatUnit = queryMostGranularFormatUnit;
  1131. // Config
  1132. // ---------------------------------------------------------------------------------------------------------------------
  1133. /*
  1134. Inserted between chunks in the fake ("intermediate") formatting string.
  1135. Important that it passes as whitespace (\s) because moment often identifies non-standalone months
  1136. via a regexp with an \s.
  1137. */
  1138. var PART_SEPARATOR = '\u000b'; // vertical tab
  1139. /*
  1140. Inserted as the first character of a literal-text chunk to indicate that the literal text is not actually literal text,
  1141. but rather, a "special" token that has custom rendering (see specialTokens map).
  1142. */
  1143. var SPECIAL_TOKEN_MARKER = '\u001f'; // information separator 1
  1144. /*
  1145. Inserted at the beginning and end of a span of text that must have non-zero numeric characters.
  1146. Handling of these markers is done in a post-processing step at the very end of text rendering.
  1147. */
  1148. var MAYBE_MARKER = '\u001e'; // information separator 2
  1149. var MAYBE_REGEXP = new RegExp(MAYBE_MARKER + '([^' + MAYBE_MARKER + ']*)' + MAYBE_MARKER, 'g'); // must be global
  1150. /*
  1151. Addition formatting tokens we want recognized
  1152. */
  1153. var specialTokens = {
  1154. t: function(date) { // "a" or "p"
  1155. return oldMomentFormat(date, 'a').charAt(0);
  1156. },
  1157. T: function(date) { // "A" or "P"
  1158. return oldMomentFormat(date, 'A').charAt(0);
  1159. }
  1160. };
  1161. /*
  1162. The first characters of formatting tokens for units that are 1 day or larger.
  1163. `value` is for ranking relative size (lower means bigger).
  1164. `unit` is a normalized unit, used for comparing moments.
  1165. */
  1166. var largeTokenMap = {
  1167. Y: { value: 1, unit: 'year' },
  1168. M: { value: 2, unit: 'month' },
  1169. W: { value: 3, unit: 'week' }, // ISO week
  1170. w: { value: 3, unit: 'week' }, // local week
  1171. D: { value: 4, unit: 'day' }, // day of month
  1172. d: { value: 4, unit: 'day' } // day of week
  1173. };
  1174. // Single Date Formatting
  1175. // ---------------------------------------------------------------------------------------------------------------------
  1176. /*
  1177. Formats `date` with a Moment formatting string, but allow our non-zero areas and special token
  1178. */
  1179. function formatDate(date, formatStr) {
  1180. return renderFakeFormatString(
  1181. getParsedFormatString(formatStr).fakeFormatString,
  1182. date
  1183. );
  1184. }
  1185. /*
  1186. Call this if you want Moment's original format method to be used
  1187. */
  1188. function oldMomentFormat(mom, formatStr) {
  1189. return oldMomentProto.format.call(mom, formatStr); // oldMomentProto defined in moment-ext.js
  1190. }
  1191. // Date Range Formatting
  1192. // -------------------------------------------------------------------------------------------------
  1193. // TODO: make it work with timezone offset
  1194. /*
  1195. Using a formatting string meant for a single date, generate a range string, like
  1196. "Sep 2 - 9 2013", that intelligently inserts a separator where the dates differ.
  1197. If the dates are the same as far as the format string is concerned, just return a single
  1198. rendering of one date, without any separator.
  1199. */
  1200. function formatRange(date1, date2, formatStr, separator, isRTL) {
  1201. var localeData;
  1202. date1 = FC.moment.parseZone(date1);
  1203. date2 = FC.moment.parseZone(date2);
  1204. localeData = date1.localeData();
  1205. // Expand localized format strings, like "LL" -> "MMMM D YYYY".
  1206. // BTW, this is not important for `formatDate` because it is impossible to put custom tokens
  1207. // or non-zero areas in Moment's localized format strings.
  1208. formatStr = localeData.longDateFormat(formatStr) || formatStr;
  1209. return renderParsedFormat(
  1210. getParsedFormatString(formatStr),
  1211. date1,
  1212. date2,
  1213. separator || ' - ',
  1214. isRTL
  1215. );
  1216. }
  1217. /*
  1218. Renders a range with an already-parsed format string.
  1219. */
  1220. function renderParsedFormat(parsedFormat, date1, date2, separator, isRTL) {
  1221. var sameUnits = parsedFormat.sameUnits;
  1222. var unzonedDate1 = date1.clone().stripZone(); // for same-unit comparisons
  1223. var unzonedDate2 = date2.clone().stripZone(); // "
  1224. var renderedParts1 = renderFakeFormatStringParts(parsedFormat.fakeFormatString, date1);
  1225. var renderedParts2 = renderFakeFormatStringParts(parsedFormat.fakeFormatString, date2);
  1226. var leftI;
  1227. var leftStr = '';
  1228. var rightI;
  1229. var rightStr = '';
  1230. var middleI;
  1231. var middleStr1 = '';
  1232. var middleStr2 = '';
  1233. var middleStr = '';
  1234. // Start at the leftmost side of the formatting string and continue until you hit a token
  1235. // that is not the same between dates.
  1236. for (
  1237. leftI = 0;
  1238. leftI < sameUnits.length && (!sameUnits[leftI] || unzonedDate1.isSame(unzonedDate2, sameUnits[leftI]));
  1239. leftI++
  1240. ) {
  1241. leftStr += renderedParts1[leftI];
  1242. }
  1243. // Similarly, start at the rightmost side of the formatting string and move left
  1244. for (
  1245. rightI = sameUnits.length - 1;
  1246. rightI > leftI && (!sameUnits[rightI] || unzonedDate1.isSame(unzonedDate2, sameUnits[rightI]));
  1247. rightI--
  1248. ) {
  1249. // If current chunk is on the boundary of unique date-content, and is a special-case
  1250. // date-formatting postfix character, then don't consume it. Consider it unique date-content.
  1251. // TODO: make configurable
  1252. if (rightI - 1 === leftI && renderedParts1[rightI] === '.') {
  1253. break;
  1254. }
  1255. rightStr = renderedParts1[rightI] + rightStr;
  1256. }
  1257. // The area in the middle is different for both of the dates.
  1258. // Collect them distinctly so we can jam them together later.
  1259. for (middleI = leftI; middleI <= rightI; middleI++) {
  1260. middleStr1 += renderedParts1[middleI];
  1261. middleStr2 += renderedParts2[middleI];
  1262. }
  1263. if (middleStr1 || middleStr2) {
  1264. if (isRTL) {
  1265. middleStr = middleStr2 + separator + middleStr1;
  1266. }
  1267. else {
  1268. middleStr = middleStr1 + separator + middleStr2;
  1269. }
  1270. }
  1271. return processMaybeMarkers(
  1272. leftStr + middleStr + rightStr
  1273. );
  1274. }
  1275. // Format String Parsing
  1276. // ---------------------------------------------------------------------------------------------------------------------
  1277. var parsedFormatStrCache = {};
  1278. /*
  1279. Returns a parsed format string, leveraging a cache.
  1280. */
  1281. function getParsedFormatString(formatStr) {
  1282. return parsedFormatStrCache[formatStr] ||
  1283. (parsedFormatStrCache[formatStr] = parseFormatString(formatStr));
  1284. }
  1285. /*
  1286. Parses a format string into the following:
  1287. - fakeFormatString: a momentJS formatting string, littered with special control characters that get post-processed.
  1288. - sameUnits: for every part in fakeFormatString, if the part is a token, the value will be a unit string (like "day"),
  1289. that indicates how similar a range's start & end must be in order to share the same formatted text.
  1290. If not a token, then the value is null.
  1291. Always a flat array (not nested liked "chunks").
  1292. */
  1293. function parseFormatString(formatStr) {
  1294. var chunks = chunkFormatString(formatStr);
  1295. return {
  1296. fakeFormatString: buildFakeFormatString(chunks),
  1297. sameUnits: buildSameUnits(chunks)
  1298. };
  1299. }
  1300. /*
  1301. Break the formatting string into an array of chunks.
  1302. A 'maybe' chunk will have nested chunks.
  1303. */
  1304. function chunkFormatString(formatStr) {
  1305. var chunks = [];
  1306. var match;
  1307. // TODO: more descrimination
  1308. // \4 is a backreference to the first character of a multi-character set.
  1309. var chunker = /\[([^\]]*)\]|\(([^\)]*)\)|(LTS|LT|(\w)\4*o?)|([^\w\[\(]+)/g;
  1310. while ((match = chunker.exec(formatStr))) {
  1311. if (match[1]) { // a literal string inside [ ... ]
  1312. chunks.push.apply(chunks, // append
  1313. splitStringLiteral(match[1])
  1314. );
  1315. }
  1316. else if (match[2]) { // non-zero formatting inside ( ... )
  1317. chunks.push({ maybe: chunkFormatString(match[2]) });
  1318. }
  1319. else if (match[3]) { // a formatting token
  1320. chunks.push({ token: match[3] });
  1321. }
  1322. else if (match[5]) { // an unenclosed literal string
  1323. chunks.push.apply(chunks, // append
  1324. splitStringLiteral(match[5])
  1325. );
  1326. }
  1327. }
  1328. return chunks;
  1329. }
  1330. /*
  1331. Potentially splits a literal-text string into multiple parts. For special cases.
  1332. */
  1333. function splitStringLiteral(s) {
  1334. if (s === '. ') {
  1335. return [ '.', ' ' ]; // for locales with periods bound to the end of each year/month/date
  1336. }
  1337. else {
  1338. return [ s ];
  1339. }
  1340. }
  1341. /*
  1342. Given chunks parsed from a real format string, generate a fake (aka "intermediate") format string with special control
  1343. characters that will eventually be given to moment for formatting, and then post-processed.
  1344. */
  1345. function buildFakeFormatString(chunks) {
  1346. var parts = [];
  1347. var i, chunk;
  1348. for (i = 0; i < chunks.length; i++) {
  1349. chunk = chunks[i];
  1350. if (typeof chunk === 'string') {
  1351. parts.push('[' + chunk + ']');
  1352. }
  1353. else if (chunk.token) {
  1354. if (chunk.token in specialTokens) {
  1355. parts.push(
  1356. SPECIAL_TOKEN_MARKER + // useful during post-processing
  1357. '[' + chunk.token + ']' // preserve as literal text
  1358. );
  1359. }
  1360. else {
  1361. parts.push(chunk.token); // unprotected text implies a format string
  1362. }
  1363. }
  1364. else if (chunk.maybe) {
  1365. parts.push(
  1366. MAYBE_MARKER + // useful during post-processing
  1367. buildFakeFormatString(chunk.maybe) +
  1368. MAYBE_MARKER
  1369. );
  1370. }
  1371. }
  1372. return parts.join(PART_SEPARATOR);
  1373. }
  1374. /*
  1375. Given parsed chunks from a real formatting string, generates an array of unit strings (like "day") that indicate
  1376. in which regard two dates must be similar in order to share range formatting text.
  1377. The `chunks` can be nested (because of "maybe" chunks), however, the returned array will be flat.
  1378. */
  1379. function buildSameUnits(chunks) {
  1380. var units = [];
  1381. var i, chunk;
  1382. var tokenInfo;
  1383. for (i = 0; i < chunks.length; i++) {
  1384. chunk = chunks[i];
  1385. if (chunk.token) {
  1386. tokenInfo = largeTokenMap[chunk.token.charAt(0)];
  1387. units.push(tokenInfo ? tokenInfo.unit : 'second'); // default to a very strict same-second
  1388. }
  1389. else if (chunk.maybe) {
  1390. units.push.apply(units, // append
  1391. buildSameUnits(chunk.maybe)
  1392. );
  1393. }
  1394. else {
  1395. units.push(null);
  1396. }
  1397. }
  1398. return units;
  1399. }
  1400. // Rendering to text
  1401. // ---------------------------------------------------------------------------------------------------------------------
  1402. /*
  1403. Formats a date with a fake format string, post-processes the control characters, then returns.
  1404. */
  1405. function renderFakeFormatString(fakeFormatString, date) {
  1406. return processMaybeMarkers(
  1407. renderFakeFormatStringParts(fakeFormatString, date).join('')
  1408. );
  1409. }
  1410. /*
  1411. Formats a date into parts that will have been post-processed, EXCEPT for the "maybe" markers.
  1412. */
  1413. function renderFakeFormatStringParts(fakeFormatString, date) {
  1414. var parts = [];
  1415. var fakeRender = oldMomentFormat(date, fakeFormatString);
  1416. var fakeParts = fakeRender.split(PART_SEPARATOR);
  1417. var i, fakePart;
  1418. for (i = 0; i < fakeParts.length; i++) {
  1419. fakePart = fakeParts[i];
  1420. if (fakePart.charAt(0) === SPECIAL_TOKEN_MARKER) {
  1421. parts.push(
  1422. // the literal string IS the token's name.
  1423. // call special token's registered function.
  1424. specialTokens[fakePart.substring(1)](date)
  1425. );
  1426. }
  1427. else {
  1428. parts.push(fakePart);
  1429. }
  1430. }
  1431. return parts;
  1432. }
  1433. /*
  1434. Accepts an almost-finally-formatted string and processes the "maybe" control characters, returning a new string.
  1435. */
  1436. function processMaybeMarkers(s) {
  1437. return s.replace(MAYBE_REGEXP, function(m0, m1) { // regex assumed to have 'g' flag
  1438. if (m1.match(/[1-9]/)) { // any non-zero numeric characters?
  1439. return m1;
  1440. }
  1441. else {
  1442. return '';
  1443. }
  1444. });
  1445. }
  1446. // Misc Utils
  1447. // -------------------------------------------------------------------------------------------------
  1448. /*
  1449. Returns a unit string, either 'year', 'month', 'day', or null for the most granular formatting token in the string.
  1450. */
  1451. function queryMostGranularFormatUnit(formatStr) {
  1452. var chunks = chunkFormatString(formatStr);
  1453. var i, chunk;
  1454. var candidate;
  1455. var best;
  1456. for (i = 0; i < chunks.length; i++) {
  1457. chunk = chunks[i];
  1458. if (chunk.token) {
  1459. candidate = largeTokenMap[chunk.token.charAt(0)];
  1460. if (candidate) {
  1461. if (!best || candidate.value > best.value) {
  1462. best = candidate;
  1463. }
  1464. }
  1465. }
  1466. }
  1467. if (best) {
  1468. return best.unit;
  1469. }
  1470. return null;
  1471. };
  1472. })();
  1473. // quick local references
  1474. var formatDate = FC.formatDate;
  1475. var formatRange = FC.formatRange;
  1476. var oldMomentFormat = FC.oldMomentFormat;
  1477. ;;
  1478. FC.Class = Class; // export
  1479. // Class that all other classes will inherit from
  1480. function Class() { }
  1481. // Called on a class to create a subclass.
  1482. // Last argument contains instance methods. Any argument before the last are considered mixins.
  1483. Class.extend = function() {
  1484. var len = arguments.length;
  1485. var i;
  1486. var members;
  1487. for (i = 0; i < len; i++) {
  1488. members = arguments[i];
  1489. if (i < len - 1) { // not the last argument?
  1490. mixIntoClass(this, members);
  1491. }
  1492. }
  1493. return extendClass(this, members || {}); // members will be undefined if no arguments
  1494. };
  1495. // Adds new member variables/methods to the class's prototype.
  1496. // Can be called with another class, or a plain object hash containing new members.
  1497. Class.mixin = function(members) {
  1498. mixIntoClass(this, members);
  1499. };
  1500. function extendClass(superClass, members) {
  1501. var subClass;
  1502. // ensure a constructor for the subclass, forwarding all arguments to the super-constructor if it doesn't exist
  1503. if (hasOwnProp(members, 'constructor')) {
  1504. subClass = members.constructor;
  1505. }
  1506. if (typeof subClass !== 'function') {
  1507. subClass = members.constructor = function() {
  1508. superClass.apply(this, arguments);
  1509. };
  1510. }
  1511. // build the base prototype for the subclass, which is an new object chained to the superclass's prototype
  1512. subClass.prototype = createObject(superClass.prototype);
  1513. // copy each member variable/method onto the the subclass's prototype
  1514. copyOwnProps(members, subClass.prototype);
  1515. // copy over all class variables/methods to the subclass, such as `extend` and `mixin`
  1516. copyOwnProps(superClass, subClass);
  1517. return subClass;
  1518. }
  1519. function mixIntoClass(theClass, members) {
  1520. copyOwnProps(members, theClass.prototype);
  1521. }
  1522. ;;
  1523. var Model = Class.extend(EmitterMixin, ListenerMixin, {
  1524. _props: null,
  1525. _watchers: null,
  1526. _globalWatchArgs: null,
  1527. constructor: function() {
  1528. this._watchers = {};
  1529. this._props = {};
  1530. this.applyGlobalWatchers();
  1531. },
  1532. applyGlobalWatchers: function() {
  1533. var argSets = this._globalWatchArgs || [];
  1534. var i;
  1535. for (i = 0; i < argSets.length; i++) {
  1536. this.watch.apply(this, argSets[i]);
  1537. }
  1538. },
  1539. has: function(name) {
  1540. return name in this._props;
  1541. },
  1542. get: function(name) {
  1543. if (name === undefined) {
  1544. return this._props;
  1545. }
  1546. return this._props[name];
  1547. },
  1548. set: function(name, val) {
  1549. var newProps;
  1550. if (typeof name === 'string') {
  1551. newProps = {};
  1552. newProps[name] = val === undefined ? null : val;
  1553. }
  1554. else {
  1555. newProps = name;
  1556. }
  1557. this.setProps(newProps);
  1558. },
  1559. reset: function(newProps) {
  1560. var oldProps = this._props;
  1561. var changeset = {}; // will have undefined's to signal unsets
  1562. var name;
  1563. for (name in oldProps) {
  1564. changeset[name] = undefined;
  1565. }
  1566. for (name in newProps) {
  1567. changeset[name] = newProps[name];
  1568. }
  1569. this.setProps(changeset);
  1570. },
  1571. unset: function(name) { // accepts a string or array of strings
  1572. var newProps = {};
  1573. var names;
  1574. var i;
  1575. if (typeof name === 'string') {
  1576. names = [ name ];
  1577. }
  1578. else {
  1579. names = name;
  1580. }
  1581. for (i = 0; i < names.length; i++) {
  1582. newProps[names[i]] = undefined;
  1583. }
  1584. this.setProps(newProps);
  1585. },
  1586. setProps: function(newProps) {
  1587. var changedProps = {};
  1588. var changedCnt = 0;
  1589. var name, val;
  1590. for (name in newProps) {
  1591. val = newProps[name];
  1592. // a change in value?
  1593. // if an object, don't check equality, because might have been mutated internally.
  1594. // TODO: eventually enforce immutability.
  1595. if (
  1596. typeof val === 'object' ||
  1597. val !== this._props[name]
  1598. ) {
  1599. changedProps[name] = val;
  1600. changedCnt++;
  1601. }
  1602. }
  1603. if (changedCnt) {
  1604. this.trigger('before:batchChange', changedProps);
  1605. for (name in changedProps) {
  1606. val = changedProps[name];
  1607. this.trigger('before:change', name, val);
  1608. this.trigger('before:change:' + name, val);
  1609. }
  1610. for (name in changedProps) {
  1611. val = changedProps[name];
  1612. if (val === undefined) {
  1613. delete this._props[name];
  1614. }
  1615. else {
  1616. this._props[name] = val;
  1617. }
  1618. this.trigger('change:' + name, val);
  1619. this.trigger('change', name, val);
  1620. }
  1621. this.trigger('batchChange', changedProps);
  1622. }
  1623. },
  1624. watch: function(name, depList, startFunc, stopFunc) {
  1625. var _this = this;
  1626. this.unwatch(name);
  1627. this._watchers[name] = this._watchDeps(depList, function(deps) {
  1628. var res = startFunc.call(_this, deps);
  1629. if (res && res.then) {
  1630. _this.unset(name); // put in an unset state while resolving
  1631. res.then(function(val) {
  1632. _this.set(name, val);
  1633. });
  1634. }
  1635. else {
  1636. _this.set(name, res);
  1637. }
  1638. }, function() {
  1639. _this.unset(name);
  1640. if (stopFunc) {
  1641. stopFunc.call(_this);
  1642. }
  1643. });
  1644. },
  1645. unwatch: function(name) {
  1646. var watcher = this._watchers[name];
  1647. if (watcher) {
  1648. delete this._watchers[name];
  1649. watcher.teardown();
  1650. }
  1651. },
  1652. _watchDeps: function(depList, startFunc, stopFunc) {
  1653. var _this = this;
  1654. var queuedChangeCnt = 0;
  1655. var depCnt = depList.length;
  1656. var satisfyCnt = 0;
  1657. var values = {}; // what's passed as the `deps` arguments
  1658. var bindTuples = []; // array of [ eventName, handlerFunc ] arrays
  1659. var isCallingStop = false;
  1660. function onBeforeDepChange(depName, val, isOptional) {
  1661. queuedChangeCnt++;
  1662. if (queuedChangeCnt === 1) { // first change to cause a "stop" ?
  1663. if (satisfyCnt === depCnt) { // all deps previously satisfied?
  1664. isCallingStop = true;
  1665. stopFunc();
  1666. isCallingStop = false;
  1667. }
  1668. }
  1669. }
  1670. function onDepChange(depName, val, isOptional) {
  1671. if (val === undefined) { // unsetting a value?
  1672. // required dependency that was previously set?
  1673. if (!isOptional && values[depName] !== undefined) {
  1674. satisfyCnt--;
  1675. }
  1676. delete values[depName];
  1677. }
  1678. else { // setting a value?
  1679. // required dependency that was previously unset?
  1680. if (!isOptional && values[depName] === undefined) {
  1681. satisfyCnt++;
  1682. }
  1683. values[depName] = val;
  1684. }
  1685. queuedChangeCnt--;
  1686. if (!queuedChangeCnt) { // last change to cause a "start"?
  1687. // now finally satisfied or satisfied all along?
  1688. if (satisfyCnt === depCnt) {
  1689. // if the stopFunc initiated another value change, ignore it.
  1690. // it will be processed by another change event anyway.
  1691. if (!isCallingStop) {
  1692. startFunc(values);
  1693. }
  1694. }
  1695. }
  1696. }
  1697. // intercept for .on() that remembers handlers
  1698. function bind(eventName, handler) {
  1699. _this.on(eventName, handler);
  1700. bindTuples.push([ eventName, handler ]);
  1701. }
  1702. // listen to dependency changes
  1703. depList.forEach(function(depName) {
  1704. var isOptional = false;
  1705. if (depName.charAt(0) === '?') { // TODO: more DRY
  1706. depName = depName.substring(1);
  1707. isOptional = true;
  1708. }
  1709. bind('before:change:' + depName, function(val) {
  1710. onBeforeDepChange(depName, val, isOptional);
  1711. });
  1712. bind('change:' + depName, function(val) {
  1713. onDepChange(depName, val, isOptional);
  1714. });
  1715. });
  1716. // process current dependency values
  1717. depList.forEach(function(depName) {
  1718. var isOptional = false;
  1719. if (depName.charAt(0) === '?') { // TODO: more DRY
  1720. depName = depName.substring(1);
  1721. isOptional = true;
  1722. }
  1723. if (_this.has(depName)) {
  1724. values[depName] = _this.get(depName);
  1725. satisfyCnt++;
  1726. }
  1727. else if (isOptional) {
  1728. satisfyCnt++;
  1729. }
  1730. });
  1731. // initially satisfied
  1732. if (satisfyCnt === depCnt) {
  1733. startFunc(values);
  1734. }
  1735. return {
  1736. teardown: function() {
  1737. // remove all handlers
  1738. for (var i = 0; i < bindTuples.length; i++) {
  1739. _this.off(bindTuples[i][0], bindTuples[i][1]);
  1740. }
  1741. bindTuples = null;
  1742. // was satisfied, so call stopFunc
  1743. if (satisfyCnt === depCnt) {
  1744. stopFunc();
  1745. }
  1746. },
  1747. flash: function() {
  1748. if (satisfyCnt === depCnt) {
  1749. stopFunc();
  1750. startFunc(values);
  1751. }
  1752. }
  1753. };
  1754. },
  1755. flash: function(name) {
  1756. var watcher = this._watchers[name];
  1757. if (watcher) {
  1758. watcher.flash();
  1759. }
  1760. }
  1761. });
  1762. Model.watch = function(/* same arguments as this.watch() */) {
  1763. var proto = this.prototype;
  1764. if (!proto._globalWatchArgs) {
  1765. proto._globalWatchArgs = [];
  1766. }
  1767. proto._globalWatchArgs.push(arguments);
  1768. };
  1769. FC.Model = Model;
  1770. ;;
  1771. var Promise = {
  1772. construct: function(executor) {
  1773. var deferred = $.Deferred();
  1774. var promise = deferred.promise();
  1775. if (typeof executor === 'function') {
  1776. executor(
  1777. function(val) { // resolve
  1778. deferred.resolve(val);
  1779. attachImmediatelyResolvingThen(promise, val);
  1780. },
  1781. function() { // reject
  1782. deferred.reject();
  1783. attachImmediatelyRejectingThen(promise);
  1784. }
  1785. );
  1786. }
  1787. return promise;
  1788. },
  1789. resolve: function(val) {
  1790. var deferred = $.Deferred().resolve(val);
  1791. var promise = deferred.promise();
  1792. attachImmediatelyResolvingThen(promise, val);
  1793. return promise;
  1794. },
  1795. reject: function() {
  1796. var deferred = $.Deferred().reject();
  1797. var promise = deferred.promise();
  1798. attachImmediatelyRejectingThen(promise);
  1799. return promise;
  1800. }
  1801. };
  1802. function attachImmediatelyResolvingThen(promise, val) {
  1803. promise.then = function(onResolve) {
  1804. if (typeof onResolve === 'function') {
  1805. onResolve(val);
  1806. }
  1807. return promise; // for chaining
  1808. };
  1809. }
  1810. function attachImmediatelyRejectingThen(promise) {
  1811. promise.then = function(onResolve, onReject) {
  1812. if (typeof onReject === 'function') {
  1813. onReject();
  1814. }
  1815. return promise; // for chaining
  1816. };
  1817. }
  1818. FC.Promise = Promise;
  1819. ;;
  1820. var TaskQueue = Class.extend(EmitterMixin, {
  1821. q: null,
  1822. isPaused: false,
  1823. isRunning: false,
  1824. constructor: function() {
  1825. this.q = [];
  1826. },
  1827. queue: function(/* taskFunc, taskFunc... */) {
  1828. this.q.push.apply(this.q, arguments); // append
  1829. this.tryStart();
  1830. },
  1831. pause: function() {
  1832. this.isPaused = true;
  1833. },
  1834. resume: function() {
  1835. this.isPaused = false;
  1836. this.tryStart();
  1837. },
  1838. tryStart: function() {
  1839. if (!this.isRunning && this.canRunNext()) {
  1840. this.isRunning = true;
  1841. this.trigger('start');
  1842. this.runNext();
  1843. }
  1844. },
  1845. canRunNext: function() {
  1846. return !this.isPaused && this.q.length;
  1847. },
  1848. runNext: function() { // does not check canRunNext
  1849. this.runTask(this.q.shift());
  1850. },
  1851. runTask: function(task) {
  1852. this.runTaskFunc(task);
  1853. },
  1854. runTaskFunc: function(taskFunc) {
  1855. var _this = this;
  1856. var res = taskFunc();
  1857. if (res && res.then) {
  1858. res.then(done);
  1859. }
  1860. else {
  1861. done();
  1862. }
  1863. function done() {
  1864. if (_this.canRunNext()) {
  1865. _this.runNext();
  1866. }
  1867. else {
  1868. _this.isRunning = false;
  1869. _this.trigger('stop');
  1870. }
  1871. }
  1872. }
  1873. });
  1874. FC.TaskQueue = TaskQueue;
  1875. ;;
  1876. var RenderQueue = TaskQueue.extend({
  1877. waitsByNamespace: null,
  1878. waitNamespace: null,
  1879. waitId: null,
  1880. constructor: function(waitsByNamespace) {
  1881. TaskQueue.call(this); // super-constructor
  1882. this.waitsByNamespace = waitsByNamespace || {};
  1883. },
  1884. queue: function(taskFunc, namespace, type) {
  1885. var task = {
  1886. func: taskFunc,
  1887. namespace: namespace,
  1888. type: type
  1889. };
  1890. var waitMs;
  1891. if (namespace) {
  1892. waitMs = this.waitsByNamespace[namespace];
  1893. }
  1894. if (this.waitNamespace) {
  1895. if (namespace === this.waitNamespace && waitMs != null) {
  1896. this.delayWait(waitMs);
  1897. }
  1898. else {
  1899. this.clearWait();
  1900. this.tryStart();
  1901. }
  1902. }
  1903. if (this.compoundTask(task)) { // appended to queue?
  1904. if (!this.waitNamespace && waitMs != null) {
  1905. this.startWait(namespace, waitMs);
  1906. }
  1907. else {
  1908. this.tryStart();
  1909. }
  1910. }
  1911. },
  1912. startWait: function(namespace, waitMs) {
  1913. this.waitNamespace = namespace;
  1914. this.spawnWait(waitMs);
  1915. },
  1916. delayWait: function(waitMs) {
  1917. clearTimeout(this.waitId);
  1918. this.spawnWait(waitMs);
  1919. },
  1920. spawnWait: function(waitMs) {
  1921. var _this = this;
  1922. this.waitId = setTimeout(function() {
  1923. _this.waitNamespace = null;
  1924. _this.tryStart();
  1925. }, waitMs);
  1926. },
  1927. clearWait: function() {
  1928. if (this.waitNamespace) {
  1929. clearTimeout(this.waitId);
  1930. this.waitId = null;
  1931. this.waitNamespace = null;
  1932. }
  1933. },
  1934. canRunNext: function() {
  1935. if (!TaskQueue.prototype.canRunNext.apply(this, arguments)) {
  1936. return false;
  1937. }
  1938. // waiting for a certain namespace to stop receiving tasks?
  1939. if (this.waitNamespace) {
  1940. // if there was a different namespace task in the meantime,
  1941. // that forces all previously-waiting tasks to suddenly execute.
  1942. // TODO: find a way to do this in constant time.
  1943. for (var q = this.q, i = 0; i < q.length; i++) {
  1944. if (q[i].namespace !== this.waitNamespace) {
  1945. return true; // allow execution
  1946. }
  1947. }
  1948. return false;
  1949. }
  1950. return true;
  1951. },
  1952. runTask: function(task) {
  1953. this.runTaskFunc(task.func);
  1954. },
  1955. compoundTask: function(newTask) {
  1956. var q = this.q;
  1957. var shouldAppend = true;
  1958. var i, task;
  1959. if (newTask.namespace) {
  1960. if (newTask.type === 'destroy' || newTask.type === 'init') {
  1961. // remove all add/remove ops with same namespace, regardless of order
  1962. for (i = q.length - 1; i >= 0; i--) {
  1963. task = q[i];
  1964. if (
  1965. task.namespace === newTask.namespace &&
  1966. (task.type === 'add' || task.type === 'remove')
  1967. ) {
  1968. q.splice(i, 1); // remove task
  1969. }
  1970. }
  1971. if (newTask.type === 'destroy') {
  1972. // eat away final init/destroy operation
  1973. if (q.length) {
  1974. task = q[q.length - 1]; // last task
  1975. if (task.namespace === newTask.namespace) {
  1976. // the init and our destroy cancel each other out
  1977. if (task.type === 'init') {
  1978. shouldAppend = false;
  1979. q.pop();
  1980. }
  1981. // prefer to use the destroy operation that's already present
  1982. else if (task.type === 'destroy') {
  1983. shouldAppend = false;
  1984. }
  1985. }
  1986. }
  1987. }
  1988. else if (newTask.type === 'init') {
  1989. // eat away final init operation
  1990. if (q.length) {
  1991. task = q[q.length - 1]; // last task
  1992. if (
  1993. task.namespace === newTask.namespace &&
  1994. task.type === 'init'
  1995. ) {
  1996. // our init operation takes precedence
  1997. q.pop();
  1998. }
  1999. }
  2000. }
  2001. }
  2002. }
  2003. if (shouldAppend) {
  2004. q.push(newTask);
  2005. }
  2006. return shouldAppend;
  2007. }
  2008. });
  2009. FC.RenderQueue = RenderQueue;
  2010. ;;
  2011. var EmitterMixin = FC.EmitterMixin = {
  2012. // jQuery-ification via $(this) allows a non-DOM object to have
  2013. // the same event handling capabilities (including namespaces).
  2014. on: function(types, handler) {
  2015. $(this).on(types, this._prepareIntercept(handler));
  2016. return this; // for chaining
  2017. },
  2018. one: function(types, handler) {
  2019. $(this).one(types, this._prepareIntercept(handler));
  2020. return this; // for chaining
  2021. },
  2022. _prepareIntercept: function(handler) {
  2023. // handlers are always called with an "event" object as their first param.
  2024. // sneak the `this` context and arguments into the extra parameter object
  2025. // and forward them on to the original handler.
  2026. var intercept = function(ev, extra) {
  2027. return handler.apply(
  2028. extra.context || this,
  2029. extra.args || []
  2030. );
  2031. };
  2032. // mimick jQuery's internal "proxy" system (risky, I know)
  2033. // causing all functions with the same .guid to appear to be the same.
  2034. // https://github.com/jquery/jquery/blob/2.2.4/src/core.js#L448
  2035. // this is needed for calling .off with the original non-intercept handler.
  2036. if (!handler.guid) {
  2037. handler.guid = $.guid++;
  2038. }
  2039. intercept.guid = handler.guid;
  2040. return intercept;
  2041. },
  2042. off: function(types, handler) {
  2043. $(this).off(types, handler);
  2044. return this; // for chaining
  2045. },
  2046. trigger: function(types) {
  2047. var args = Array.prototype.slice.call(arguments, 1); // arguments after the first
  2048. // pass in "extra" info to the intercept
  2049. $(this).triggerHandler(types, { args: args });
  2050. return this; // for chaining
  2051. },
  2052. triggerWith: function(types, context, args) {
  2053. // `triggerHandler` is less reliant on the DOM compared to `trigger`.
  2054. // pass in "extra" info to the intercept.
  2055. $(this).triggerHandler(types, { context: context, args: args });
  2056. return this; // for chaining
  2057. }
  2058. };
  2059. ;;
  2060. /*
  2061. Utility methods for easily listening to events on another object,
  2062. and more importantly, easily unlistening from them.
  2063. */
  2064. var ListenerMixin = FC.ListenerMixin = (function() {
  2065. var guid = 0;
  2066. var ListenerMixin = {
  2067. listenerId: null,
  2068. /*
  2069. Given an `other` object that has on/off methods, bind the given `callback` to an event by the given name.
  2070. The `callback` will be called with the `this` context of the object that .listenTo is being called on.
  2071. Can be called:
  2072. .listenTo(other, eventName, callback)
  2073. OR
  2074. .listenTo(other, {
  2075. eventName1: callback1,
  2076. eventName2: callback2
  2077. })
  2078. */
  2079. listenTo: function(other, arg, callback) {
  2080. if (typeof arg === 'object') { // given dictionary of callbacks
  2081. for (var eventName in arg) {
  2082. if (arg.hasOwnProperty(eventName)) {
  2083. this.listenTo(other, eventName, arg[eventName]);
  2084. }
  2085. }
  2086. }
  2087. else if (typeof arg === 'string') {
  2088. other.on(
  2089. arg + '.' + this.getListenerNamespace(), // use event namespacing to identify this object
  2090. $.proxy(callback, this) // always use `this` context
  2091. // the usually-undesired jQuery guid behavior doesn't matter,
  2092. // because we always unbind via namespace
  2093. );
  2094. }
  2095. },
  2096. /*
  2097. Causes the current object to stop listening to events on the `other` object.
  2098. `eventName` is optional. If omitted, will stop listening to ALL events on `other`.
  2099. */
  2100. stopListeningTo: function(other, eventName) {
  2101. other.off((eventName || '') + '.' + this.getListenerNamespace());
  2102. },
  2103. /*
  2104. Returns a string, unique to this object, to be used for event namespacing
  2105. */
  2106. getListenerNamespace: function() {
  2107. if (this.listenerId == null) {
  2108. this.listenerId = guid++;
  2109. }
  2110. return '_listener' + this.listenerId;
  2111. }
  2112. };
  2113. return ListenerMixin;
  2114. })();
  2115. ;;
  2116. /* A rectangular panel that is absolutely positioned over other content
  2117. ------------------------------------------------------------------------------------------------------------------------
  2118. Options:
  2119. - className (string)
  2120. - content (HTML string or jQuery element set)
  2121. - parentEl
  2122. - top
  2123. - left
  2124. - right (the x coord of where the right edge should be. not a "CSS" right)
  2125. - autoHide (boolean)
  2126. - show (callback)
  2127. - hide (callback)
  2128. */
  2129. var Popover = Class.extend(ListenerMixin, {
  2130. isHidden: true,
  2131. options: null,
  2132. el: null, // the container element for the popover. generated by this object
  2133. margin: 10, // the space required between the popover and the edges of the scroll container
  2134. constructor: function(options) {
  2135. this.options = options || {};
  2136. },
  2137. // Shows the popover on the specified position. Renders it if not already
  2138. show: function() {
  2139. if (this.isHidden) {
  2140. if (!this.el) {
  2141. this.render();
  2142. }
  2143. this.el.show();
  2144. this.position();
  2145. this.isHidden = false;
  2146. this.trigger('show');
  2147. }
  2148. },
  2149. // Hides the popover, through CSS, but does not remove it from the DOM
  2150. hide: function() {
  2151. if (!this.isHidden) {
  2152. this.el.hide();
  2153. this.isHidden = true;
  2154. this.trigger('hide');
  2155. }
  2156. },
  2157. // Creates `this.el` and renders content inside of it
  2158. render: function() {
  2159. var _this = this;
  2160. var options = this.options;
  2161. this.el = $('<div class="fc-popover"/>')
  2162. .addClass(options.className || '')
  2163. .css({
  2164. // position initially to the top left to avoid creating scrollbars
  2165. top: 0,
  2166. left: 0
  2167. })
  2168. .append(options.content)
  2169. .appendTo(options.parentEl);
  2170. // when a click happens on anything inside with a 'fc-close' className, hide the popover
  2171. this.el.on('click', '.fc-close', function() {
  2172. _this.hide();
  2173. });
  2174. if (options.autoHide) {
  2175. this.listenTo($(document), 'mousedown', this.documentMousedown);
  2176. }
  2177. },
  2178. // Triggered when the user clicks *anywhere* in the document, for the autoHide feature
  2179. documentMousedown: function(ev) {
  2180. // only hide the popover if the click happened outside the popover
  2181. if (this.el && !$(ev.target).closest(this.el).length) {
  2182. this.hide();
  2183. }
  2184. },
  2185. // Hides and unregisters any handlers
  2186. removeElement: function() {
  2187. this.hide();
  2188. if (this.el) {
  2189. this.el.remove();
  2190. this.el = null;
  2191. }
  2192. this.stopListeningTo($(document), 'mousedown');
  2193. },
  2194. // Positions the popover optimally, using the top/left/right options
  2195. position: function() {
  2196. var options = this.options;
  2197. var origin = this.el.offsetParent().offset();
  2198. var width = this.el.outerWidth();
  2199. var height = this.el.outerHeight();
  2200. var windowEl = $(window);
  2201. var viewportEl = getScrollParent(this.el);
  2202. var viewportTop;
  2203. var viewportLeft;
  2204. var viewportOffset;
  2205. var top; // the "position" (not "offset") values for the popover
  2206. var left; //
  2207. // compute top and left
  2208. top = options.top || 0;
  2209. if (options.left !== undefined) {
  2210. left = options.left;
  2211. }
  2212. else if (options.right !== undefined) {
  2213. left = options.right - width; // derive the left value from the right value
  2214. }
  2215. else {
  2216. left = 0;
  2217. }
  2218. if (viewportEl.is(window) || viewportEl.is(document)) { // normalize getScrollParent's result
  2219. viewportEl = windowEl;
  2220. viewportTop = 0; // the window is always at the top left
  2221. viewportLeft = 0; // (and .offset() won't work if called here)
  2222. }
  2223. else {
  2224. viewportOffset = viewportEl.offset();
  2225. viewportTop = viewportOffset.top;
  2226. viewportLeft = viewportOffset.left;
  2227. }
  2228. // if the window is scrolled, it causes the visible area to be further down
  2229. viewportTop += windowEl.scrollTop();
  2230. viewportLeft += windowEl.scrollLeft();
  2231. // constrain to the view port. if constrained by two edges, give precedence to top/left
  2232. if (options.viewportConstrain !== false) {
  2233. top = Math.min(top, viewportTop + viewportEl.outerHeight() - height - this.margin);
  2234. top = Math.max(top, viewportTop + this.margin);
  2235. left = Math.min(left, viewportLeft + viewportEl.outerWidth() - width - this.margin);
  2236. left = Math.max(left, viewportLeft + this.margin);
  2237. }
  2238. this.el.css({
  2239. top: top - origin.top,
  2240. left: left - origin.left
  2241. });
  2242. },
  2243. // Triggers a callback. Calls a function in the option hash of the same name.
  2244. // Arguments beyond the first `name` are forwarded on.
  2245. // TODO: better code reuse for this. Repeat code
  2246. trigger: function(name) {
  2247. if (this.options[name]) {
  2248. this.options[name].apply(this, Array.prototype.slice.call(arguments, 1));
  2249. }
  2250. }
  2251. });
  2252. ;;
  2253. /*
  2254. A cache for the left/right/top/bottom/width/height values for one or more elements.
  2255. Works with both offset (from topleft document) and position (from offsetParent).
  2256. options:
  2257. - els
  2258. - isHorizontal
  2259. - isVertical
  2260. */
  2261. var CoordCache = FC.CoordCache = Class.extend({
  2262. els: null, // jQuery set (assumed to be siblings)
  2263. forcedOffsetParentEl: null, // options can override the natural offsetParent
  2264. origin: null, // {left,top} position of offsetParent of els
  2265. boundingRect: null, // constrain cordinates to this rectangle. {left,right,top,bottom} or null
  2266. isHorizontal: false, // whether to query for left/right/width
  2267. isVertical: false, // whether to query for top/bottom/height
  2268. // arrays of coordinates (offsets from topleft of document)
  2269. lefts: null,
  2270. rights: null,
  2271. tops: null,
  2272. bottoms: null,
  2273. constructor: function(options) {
  2274. this.els = $(options.els);
  2275. this.isHorizontal = options.isHorizontal;
  2276. this.isVertical = options.isVertical;
  2277. this.forcedOffsetParentEl = options.offsetParent ? $(options.offsetParent) : null;
  2278. },
  2279. // Queries the els for coordinates and stores them.
  2280. // Call this method before using and of the get* methods below.
  2281. build: function() {
  2282. var offsetParentEl = this.forcedOffsetParentEl;
  2283. if (!offsetParentEl && this.els.length > 0) {
  2284. offsetParentEl = this.els.eq(0).offsetParent();
  2285. }
  2286. this.origin = offsetParentEl ?
  2287. offsetParentEl.offset() :
  2288. null;
  2289. this.boundingRect = this.queryBoundingRect();
  2290. if (this.isHorizontal) {
  2291. this.buildElHorizontals();
  2292. }
  2293. if (this.isVertical) {
  2294. this.buildElVerticals();
  2295. }
  2296. },
  2297. // Destroys all internal data about coordinates, freeing memory
  2298. clear: function() {
  2299. this.origin = null;
  2300. this.boundingRect = null;
  2301. this.lefts = null;
  2302. this.rights = null;
  2303. this.tops = null;
  2304. this.bottoms = null;
  2305. },
  2306. // When called, if coord caches aren't built, builds them
  2307. ensureBuilt: function() {
  2308. if (!this.origin) {
  2309. this.build();
  2310. }
  2311. },
  2312. // Populates the left/right internal coordinate arrays
  2313. buildElHorizontals: function() {
  2314. var lefts = [];
  2315. var rights = [];
  2316. this.els.each(function(i, node) {
  2317. var el = $(node);
  2318. var left = el.offset().left;
  2319. var width = el.outerWidth();
  2320. lefts.push(left);
  2321. rights.push(left + width);
  2322. });
  2323. this.lefts = lefts;
  2324. this.rights = rights;
  2325. },
  2326. // Populates the top/bottom internal coordinate arrays
  2327. buildElVerticals: function() {
  2328. var tops = [];
  2329. var bottoms = [];
  2330. this.els.each(function(i, node) {
  2331. var el = $(node);
  2332. var top = el.offset().top;
  2333. var height = el.outerHeight();
  2334. tops.push(top);
  2335. bottoms.push(top + height);
  2336. });
  2337. this.tops = tops;
  2338. this.bottoms = bottoms;
  2339. },
  2340. // Given a left offset (from document left), returns the index of the el that it horizontally intersects.
  2341. // If no intersection is made, returns undefined.
  2342. getHorizontalIndex: function(leftOffset) {
  2343. this.ensureBuilt();
  2344. var lefts = this.lefts;
  2345. var rights = this.rights;
  2346. var len = lefts.length;
  2347. var i;
  2348. for (i = 0; i < len; i++) {
  2349. if (leftOffset >= lefts[i] && leftOffset < rights[i]) {
  2350. return i;
  2351. }
  2352. }
  2353. },
  2354. // Given a top offset (from document top), returns the index of the el that it vertically intersects.
  2355. // If no intersection is made, returns undefined.
  2356. getVerticalIndex: function(topOffset) {
  2357. this.ensureBuilt();
  2358. var tops = this.tops;
  2359. var bottoms = this.bottoms;
  2360. var len = tops.length;
  2361. var i;
  2362. for (i = 0; i < len; i++) {
  2363. if (topOffset >= tops[i] && topOffset < bottoms[i]) {
  2364. return i;
  2365. }
  2366. }
  2367. },
  2368. // Gets the left offset (from document left) of the element at the given index
  2369. getLeftOffset: function(leftIndex) {
  2370. this.ensureBuilt();
  2371. return this.lefts[leftIndex];
  2372. },
  2373. // Gets the left position (from offsetParent left) of the element at the given index
  2374. getLeftPosition: function(leftIndex) {
  2375. this.ensureBuilt();
  2376. return this.lefts[leftIndex] - this.origin.left;
  2377. },
  2378. // Gets the right offset (from document left) of the element at the given index.
  2379. // This value is NOT relative to the document's right edge, like the CSS concept of "right" would be.
  2380. getRightOffset: function(leftIndex) {
  2381. this.ensureBuilt();
  2382. return this.rights[leftIndex];
  2383. },
  2384. // Gets the right position (from offsetParent left) of the element at the given index.
  2385. // This value is NOT relative to the offsetParent's right edge, like the CSS concept of "right" would be.
  2386. getRightPosition: function(leftIndex) {
  2387. this.ensureBuilt();
  2388. return this.rights[leftIndex] - this.origin.left;
  2389. },
  2390. // Gets the width of the element at the given index
  2391. getWidth: function(leftIndex) {
  2392. this.ensureBuilt();
  2393. return this.rights[leftIndex] - this.lefts[leftIndex];
  2394. },
  2395. // Gets the top offset (from document top) of the element at the given index
  2396. getTopOffset: function(topIndex) {
  2397. this.ensureBuilt();
  2398. return this.tops[topIndex];
  2399. },
  2400. // Gets the top position (from offsetParent top) of the element at the given position
  2401. getTopPosition: function(topIndex) {
  2402. this.ensureBuilt();
  2403. return this.tops[topIndex] - this.origin.top;
  2404. },
  2405. // Gets the bottom offset (from the document top) of the element at the given index.
  2406. // This value is NOT relative to the offsetParent's bottom edge, like the CSS concept of "bottom" would be.
  2407. getBottomOffset: function(topIndex) {
  2408. this.ensureBuilt();
  2409. return this.bottoms[topIndex];
  2410. },
  2411. // Gets the bottom position (from the offsetParent top) of the element at the given index.
  2412. // This value is NOT relative to the offsetParent's bottom edge, like the CSS concept of "bottom" would be.
  2413. getBottomPosition: function(topIndex) {
  2414. this.ensureBuilt();
  2415. return this.bottoms[topIndex] - this.origin.top;
  2416. },
  2417. // Gets the height of the element at the given index
  2418. getHeight: function(topIndex) {
  2419. this.ensureBuilt();
  2420. return this.bottoms[topIndex] - this.tops[topIndex];
  2421. },
  2422. // Bounding Rect
  2423. // TODO: decouple this from CoordCache
  2424. // Compute and return what the elements' bounding rectangle is, from the user's perspective.
  2425. // Right now, only returns a rectangle if constrained by an overflow:scroll element.
  2426. // Returns null if there are no elements
  2427. queryBoundingRect: function() {
  2428. var scrollParentEl;
  2429. if (this.els.length > 0) {
  2430. scrollParentEl = getScrollParent(this.els.eq(0));
  2431. if (!scrollParentEl.is(document)) {
  2432. return getClientRect(scrollParentEl);
  2433. }
  2434. }
  2435. return null;
  2436. },
  2437. isPointInBounds: function(leftOffset, topOffset) {
  2438. return this.isLeftInBounds(leftOffset) && this.isTopInBounds(topOffset);
  2439. },
  2440. isLeftInBounds: function(leftOffset) {
  2441. return !this.boundingRect || (leftOffset >= this.boundingRect.left && leftOffset < this.boundingRect.right);
  2442. },
  2443. isTopInBounds: function(topOffset) {
  2444. return !this.boundingRect || (topOffset >= this.boundingRect.top && topOffset < this.boundingRect.bottom);
  2445. }
  2446. });
  2447. ;;
  2448. /* Tracks a drag's mouse movement, firing various handlers
  2449. ----------------------------------------------------------------------------------------------------------------------*/
  2450. // TODO: use Emitter
  2451. var DragListener = FC.DragListener = Class.extend(ListenerMixin, {
  2452. options: null,
  2453. subjectEl: null,
  2454. // coordinates of the initial mousedown
  2455. originX: null,
  2456. originY: null,
  2457. // the wrapping element that scrolls, or MIGHT scroll if there's overflow.
  2458. // TODO: do this for wrappers that have overflow:hidden as well.
  2459. scrollEl: null,
  2460. isInteracting: false,
  2461. isDistanceSurpassed: false,
  2462. isDelayEnded: false,
  2463. isDragging: false,
  2464. isTouch: false,
  2465. isGeneric: false, // initiated by 'dragstart' (jqui)
  2466. delay: null,
  2467. delayTimeoutId: null,
  2468. minDistance: null,
  2469. shouldCancelTouchScroll: true,
  2470. scrollAlwaysKills: false,
  2471. constructor: function(options) {
  2472. this.options = options || {};
  2473. },
  2474. // Interaction (high-level)
  2475. // -----------------------------------------------------------------------------------------------------------------
  2476. startInteraction: function(ev, extraOptions) {
  2477. if (ev.type === 'mousedown') {
  2478. if (GlobalEmitter.get().shouldIgnoreMouse()) {
  2479. return;
  2480. }
  2481. else if (!isPrimaryMouseButton(ev)) {
  2482. return;
  2483. }
  2484. else {
  2485. ev.preventDefault(); // prevents native selection in most browsers
  2486. }
  2487. }
  2488. if (!this.isInteracting) {
  2489. // process options
  2490. extraOptions = extraOptions || {};
  2491. this.delay = firstDefined(extraOptions.delay, this.options.delay, 0);
  2492. this.minDistance = firstDefined(extraOptions.distance, this.options.distance, 0);
  2493. this.subjectEl = this.options.subjectEl;
  2494. preventSelection($('body'));
  2495. this.isInteracting = true;
  2496. this.isTouch = getEvIsTouch(ev);
  2497. this.isGeneric = ev.type === 'dragstart';
  2498. this.isDelayEnded = false;
  2499. this.isDistanceSurpassed = false;
  2500. this.originX = getEvX(ev);
  2501. this.originY = getEvY(ev);
  2502. this.scrollEl = getScrollParent($(ev.target));
  2503. this.bindHandlers();
  2504. this.initAutoScroll();
  2505. this.handleInteractionStart(ev);
  2506. this.startDelay(ev);
  2507. if (!this.minDistance) {
  2508. this.handleDistanceSurpassed(ev);
  2509. }
  2510. }
  2511. },
  2512. handleInteractionStart: function(ev) {
  2513. this.trigger('interactionStart', ev);
  2514. },
  2515. endInteraction: function(ev, isCancelled) {
  2516. if (this.isInteracting) {
  2517. this.endDrag(ev);
  2518. if (this.delayTimeoutId) {
  2519. clearTimeout(this.delayTimeoutId);
  2520. this.delayTimeoutId = null;
  2521. }
  2522. this.destroyAutoScroll();
  2523. this.unbindHandlers();
  2524. this.isInteracting = false;
  2525. this.handleInteractionEnd(ev, isCancelled);
  2526. allowSelection($('body'));
  2527. }
  2528. },
  2529. handleInteractionEnd: function(ev, isCancelled) {
  2530. this.trigger('interactionEnd', ev, isCancelled || false);
  2531. },
  2532. // Binding To DOM
  2533. // -----------------------------------------------------------------------------------------------------------------
  2534. bindHandlers: function() {
  2535. // some browsers (Safari in iOS 10) don't allow preventDefault on touch events that are bound after touchstart,
  2536. // so listen to the GlobalEmitter singleton, which is always bound, instead of the document directly.
  2537. var globalEmitter = GlobalEmitter.get();
  2538. if (this.isGeneric) {
  2539. this.listenTo($(document), { // might only work on iOS because of GlobalEmitter's bind :(
  2540. drag: this.handleMove,
  2541. dragstop: this.endInteraction
  2542. });
  2543. }
  2544. else if (this.isTouch) {
  2545. this.listenTo(globalEmitter, {
  2546. touchmove: this.handleTouchMove,
  2547. touchend: this.endInteraction,
  2548. scroll: this.handleTouchScroll
  2549. });
  2550. }
  2551. else {
  2552. this.listenTo(globalEmitter, {
  2553. mousemove: this.handleMouseMove,
  2554. mouseup: this.endInteraction
  2555. });
  2556. }
  2557. this.listenTo(globalEmitter, {
  2558. selectstart: preventDefault, // don't allow selection while dragging
  2559. contextmenu: preventDefault // long taps would open menu on Chrome dev tools
  2560. });
  2561. },
  2562. unbindHandlers: function() {
  2563. this.stopListeningTo(GlobalEmitter.get());
  2564. this.stopListeningTo($(document)); // for isGeneric
  2565. },
  2566. // Drag (high-level)
  2567. // -----------------------------------------------------------------------------------------------------------------
  2568. // extraOptions ignored if drag already started
  2569. startDrag: function(ev, extraOptions) {
  2570. this.startInteraction(ev, extraOptions); // ensure interaction began
  2571. if (!this.isDragging) {
  2572. this.isDragging = true;
  2573. this.handleDragStart(ev);
  2574. }
  2575. },
  2576. handleDragStart: function(ev) {
  2577. this.trigger('dragStart', ev);
  2578. },
  2579. handleMove: function(ev) {
  2580. var dx = getEvX(ev) - this.originX;
  2581. var dy = getEvY(ev) - this.originY;
  2582. var minDistance = this.minDistance;
  2583. var distanceSq; // current distance from the origin, squared
  2584. if (!this.isDistanceSurpassed) {
  2585. distanceSq = dx * dx + dy * dy;
  2586. if (distanceSq >= minDistance * minDistance) { // use pythagorean theorem
  2587. this.handleDistanceSurpassed(ev);
  2588. }
  2589. }
  2590. if (this.isDragging) {
  2591. this.handleDrag(dx, dy, ev);
  2592. }
  2593. },
  2594. // Called while the mouse is being moved and when we know a legitimate drag is taking place
  2595. handleDrag: function(dx, dy, ev) {
  2596. this.trigger('drag', dx, dy, ev);
  2597. this.updateAutoScroll(ev); // will possibly cause scrolling
  2598. },
  2599. endDrag: function(ev) {
  2600. if (this.isDragging) {
  2601. this.isDragging = false;
  2602. this.handleDragEnd(ev);
  2603. }
  2604. },
  2605. handleDragEnd: function(ev) {
  2606. this.trigger('dragEnd', ev);
  2607. },
  2608. // Delay
  2609. // -----------------------------------------------------------------------------------------------------------------
  2610. startDelay: function(initialEv) {
  2611. var _this = this;
  2612. if (this.delay) {
  2613. this.delayTimeoutId = setTimeout(function() {
  2614. _this.handleDelayEnd(initialEv);
  2615. }, this.delay);
  2616. }
  2617. else {
  2618. this.handleDelayEnd(initialEv);
  2619. }
  2620. },
  2621. handleDelayEnd: function(initialEv) {
  2622. this.isDelayEnded = true;
  2623. if (this.isDistanceSurpassed) {
  2624. this.startDrag(initialEv);
  2625. }
  2626. },
  2627. // Distance
  2628. // -----------------------------------------------------------------------------------------------------------------
  2629. handleDistanceSurpassed: function(ev) {
  2630. this.isDistanceSurpassed = true;
  2631. if (this.isDelayEnded) {
  2632. this.startDrag(ev);
  2633. }
  2634. },
  2635. // Mouse / Touch
  2636. // -----------------------------------------------------------------------------------------------------------------
  2637. handleTouchMove: function(ev) {
  2638. // prevent inertia and touchmove-scrolling while dragging
  2639. if (this.isDragging && this.shouldCancelTouchScroll) {
  2640. ev.preventDefault();
  2641. }
  2642. this.handleMove(ev);
  2643. },
  2644. handleMouseMove: function(ev) {
  2645. this.handleMove(ev);
  2646. },
  2647. // Scrolling (unrelated to auto-scroll)
  2648. // -----------------------------------------------------------------------------------------------------------------
  2649. handleTouchScroll: function(ev) {
  2650. // if the drag is being initiated by touch, but a scroll happens before
  2651. // the drag-initiating delay is over, cancel the drag
  2652. if (!this.isDragging || this.scrollAlwaysKills) {
  2653. this.endInteraction(ev, true); // isCancelled=true
  2654. }
  2655. },
  2656. // Utils
  2657. // -----------------------------------------------------------------------------------------------------------------
  2658. // Triggers a callback. Calls a function in the option hash of the same name.
  2659. // Arguments beyond the first `name` are forwarded on.
  2660. trigger: function(name) {
  2661. if (this.options[name]) {
  2662. this.options[name].apply(this, Array.prototype.slice.call(arguments, 1));
  2663. }
  2664. // makes _methods callable by event name. TODO: kill this
  2665. if (this['_' + name]) {
  2666. this['_' + name].apply(this, Array.prototype.slice.call(arguments, 1));
  2667. }
  2668. }
  2669. });
  2670. ;;
  2671. /*
  2672. this.scrollEl is set in DragListener
  2673. */
  2674. DragListener.mixin({
  2675. isAutoScroll: false,
  2676. scrollBounds: null, // { top, bottom, left, right }
  2677. scrollTopVel: null, // pixels per second
  2678. scrollLeftVel: null, // pixels per second
  2679. scrollIntervalId: null, // ID of setTimeout for scrolling animation loop
  2680. // defaults
  2681. scrollSensitivity: 30, // pixels from edge for scrolling to start
  2682. scrollSpeed: 200, // pixels per second, at maximum speed
  2683. scrollIntervalMs: 50, // millisecond wait between scroll increment
  2684. initAutoScroll: function() {
  2685. var scrollEl = this.scrollEl;
  2686. this.isAutoScroll =
  2687. this.options.scroll &&
  2688. scrollEl &&
  2689. !scrollEl.is(window) &&
  2690. !scrollEl.is(document);
  2691. if (this.isAutoScroll) {
  2692. // debounce makes sure rapid calls don't happen
  2693. this.listenTo(scrollEl, 'scroll', debounce(this.handleDebouncedScroll, 100));
  2694. }
  2695. },
  2696. destroyAutoScroll: function() {
  2697. this.endAutoScroll(); // kill any animation loop
  2698. // remove the scroll handler if there is a scrollEl
  2699. if (this.isAutoScroll) {
  2700. this.stopListeningTo(this.scrollEl, 'scroll'); // will probably get removed by unbindHandlers too :(
  2701. }
  2702. },
  2703. // Computes and stores the bounding rectangle of scrollEl
  2704. computeScrollBounds: function() {
  2705. if (this.isAutoScroll) {
  2706. this.scrollBounds = getOuterRect(this.scrollEl);
  2707. // TODO: use getClientRect in future. but prevents auto scrolling when on top of scrollbars
  2708. }
  2709. },
  2710. // Called when the dragging is in progress and scrolling should be updated
  2711. updateAutoScroll: function(ev) {
  2712. var sensitivity = this.scrollSensitivity;
  2713. var bounds = this.scrollBounds;
  2714. var topCloseness, bottomCloseness;
  2715. var leftCloseness, rightCloseness;
  2716. var topVel = 0;
  2717. var leftVel = 0;
  2718. if (bounds) { // only scroll if scrollEl exists
  2719. // compute closeness to edges. valid range is from 0.0 - 1.0
  2720. topCloseness = (sensitivity - (getEvY(ev) - bounds.top)) / sensitivity;
  2721. bottomCloseness = (sensitivity - (bounds.bottom - getEvY(ev))) / sensitivity;
  2722. leftCloseness = (sensitivity - (getEvX(ev) - bounds.left)) / sensitivity;
  2723. rightCloseness = (sensitivity - (bounds.right - getEvX(ev))) / sensitivity;
  2724. // translate vertical closeness into velocity.
  2725. // mouse must be completely in bounds for velocity to happen.
  2726. if (topCloseness >= 0 && topCloseness <= 1) {
  2727. topVel = topCloseness * this.scrollSpeed * -1; // negative. for scrolling up
  2728. }
  2729. else if (bottomCloseness >= 0 && bottomCloseness <= 1) {
  2730. topVel = bottomCloseness * this.scrollSpeed;
  2731. }
  2732. // translate horizontal closeness into velocity
  2733. if (leftCloseness >= 0 && leftCloseness <= 1) {
  2734. leftVel = leftCloseness * this.scrollSpeed * -1; // negative. for scrolling left
  2735. }
  2736. else if (rightCloseness >= 0 && rightCloseness <= 1) {
  2737. leftVel = rightCloseness * this.scrollSpeed;
  2738. }
  2739. }
  2740. this.setScrollVel(topVel, leftVel);
  2741. },
  2742. // Sets the speed-of-scrolling for the scrollEl
  2743. setScrollVel: function(topVel, leftVel) {
  2744. this.scrollTopVel = topVel;
  2745. this.scrollLeftVel = leftVel;
  2746. this.constrainScrollVel(); // massages into realistic values
  2747. // if there is non-zero velocity, and an animation loop hasn't already started, then START
  2748. if ((this.scrollTopVel || this.scrollLeftVel) && !this.scrollIntervalId) {
  2749. this.scrollIntervalId = setInterval(
  2750. proxy(this, 'scrollIntervalFunc'), // scope to `this`
  2751. this.scrollIntervalMs
  2752. );
  2753. }
  2754. },
  2755. // Forces scrollTopVel and scrollLeftVel to be zero if scrolling has already gone all the way
  2756. constrainScrollVel: function() {
  2757. var el = this.scrollEl;
  2758. if (this.scrollTopVel < 0) { // scrolling up?
  2759. if (el.scrollTop() <= 0) { // already scrolled all the way up?
  2760. this.scrollTopVel = 0;
  2761. }
  2762. }
  2763. else if (this.scrollTopVel > 0) { // scrolling down?
  2764. if (el.scrollTop() + el[0].clientHeight >= el[0].scrollHeight) { // already scrolled all the way down?
  2765. this.scrollTopVel = 0;
  2766. }
  2767. }
  2768. if (this.scrollLeftVel < 0) { // scrolling left?
  2769. if (el.scrollLeft() <= 0) { // already scrolled all the left?
  2770. this.scrollLeftVel = 0;
  2771. }
  2772. }
  2773. else if (this.scrollLeftVel > 0) { // scrolling right?
  2774. if (el.scrollLeft() + el[0].clientWidth >= el[0].scrollWidth) { // already scrolled all the way right?
  2775. this.scrollLeftVel = 0;
  2776. }
  2777. }
  2778. },
  2779. // This function gets called during every iteration of the scrolling animation loop
  2780. scrollIntervalFunc: function() {
  2781. var el = this.scrollEl;
  2782. var frac = this.scrollIntervalMs / 1000; // considering animation frequency, what the vel should be mult'd by
  2783. // change the value of scrollEl's scroll
  2784. if (this.scrollTopVel) {
  2785. el.scrollTop(el.scrollTop() + this.scrollTopVel * frac);
  2786. }
  2787. if (this.scrollLeftVel) {
  2788. el.scrollLeft(el.scrollLeft() + this.scrollLeftVel * frac);
  2789. }
  2790. this.constrainScrollVel(); // since the scroll values changed, recompute the velocities
  2791. // if scrolled all the way, which causes the vels to be zero, stop the animation loop
  2792. if (!this.scrollTopVel && !this.scrollLeftVel) {
  2793. this.endAutoScroll();
  2794. }
  2795. },
  2796. // Kills any existing scrolling animation loop
  2797. endAutoScroll: function() {
  2798. if (this.scrollIntervalId) {
  2799. clearInterval(this.scrollIntervalId);
  2800. this.scrollIntervalId = null;
  2801. this.handleScrollEnd();
  2802. }
  2803. },
  2804. // Get called when the scrollEl is scrolled (NOTE: this is delayed via debounce)
  2805. handleDebouncedScroll: function() {
  2806. // recompute all coordinates, but *only* if this is *not* part of our scrolling animation
  2807. if (!this.scrollIntervalId) {
  2808. this.handleScrollEnd();
  2809. }
  2810. },
  2811. // Called when scrolling has stopped, whether through auto scroll, or the user scrolling
  2812. handleScrollEnd: function() {
  2813. }
  2814. });
  2815. ;;
  2816. /* Tracks mouse movements over a component and raises events about which hit the mouse is over.
  2817. ------------------------------------------------------------------------------------------------------------------------
  2818. options:
  2819. - subjectEl
  2820. - subjectCenter
  2821. */
  2822. var HitDragListener = DragListener.extend({
  2823. component: null, // converts coordinates to hits
  2824. // methods: hitsNeeded, hitsNotNeeded, queryHit
  2825. origHit: null, // the hit the mouse was over when listening started
  2826. hit: null, // the hit the mouse is over
  2827. coordAdjust: null, // delta that will be added to the mouse coordinates when computing collisions
  2828. constructor: function(component, options) {
  2829. DragListener.call(this, options); // call the super-constructor
  2830. this.component = component;
  2831. },
  2832. // Called when drag listening starts (but a real drag has not necessarily began).
  2833. // ev might be undefined if dragging was started manually.
  2834. handleInteractionStart: function(ev) {
  2835. var subjectEl = this.subjectEl;
  2836. var subjectRect;
  2837. var origPoint;
  2838. var point;
  2839. this.component.hitsNeeded();
  2840. this.computeScrollBounds(); // for autoscroll
  2841. if (ev) {
  2842. origPoint = { left: getEvX(ev), top: getEvY(ev) };
  2843. point = origPoint;
  2844. // constrain the point to bounds of the element being dragged
  2845. if (subjectEl) {
  2846. subjectRect = getOuterRect(subjectEl); // used for centering as well
  2847. point = constrainPoint(point, subjectRect);
  2848. }
  2849. this.origHit = this.queryHit(point.left, point.top);
  2850. // treat the center of the subject as the collision point?
  2851. if (subjectEl && this.options.subjectCenter) {
  2852. // only consider the area the subject overlaps the hit. best for large subjects.
  2853. // TODO: skip this if hit didn't supply left/right/top/bottom
  2854. if (this.origHit) {
  2855. subjectRect = intersectRects(this.origHit, subjectRect) ||
  2856. subjectRect; // in case there is no intersection
  2857. }
  2858. point = getRectCenter(subjectRect);
  2859. }
  2860. this.coordAdjust = diffPoints(point, origPoint); // point - origPoint
  2861. }
  2862. else {
  2863. this.origHit = null;
  2864. this.coordAdjust = null;
  2865. }
  2866. // call the super-method. do it after origHit has been computed
  2867. DragListener.prototype.handleInteractionStart.apply(this, arguments);
  2868. },
  2869. // Called when the actual drag has started
  2870. handleDragStart: function(ev) {
  2871. var hit;
  2872. DragListener.prototype.handleDragStart.apply(this, arguments); // call the super-method
  2873. // might be different from this.origHit if the min-distance is large
  2874. hit = this.queryHit(getEvX(ev), getEvY(ev));
  2875. // report the initial hit the mouse is over
  2876. // especially important if no min-distance and drag starts immediately
  2877. if (hit) {
  2878. this.handleHitOver(hit);
  2879. }
  2880. },
  2881. // Called when the drag moves
  2882. handleDrag: function(dx, dy, ev) {
  2883. var hit;
  2884. DragListener.prototype.handleDrag.apply(this, arguments); // call the super-method
  2885. hit = this.queryHit(getEvX(ev), getEvY(ev));
  2886. if (!isHitsEqual(hit, this.hit)) { // a different hit than before?
  2887. if (this.hit) {
  2888. this.handleHitOut();
  2889. }
  2890. if (hit) {
  2891. this.handleHitOver(hit);
  2892. }
  2893. }
  2894. },
  2895. // Called when dragging has been stopped
  2896. handleDragEnd: function() {
  2897. this.handleHitDone();
  2898. DragListener.prototype.handleDragEnd.apply(this, arguments); // call the super-method
  2899. },
  2900. // Called when a the mouse has just moved over a new hit
  2901. handleHitOver: function(hit) {
  2902. var isOrig = isHitsEqual(hit, this.origHit);
  2903. this.hit = hit;
  2904. this.trigger('hitOver', this.hit, isOrig, this.origHit);
  2905. },
  2906. // Called when the mouse has just moved out of a hit
  2907. handleHitOut: function() {
  2908. if (this.hit) {
  2909. this.trigger('hitOut', this.hit);
  2910. this.handleHitDone();
  2911. this.hit = null;
  2912. }
  2913. },
  2914. // Called after a hitOut. Also called before a dragStop
  2915. handleHitDone: function() {
  2916. if (this.hit) {
  2917. this.trigger('hitDone', this.hit);
  2918. }
  2919. },
  2920. // Called when the interaction ends, whether there was a real drag or not
  2921. handleInteractionEnd: function() {
  2922. DragListener.prototype.handleInteractionEnd.apply(this, arguments); // call the super-method
  2923. this.origHit = null;
  2924. this.hit = null;
  2925. this.component.hitsNotNeeded();
  2926. },
  2927. // Called when scrolling has stopped, whether through auto scroll, or the user scrolling
  2928. handleScrollEnd: function() {
  2929. DragListener.prototype.handleScrollEnd.apply(this, arguments); // call the super-method
  2930. // hits' absolute positions will be in new places after a user's scroll.
  2931. // HACK for recomputing.
  2932. if (this.isDragging) {
  2933. this.component.releaseHits();
  2934. this.component.prepareHits();
  2935. }
  2936. },
  2937. // Gets the hit underneath the coordinates for the given mouse event
  2938. queryHit: function(left, top) {
  2939. if (this.coordAdjust) {
  2940. left += this.coordAdjust.left;
  2941. top += this.coordAdjust.top;
  2942. }
  2943. return this.component.queryHit(left, top);
  2944. }
  2945. });
  2946. // Returns `true` if the hits are identically equal. `false` otherwise. Must be from the same component.
  2947. // Two null values will be considered equal, as two "out of the component" states are the same.
  2948. function isHitsEqual(hit0, hit1) {
  2949. if (!hit0 && !hit1) {
  2950. return true;
  2951. }
  2952. if (hit0 && hit1) {
  2953. return hit0.component === hit1.component &&
  2954. isHitPropsWithin(hit0, hit1) &&
  2955. isHitPropsWithin(hit1, hit0); // ensures all props are identical
  2956. }
  2957. return false;
  2958. }
  2959. // Returns true if all of subHit's non-standard properties are within superHit
  2960. function isHitPropsWithin(subHit, superHit) {
  2961. for (var propName in subHit) {
  2962. if (!/^(component|left|right|top|bottom)$/.test(propName)) {
  2963. if (subHit[propName] !== superHit[propName]) {
  2964. return false;
  2965. }
  2966. }
  2967. }
  2968. return true;
  2969. }
  2970. ;;
  2971. /*
  2972. Listens to document and window-level user-interaction events, like touch events and mouse events,
  2973. and fires these events as-is to whoever is observing a GlobalEmitter.
  2974. Best when used as a singleton via GlobalEmitter.get()
  2975. Normalizes mouse/touch events. For examples:
  2976. - ignores the the simulated mouse events that happen after a quick tap: mousemove+mousedown+mouseup+click
  2977. - compensates for various buggy scenarios where a touchend does not fire
  2978. */
  2979. FC.touchMouseIgnoreWait = 500;
  2980. var GlobalEmitter = Class.extend(ListenerMixin, EmitterMixin, {
  2981. isTouching: false,
  2982. mouseIgnoreDepth: 0,
  2983. handleScrollProxy: null,
  2984. bind: function() {
  2985. var _this = this;
  2986. this.listenTo($(document), {
  2987. touchstart: this.handleTouchStart,
  2988. touchcancel: this.handleTouchCancel,
  2989. touchend: this.handleTouchEnd,
  2990. mousedown: this.handleMouseDown,
  2991. mousemove: this.handleMouseMove,
  2992. mouseup: this.handleMouseUp,
  2993. click: this.handleClick,
  2994. selectstart: this.handleSelectStart,
  2995. contextmenu: this.handleContextMenu
  2996. });
  2997. // because we need to call preventDefault
  2998. // because https://www.chromestatus.com/features/5093566007214080
  2999. // TODO: investigate performance because this is a global handler
  3000. window.addEventListener(
  3001. 'touchmove',
  3002. this.handleTouchMoveProxy = function(ev) {
  3003. _this.handleTouchMove($.Event(ev));
  3004. },
  3005. { passive: false } // allows preventDefault()
  3006. );
  3007. // attach a handler to get called when ANY scroll action happens on the page.
  3008. // this was impossible to do with normal on/off because 'scroll' doesn't bubble.
  3009. // http://stackoverflow.com/a/32954565/96342
  3010. window.addEventListener(
  3011. 'scroll',
  3012. this.handleScrollProxy = function(ev) {
  3013. _this.handleScroll($.Event(ev));
  3014. },
  3015. true // useCapture
  3016. );
  3017. },
  3018. unbind: function() {
  3019. this.stopListeningTo($(document));
  3020. window.removeEventListener(
  3021. 'touchmove',
  3022. this.handleTouchMoveProxy
  3023. );
  3024. window.removeEventListener(
  3025. 'scroll',
  3026. this.handleScrollProxy,
  3027. true // useCapture
  3028. );
  3029. },
  3030. // Touch Handlers
  3031. // -----------------------------------------------------------------------------------------------------------------
  3032. handleTouchStart: function(ev) {
  3033. // if a previous touch interaction never ended with a touchend, then implicitly end it,
  3034. // but since a new touch interaction is about to begin, don't start the mouse ignore period.
  3035. this.stopTouch(ev, true); // skipMouseIgnore=true
  3036. this.isTouching = true;
  3037. this.trigger('touchstart', ev);
  3038. },
  3039. handleTouchMove: function(ev) {
  3040. if (this.isTouching) {
  3041. this.trigger('touchmove', ev);
  3042. }
  3043. },
  3044. handleTouchCancel: function(ev) {
  3045. if (this.isTouching) {
  3046. this.trigger('touchcancel', ev);
  3047. // Have touchcancel fire an artificial touchend. That way, handlers won't need to listen to both.
  3048. // If touchend fires later, it won't have any effect b/c isTouching will be false.
  3049. this.stopTouch(ev);
  3050. }
  3051. },
  3052. handleTouchEnd: function(ev) {
  3053. this.stopTouch(ev);
  3054. },
  3055. // Mouse Handlers
  3056. // -----------------------------------------------------------------------------------------------------------------
  3057. handleMouseDown: function(ev) {
  3058. if (!this.shouldIgnoreMouse()) {
  3059. this.trigger('mousedown', ev);
  3060. }
  3061. },
  3062. handleMouseMove: function(ev) {
  3063. if (!this.shouldIgnoreMouse()) {
  3064. this.trigger('mousemove', ev);
  3065. }
  3066. },
  3067. handleMouseUp: function(ev) {
  3068. if (!this.shouldIgnoreMouse()) {
  3069. this.trigger('mouseup', ev);
  3070. }
  3071. },
  3072. handleClick: function(ev) {
  3073. if (!this.shouldIgnoreMouse()) {
  3074. this.trigger('click', ev);
  3075. }
  3076. },
  3077. // Misc Handlers
  3078. // -----------------------------------------------------------------------------------------------------------------
  3079. handleSelectStart: function(ev) {
  3080. this.trigger('selectstart', ev);
  3081. },
  3082. handleContextMenu: function(ev) {
  3083. this.trigger('contextmenu', ev);
  3084. },
  3085. handleScroll: function(ev) {
  3086. this.trigger('scroll', ev);
  3087. },
  3088. // Utils
  3089. // -----------------------------------------------------------------------------------------------------------------
  3090. stopTouch: function(ev, skipMouseIgnore) {
  3091. if (this.isTouching) {
  3092. this.isTouching = false;
  3093. this.trigger('touchend', ev);
  3094. if (!skipMouseIgnore) {
  3095. this.startTouchMouseIgnore();
  3096. }
  3097. }
  3098. },
  3099. startTouchMouseIgnore: function() {
  3100. var _this = this;
  3101. var wait = FC.touchMouseIgnoreWait;
  3102. if (wait) {
  3103. this.mouseIgnoreDepth++;
  3104. setTimeout(function() {
  3105. _this.mouseIgnoreDepth--;
  3106. }, wait);
  3107. }
  3108. },
  3109. shouldIgnoreMouse: function() {
  3110. return this.isTouching || Boolean(this.mouseIgnoreDepth);
  3111. }
  3112. });
  3113. // Singleton
  3114. // ---------------------------------------------------------------------------------------------------------------------
  3115. (function() {
  3116. var globalEmitter = null;
  3117. var neededCount = 0;
  3118. // gets the singleton
  3119. GlobalEmitter.get = function() {
  3120. if (!globalEmitter) {
  3121. globalEmitter = new GlobalEmitter();
  3122. globalEmitter.bind();
  3123. }
  3124. return globalEmitter;
  3125. };
  3126. // called when an object knows it will need a GlobalEmitter in the near future.
  3127. GlobalEmitter.needed = function() {
  3128. GlobalEmitter.get(); // ensures globalEmitter
  3129. neededCount++;
  3130. };
  3131. // called when the object that originally called needed() doesn't need a GlobalEmitter anymore.
  3132. GlobalEmitter.unneeded = function() {
  3133. neededCount--;
  3134. if (!neededCount) { // nobody else needs it
  3135. globalEmitter.unbind();
  3136. globalEmitter = null;
  3137. }
  3138. };
  3139. })();
  3140. ;;
  3141. /* Creates a clone of an element and lets it track the mouse as it moves
  3142. ----------------------------------------------------------------------------------------------------------------------*/
  3143. var MouseFollower = Class.extend(ListenerMixin, {
  3144. options: null,
  3145. sourceEl: null, // the element that will be cloned and made to look like it is dragging
  3146. el: null, // the clone of `sourceEl` that will track the mouse
  3147. parentEl: null, // the element that `el` (the clone) will be attached to
  3148. // the initial position of el, relative to the offset parent. made to match the initial offset of sourceEl
  3149. top0: null,
  3150. left0: null,
  3151. // the absolute coordinates of the initiating touch/mouse action
  3152. y0: null,
  3153. x0: null,
  3154. // the number of pixels the mouse has moved from its initial position
  3155. topDelta: null,
  3156. leftDelta: null,
  3157. isFollowing: false,
  3158. isHidden: false,
  3159. isAnimating: false, // doing the revert animation?
  3160. constructor: function(sourceEl, options) {
  3161. this.options = options = options || {};
  3162. this.sourceEl = sourceEl;
  3163. this.parentEl = options.parentEl ? $(options.parentEl) : sourceEl.parent(); // default to sourceEl's parent
  3164. },
  3165. // Causes the element to start following the mouse
  3166. start: function(ev) {
  3167. if (!this.isFollowing) {
  3168. this.isFollowing = true;
  3169. this.y0 = getEvY(ev);
  3170. this.x0 = getEvX(ev);
  3171. this.topDelta = 0;
  3172. this.leftDelta = 0;
  3173. if (!this.isHidden) {
  3174. this.updatePosition();
  3175. }
  3176. if (getEvIsTouch(ev)) {
  3177. this.listenTo($(document), 'touchmove', this.handleMove);
  3178. }
  3179. else {
  3180. this.listenTo($(document), 'mousemove', this.handleMove);
  3181. }
  3182. }
  3183. },
  3184. // Causes the element to stop following the mouse. If shouldRevert is true, will animate back to original position.
  3185. // `callback` gets invoked when the animation is complete. If no animation, it is invoked immediately.
  3186. stop: function(shouldRevert, callback) {
  3187. var _this = this;
  3188. var revertDuration = this.options.revertDuration;
  3189. function complete() { // might be called by .animate(), which might change `this` context
  3190. _this.isAnimating = false;
  3191. _this.removeElement();
  3192. _this.top0 = _this.left0 = null; // reset state for future updatePosition calls
  3193. if (callback) {
  3194. callback();
  3195. }
  3196. }
  3197. if (this.isFollowing && !this.isAnimating) { // disallow more than one stop animation at a time
  3198. this.isFollowing = false;
  3199. this.stopListeningTo($(document));
  3200. if (shouldRevert && revertDuration && !this.isHidden) { // do a revert animation?
  3201. this.isAnimating = true;
  3202. this.el.animate({
  3203. top: this.top0,
  3204. left: this.left0
  3205. }, {
  3206. duration: revertDuration,
  3207. complete: complete
  3208. });
  3209. }
  3210. else {
  3211. complete();
  3212. }
  3213. }
  3214. },
  3215. // Gets the tracking element. Create it if necessary
  3216. getEl: function() {
  3217. var el = this.el;
  3218. if (!el) {
  3219. el = this.el = this.sourceEl.clone()
  3220. .addClass(this.options.additionalClass || '')
  3221. .css({
  3222. position: 'absolute',
  3223. visibility: '', // in case original element was hidden (commonly through hideEvents())
  3224. display: this.isHidden ? 'none' : '', // for when initially hidden
  3225. margin: 0,
  3226. right: 'auto', // erase and set width instead
  3227. bottom: 'auto', // erase and set height instead
  3228. width: this.sourceEl.width(), // explicit height in case there was a 'right' value
  3229. height: this.sourceEl.height(), // explicit width in case there was a 'bottom' value
  3230. opacity: this.options.opacity || '',
  3231. zIndex: this.options.zIndex
  3232. });
  3233. // we don't want long taps or any mouse interaction causing selection/menus.
  3234. // would use preventSelection(), but that prevents selectstart, causing problems.
  3235. el.addClass('fc-unselectable');
  3236. el.appendTo(this.parentEl);
  3237. }
  3238. return el;
  3239. },
  3240. // Removes the tracking element if it has already been created
  3241. removeElement: function() {
  3242. if (this.el) {
  3243. this.el.remove();
  3244. this.el = null;
  3245. }
  3246. },
  3247. // Update the CSS position of the tracking element
  3248. updatePosition: function() {
  3249. var sourceOffset;
  3250. var origin;
  3251. this.getEl(); // ensure this.el
  3252. // make sure origin info was computed
  3253. if (this.top0 === null) {
  3254. sourceOffset = this.sourceEl.offset();
  3255. origin = this.el.offsetParent().offset();
  3256. this.top0 = sourceOffset.top - origin.top;
  3257. this.left0 = sourceOffset.left - origin.left;
  3258. }
  3259. this.el.css({
  3260. top: this.top0 + this.topDelta,
  3261. left: this.left0 + this.leftDelta
  3262. });
  3263. },
  3264. // Gets called when the user moves the mouse
  3265. handleMove: function(ev) {
  3266. this.topDelta = getEvY(ev) - this.y0;
  3267. this.leftDelta = getEvX(ev) - this.x0;
  3268. if (!this.isHidden) {
  3269. this.updatePosition();
  3270. }
  3271. },
  3272. // Temporarily makes the tracking element invisible. Can be called before following starts
  3273. hide: function() {
  3274. if (!this.isHidden) {
  3275. this.isHidden = true;
  3276. if (this.el) {
  3277. this.el.hide();
  3278. }
  3279. }
  3280. },
  3281. // Show the tracking element after it has been temporarily hidden
  3282. show: function() {
  3283. if (this.isHidden) {
  3284. this.isHidden = false;
  3285. this.updatePosition();
  3286. this.getEl().show();
  3287. }
  3288. }
  3289. });
  3290. ;;
  3291. /* An abstract class comprised of a "grid" of areas that each represent a specific datetime
  3292. ----------------------------------------------------------------------------------------------------------------------*/
  3293. var Grid = FC.Grid = Class.extend(ListenerMixin, {
  3294. // self-config, overridable by subclasses
  3295. hasDayInteractions: true, // can user click/select ranges of time?
  3296. view: null, // a View object
  3297. isRTL: null, // shortcut to the view's isRTL option
  3298. start: null,
  3299. end: null,
  3300. el: null, // the containing element
  3301. elsByFill: null, // a hash of jQuery element sets used for rendering each fill. Keyed by fill name.
  3302. // derived from options
  3303. eventTimeFormat: null,
  3304. displayEventTime: null,
  3305. displayEventEnd: null,
  3306. minResizeDuration: null, // TODO: hack. set by subclasses. minumum event resize duration
  3307. // if defined, holds the unit identified (ex: "year" or "month") that determines the level of granularity
  3308. // of the date areas. if not defined, assumes to be day and time granularity.
  3309. // TODO: port isTimeScale into same system?
  3310. largeUnit: null,
  3311. dayClickListener: null,
  3312. daySelectListener: null,
  3313. segDragListener: null,
  3314. segResizeListener: null,
  3315. externalDragListener: null,
  3316. constructor: function(view) {
  3317. this.view = view;
  3318. this.isRTL = view.opt('isRTL');
  3319. this.elsByFill = {};
  3320. this.dayClickListener = this.buildDayClickListener();
  3321. this.daySelectListener = this.buildDaySelectListener();
  3322. },
  3323. /* Options
  3324. ------------------------------------------------------------------------------------------------------------------*/
  3325. // Generates the format string used for event time text, if not explicitly defined by 'timeFormat'
  3326. computeEventTimeFormat: function() {
  3327. return this.view.opt('smallTimeFormat');
  3328. },
  3329. // Determines whether events should have their end times displayed, if not explicitly defined by 'displayEventTime'.
  3330. // Only applies to non-all-day events.
  3331. computeDisplayEventTime: function() {
  3332. return true;
  3333. },
  3334. // Determines whether events should have their end times displayed, if not explicitly defined by 'displayEventEnd'
  3335. computeDisplayEventEnd: function() {
  3336. return true;
  3337. },
  3338. /* Dates
  3339. ------------------------------------------------------------------------------------------------------------------*/
  3340. // Tells the grid about what period of time to display.
  3341. // Any date-related internal data should be generated.
  3342. setRange: function(range) {
  3343. this.start = range.start.clone();
  3344. this.end = range.end.clone();
  3345. this.rangeUpdated();
  3346. this.processRangeOptions();
  3347. },
  3348. // Called when internal variables that rely on the range should be updated
  3349. rangeUpdated: function() {
  3350. },
  3351. // Updates values that rely on options and also relate to range
  3352. processRangeOptions: function() {
  3353. var view = this.view;
  3354. var displayEventTime;
  3355. var displayEventEnd;
  3356. this.eventTimeFormat =
  3357. view.opt('eventTimeFormat') ||
  3358. view.opt('timeFormat') || // deprecated
  3359. this.computeEventTimeFormat();
  3360. displayEventTime = view.opt('displayEventTime');
  3361. if (displayEventTime == null) {
  3362. displayEventTime = this.computeDisplayEventTime(); // might be based off of range
  3363. }
  3364. displayEventEnd = view.opt('displayEventEnd');
  3365. if (displayEventEnd == null) {
  3366. displayEventEnd = this.computeDisplayEventEnd(); // might be based off of range
  3367. }
  3368. this.displayEventTime = displayEventTime;
  3369. this.displayEventEnd = displayEventEnd;
  3370. },
  3371. // Converts a span (has unzoned start/end and any other grid-specific location information)
  3372. // into an array of segments (pieces of events whose format is decided by the grid).
  3373. spanToSegs: function(span) {
  3374. // subclasses must implement
  3375. },
  3376. // Diffs the two dates, returning a duration, based on granularity of the grid
  3377. // TODO: port isTimeScale into this system?
  3378. diffDates: function(a, b) {
  3379. if (this.largeUnit) {
  3380. return diffByUnit(a, b, this.largeUnit);
  3381. }
  3382. else {
  3383. return diffDayTime(a, b);
  3384. }
  3385. },
  3386. /* Hit Area
  3387. ------------------------------------------------------------------------------------------------------------------*/
  3388. hitsNeededDepth: 0, // necessary because multiple callers might need the same hits
  3389. hitsNeeded: function() {
  3390. if (!(this.hitsNeededDepth++)) {
  3391. this.prepareHits();
  3392. }
  3393. },
  3394. hitsNotNeeded: function() {
  3395. if (this.hitsNeededDepth && !(--this.hitsNeededDepth)) {
  3396. this.releaseHits();
  3397. }
  3398. },
  3399. // Called before one or more queryHit calls might happen. Should prepare any cached coordinates for queryHit
  3400. prepareHits: function() {
  3401. },
  3402. // Called when queryHit calls have subsided. Good place to clear any coordinate caches.
  3403. releaseHits: function() {
  3404. },
  3405. // Given coordinates from the topleft of the document, return data about the date-related area underneath.
  3406. // Can return an object with arbitrary properties (although top/right/left/bottom are encouraged).
  3407. // Must have a `grid` property, a reference to this current grid. TODO: avoid this
  3408. // The returned object will be processed by getHitSpan and getHitEl.
  3409. queryHit: function(leftOffset, topOffset) {
  3410. },
  3411. // like getHitSpan, but returns null if the resulting span's range is invalid
  3412. getSafeHitSpan: function(hit) {
  3413. var hitSpan = this.getHitSpan(hit);
  3414. if (!isRangeWithinRange(hitSpan, this.view.activeRange)) {
  3415. return null;
  3416. }
  3417. return hitSpan;
  3418. },
  3419. // Given position-level information about a date-related area within the grid,
  3420. // should return an object with at least a start/end date. Can provide other information as well.
  3421. getHitSpan: function(hit) {
  3422. },
  3423. // Given position-level information about a date-related area within the grid,
  3424. // should return a jQuery element that best represents it. passed to dayClick callback.
  3425. getHitEl: function(hit) {
  3426. },
  3427. /* Rendering
  3428. ------------------------------------------------------------------------------------------------------------------*/
  3429. // Sets the container element that the grid should render inside of.
  3430. // Does other DOM-related initializations.
  3431. setElement: function(el) {
  3432. this.el = el;
  3433. if (this.hasDayInteractions) {
  3434. preventSelection(el);
  3435. this.bindDayHandler('touchstart', this.dayTouchStart);
  3436. this.bindDayHandler('mousedown', this.dayMousedown);
  3437. }
  3438. // attach event-element-related handlers. in Grid.events
  3439. // same garbage collection note as above.
  3440. this.bindSegHandlers();
  3441. this.bindGlobalHandlers();
  3442. },
  3443. bindDayHandler: function(name, handler) {
  3444. var _this = this;
  3445. // attach a handler to the grid's root element.
  3446. // jQuery will take care of unregistering them when removeElement gets called.
  3447. this.el.on(name, function(ev) {
  3448. if (
  3449. !$(ev.target).is(
  3450. _this.segSelector + ',' + // directly on an event element
  3451. _this.segSelector + ' *,' + // within an event element
  3452. '.fc-more,' + // a "more.." link
  3453. 'a[data-goto]' // a clickable nav link
  3454. )
  3455. ) {
  3456. return handler.call(_this, ev);
  3457. }
  3458. });
  3459. },
  3460. // Removes the grid's container element from the DOM. Undoes any other DOM-related attachments.
  3461. // DOES NOT remove any content beforehand (doesn't clear events or call unrenderDates), unlike View
  3462. removeElement: function() {
  3463. this.unbindGlobalHandlers();
  3464. this.clearDragListeners();
  3465. this.el.remove();
  3466. // NOTE: we don't null-out this.el for the same reasons we don't do it within View::removeElement
  3467. },
  3468. // Renders the basic structure of grid view before any content is rendered
  3469. renderSkeleton: function() {
  3470. // subclasses should implement
  3471. },
  3472. // Renders the grid's date-related content (like areas that represent days/times).
  3473. // Assumes setRange has already been called and the skeleton has already been rendered.
  3474. renderDates: function() {
  3475. // subclasses should implement
  3476. },
  3477. // Unrenders the grid's date-related content
  3478. unrenderDates: function() {
  3479. // subclasses should implement
  3480. },
  3481. /* Handlers
  3482. ------------------------------------------------------------------------------------------------------------------*/
  3483. // Binds DOM handlers to elements that reside outside the grid, such as the document
  3484. bindGlobalHandlers: function() {
  3485. this.listenTo($(document), {
  3486. dragstart: this.externalDragStart, // jqui
  3487. sortstart: this.externalDragStart // jqui
  3488. });
  3489. },
  3490. // Unbinds DOM handlers from elements that reside outside the grid
  3491. unbindGlobalHandlers: function() {
  3492. this.stopListeningTo($(document));
  3493. },
  3494. // Process a mousedown on an element that represents a day. For day clicking and selecting.
  3495. dayMousedown: function(ev) {
  3496. var view = this.view;
  3497. // HACK
  3498. // This will still work even though bindDayHandler doesn't use GlobalEmitter.
  3499. if (GlobalEmitter.get().shouldIgnoreMouse()) {
  3500. return;
  3501. }
  3502. this.dayClickListener.startInteraction(ev);
  3503. if (view.opt('selectable')) {
  3504. this.daySelectListener.startInteraction(ev, {
  3505. distance: view.opt('selectMinDistance')
  3506. });
  3507. }
  3508. },
  3509. dayTouchStart: function(ev) {
  3510. var view = this.view;
  3511. var selectLongPressDelay;
  3512. // On iOS (and Android?) when a new selection is initiated overtop another selection,
  3513. // the touchend never fires because the elements gets removed mid-touch-interaction (my theory).
  3514. // HACK: simply don't allow this to happen.
  3515. // ALSO: prevent selection when an *event* is already raised.
  3516. if (view.isSelected || view.selectedEvent) {
  3517. return;
  3518. }
  3519. selectLongPressDelay = view.opt('selectLongPressDelay');
  3520. if (selectLongPressDelay == null) {
  3521. selectLongPressDelay = view.opt('longPressDelay'); // fallback
  3522. }
  3523. this.dayClickListener.startInteraction(ev);
  3524. if (view.opt('selectable')) {
  3525. this.daySelectListener.startInteraction(ev, {
  3526. delay: selectLongPressDelay
  3527. });
  3528. }
  3529. },
  3530. // Creates a listener that tracks the user's drag across day elements, for day clicking.
  3531. buildDayClickListener: function() {
  3532. var _this = this;
  3533. var view = this.view;
  3534. var dayClickHit; // null if invalid dayClick
  3535. var dragListener = new HitDragListener(this, {
  3536. scroll: view.opt('dragScroll'),
  3537. interactionStart: function() {
  3538. dayClickHit = dragListener.origHit;
  3539. },
  3540. hitOver: function(hit, isOrig, origHit) {
  3541. // if user dragged to another cell at any point, it can no longer be a dayClick
  3542. if (!isOrig) {
  3543. dayClickHit = null;
  3544. }
  3545. },
  3546. hitOut: function() { // called before mouse moves to a different hit OR moved out of all hits
  3547. dayClickHit = null;
  3548. },
  3549. interactionEnd: function(ev, isCancelled) {
  3550. var hitSpan;
  3551. if (!isCancelled && dayClickHit) {
  3552. hitSpan = _this.getSafeHitSpan(dayClickHit);
  3553. if (hitSpan) {
  3554. view.triggerDayClick(hitSpan, _this.getHitEl(dayClickHit), ev);
  3555. }
  3556. }
  3557. }
  3558. });
  3559. // because dayClickListener won't be called with any time delay, "dragging" will begin immediately,
  3560. // which will kill any touchmoving/scrolling. Prevent this.
  3561. dragListener.shouldCancelTouchScroll = false;
  3562. dragListener.scrollAlwaysKills = true;
  3563. return dragListener;
  3564. },
  3565. // Creates a listener that tracks the user's drag across day elements, for day selecting.
  3566. buildDaySelectListener: function() {
  3567. var _this = this;
  3568. var view = this.view;
  3569. var selectionSpan; // null if invalid selection
  3570. var dragListener = new HitDragListener(this, {
  3571. scroll: view.opt('dragScroll'),
  3572. interactionStart: function() {
  3573. selectionSpan = null;
  3574. },
  3575. dragStart: function() {
  3576. view.unselect(); // since we could be rendering a new selection, we want to clear any old one
  3577. },
  3578. hitOver: function(hit, isOrig, origHit) {
  3579. var origHitSpan;
  3580. var hitSpan;
  3581. if (origHit) { // click needs to have started on a hit
  3582. origHitSpan = _this.getSafeHitSpan(origHit);
  3583. hitSpan = _this.getSafeHitSpan(hit);
  3584. if (origHitSpan && hitSpan) {
  3585. selectionSpan = _this.computeSelection(origHitSpan, hitSpan);
  3586. }
  3587. else {
  3588. selectionSpan = null;
  3589. }
  3590. if (selectionSpan) {
  3591. _this.renderSelection(selectionSpan);
  3592. }
  3593. else if (selectionSpan === false) {
  3594. disableCursor();
  3595. }
  3596. }
  3597. },
  3598. hitOut: function() { // called before mouse moves to a different hit OR moved out of all hits
  3599. selectionSpan = null;
  3600. _this.unrenderSelection();
  3601. },
  3602. hitDone: function() { // called after a hitOut OR before a dragEnd
  3603. enableCursor();
  3604. },
  3605. interactionEnd: function(ev, isCancelled) {
  3606. if (!isCancelled && selectionSpan) {
  3607. // the selection will already have been rendered. just report it
  3608. view.reportSelection(selectionSpan, ev);
  3609. }
  3610. }
  3611. });
  3612. return dragListener;
  3613. },
  3614. // Kills all in-progress dragging.
  3615. // Useful for when public API methods that result in re-rendering are invoked during a drag.
  3616. // Also useful for when touch devices misbehave and don't fire their touchend.
  3617. clearDragListeners: function() {
  3618. this.dayClickListener.endInteraction();
  3619. this.daySelectListener.endInteraction();
  3620. if (this.segDragListener) {
  3621. this.segDragListener.endInteraction(); // will clear this.segDragListener
  3622. }
  3623. if (this.segResizeListener) {
  3624. this.segResizeListener.endInteraction(); // will clear this.segResizeListener
  3625. }
  3626. if (this.externalDragListener) {
  3627. this.externalDragListener.endInteraction(); // will clear this.externalDragListener
  3628. }
  3629. },
  3630. /* Event Helper
  3631. ------------------------------------------------------------------------------------------------------------------*/
  3632. // TODO: should probably move this to Grid.events, like we did event dragging / resizing
  3633. // Renders a mock event at the given event location, which contains zoned start/end properties.
  3634. // Returns all mock event elements.
  3635. renderEventLocationHelper: function(eventLocation, sourceSeg) {
  3636. var fakeEvent = this.fabricateHelperEvent(eventLocation, sourceSeg);
  3637. return this.renderHelper(fakeEvent, sourceSeg); // do the actual rendering
  3638. },
  3639. // Builds a fake event given zoned event date properties and a segment is should be inspired from.
  3640. // The range's end can be null, in which case the mock event that is rendered will have a null end time.
  3641. // `sourceSeg` is the internal segment object involved in the drag. If null, something external is dragging.
  3642. fabricateHelperEvent: function(eventLocation, sourceSeg) {
  3643. var fakeEvent = sourceSeg ? createObject(sourceSeg.event) : {}; // mask the original event object if possible
  3644. fakeEvent.start = eventLocation.start.clone();
  3645. fakeEvent.end = eventLocation.end ? eventLocation.end.clone() : null;
  3646. fakeEvent.allDay = null; // force it to be freshly computed by normalizeEventDates
  3647. this.view.calendar.normalizeEventDates(fakeEvent);
  3648. // this extra className will be useful for differentiating real events from mock events in CSS
  3649. fakeEvent.className = (fakeEvent.className || []).concat('fc-helper');
  3650. // if something external is being dragged in, don't render a resizer
  3651. if (!sourceSeg) {
  3652. fakeEvent.editable = false;
  3653. }
  3654. return fakeEvent;
  3655. },
  3656. // Renders a mock event. Given zoned event date properties.
  3657. // Must return all mock event elements.
  3658. renderHelper: function(eventLocation, sourceSeg) {
  3659. // subclasses must implement
  3660. },
  3661. // Unrenders a mock event
  3662. unrenderHelper: function() {
  3663. // subclasses must implement
  3664. },
  3665. /* Selection
  3666. ------------------------------------------------------------------------------------------------------------------*/
  3667. // Renders a visual indication of a selection. Will highlight by default but can be overridden by subclasses.
  3668. // Given a span (unzoned start/end and other misc data)
  3669. renderSelection: function(span) {
  3670. this.renderHighlight(span);
  3671. },
  3672. // Unrenders any visual indications of a selection. Will unrender a highlight by default.
  3673. unrenderSelection: function() {
  3674. this.unrenderHighlight();
  3675. },
  3676. // Given the first and last date-spans of a selection, returns another date-span object.
  3677. // Subclasses can override and provide additional data in the span object. Will be passed to renderSelection().
  3678. // Will return false if the selection is invalid and this should be indicated to the user.
  3679. // Will return null/undefined if a selection invalid but no error should be reported.
  3680. computeSelection: function(span0, span1) {
  3681. var span = this.computeSelectionSpan(span0, span1);
  3682. if (span && !this.view.calendar.isSelectionSpanAllowed(span)) {
  3683. return false;
  3684. }
  3685. return span;
  3686. },
  3687. // Given two spans, must return the combination of the two.
  3688. // TODO: do this separation of concerns (combining VS validation) for event dnd/resize too.
  3689. computeSelectionSpan: function(span0, span1) {
  3690. var dates = [ span0.start, span0.end, span1.start, span1.end ];
  3691. dates.sort(compareNumbers); // sorts chronologically. works with Moments
  3692. return { start: dates[0].clone(), end: dates[3].clone() };
  3693. },
  3694. /* Highlight
  3695. ------------------------------------------------------------------------------------------------------------------*/
  3696. // Renders an emphasis on the given date range. Given a span (unzoned start/end and other misc data)
  3697. renderHighlight: function(span) {
  3698. this.renderFill('highlight', this.spanToSegs(span));
  3699. },
  3700. // Unrenders the emphasis on a date range
  3701. unrenderHighlight: function() {
  3702. this.unrenderFill('highlight');
  3703. },
  3704. // Generates an array of classNames for rendering the highlight. Used by the fill system.
  3705. highlightSegClasses: function() {
  3706. return [ 'fc-highlight' ];
  3707. },
  3708. /* Business Hours
  3709. ------------------------------------------------------------------------------------------------------------------*/
  3710. renderBusinessHours: function() {
  3711. },
  3712. unrenderBusinessHours: function() {
  3713. },
  3714. /* Now Indicator
  3715. ------------------------------------------------------------------------------------------------------------------*/
  3716. getNowIndicatorUnit: function() {
  3717. },
  3718. renderNowIndicator: function(date) {
  3719. },
  3720. unrenderNowIndicator: function() {
  3721. },
  3722. /* Fill System (highlight, background events, business hours)
  3723. --------------------------------------------------------------------------------------------------------------------
  3724. TODO: remove this system. like we did in TimeGrid
  3725. */
  3726. // Renders a set of rectangles over the given segments of time.
  3727. // MUST RETURN a subset of segs, the segs that were actually rendered.
  3728. // Responsible for populating this.elsByFill. TODO: better API for expressing this requirement
  3729. renderFill: function(type, segs) {
  3730. // subclasses must implement
  3731. },
  3732. // Unrenders a specific type of fill that is currently rendered on the grid
  3733. unrenderFill: function(type) {
  3734. var el = this.elsByFill[type];
  3735. if (el) {
  3736. el.remove();
  3737. delete this.elsByFill[type];
  3738. }
  3739. },
  3740. // Renders and assigns an `el` property for each fill segment. Generic enough to work with different types.
  3741. // Only returns segments that successfully rendered.
  3742. // To be harnessed by renderFill (implemented by subclasses).
  3743. // Analagous to renderFgSegEls.
  3744. renderFillSegEls: function(type, segs) {
  3745. var _this = this;
  3746. var segElMethod = this[type + 'SegEl'];
  3747. var html = '';
  3748. var renderedSegs = [];
  3749. var i;
  3750. if (segs.length) {
  3751. // build a large concatenation of segment HTML
  3752. for (i = 0; i < segs.length; i++) {
  3753. html += this.fillSegHtml(type, segs[i]);
  3754. }
  3755. // Grab individual elements from the combined HTML string. Use each as the default rendering.
  3756. // Then, compute the 'el' for each segment.
  3757. $(html).each(function(i, node) {
  3758. var seg = segs[i];
  3759. var el = $(node);
  3760. // allow custom filter methods per-type
  3761. if (segElMethod) {
  3762. el = segElMethod.call(_this, seg, el);
  3763. }
  3764. if (el) { // custom filters did not cancel the render
  3765. el = $(el); // allow custom filter to return raw DOM node
  3766. // correct element type? (would be bad if a non-TD were inserted into a table for example)
  3767. if (el.is(_this.fillSegTag)) {
  3768. seg.el = el;
  3769. renderedSegs.push(seg);
  3770. }
  3771. }
  3772. });
  3773. }
  3774. return renderedSegs;
  3775. },
  3776. fillSegTag: 'div', // subclasses can override
  3777. // Builds the HTML needed for one fill segment. Generic enough to work with different types.
  3778. fillSegHtml: function(type, seg) {
  3779. // custom hooks per-type
  3780. var classesMethod = this[type + 'SegClasses'];
  3781. var cssMethod = this[type + 'SegCss'];
  3782. var classes = classesMethod ? classesMethod.call(this, seg) : [];
  3783. var css = cssToStr(cssMethod ? cssMethod.call(this, seg) : {});
  3784. return '<' + this.fillSegTag +
  3785. (classes.length ? ' class="' + classes.join(' ') + '"' : '') +
  3786. (css ? ' style="' + css + '"' : '') +
  3787. ' />';
  3788. },
  3789. /* Generic rendering utilities for subclasses
  3790. ------------------------------------------------------------------------------------------------------------------*/
  3791. // Computes HTML classNames for a single-day element
  3792. getDayClasses: function(date, noThemeHighlight) {
  3793. var view = this.view;
  3794. var classes = [];
  3795. var today;
  3796. if (!isDateWithinRange(date, view.activeRange)) {
  3797. classes.push('fc-disabled-day'); // TODO: jQuery UI theme?
  3798. }
  3799. else {
  3800. classes.push('fc-' + dayIDs[date.day()]);
  3801. if (
  3802. view.currentRangeAs('months') == 1 && // TODO: somehow get into MonthView
  3803. date.month() != view.currentRange.start.month()
  3804. ) {
  3805. classes.push('fc-other-month');
  3806. }
  3807. today = view.calendar.getNow();
  3808. if (date.isSame(today, 'day')) {
  3809. classes.push('fc-today');
  3810. if (noThemeHighlight !== true) {
  3811. classes.push(view.highlightStateClass);
  3812. }
  3813. }
  3814. else if (date < today) {
  3815. classes.push('fc-past');
  3816. }
  3817. else {
  3818. classes.push('fc-future');
  3819. }
  3820. }
  3821. return classes;
  3822. }
  3823. });
  3824. ;;
  3825. /* Event-rendering and event-interaction methods for the abstract Grid class
  3826. ----------------------------------------------------------------------------------------------------------------------
  3827. Data Types:
  3828. event - { title, id, start, (end), whatever }
  3829. location - { start, (end), allDay }
  3830. rawEventRange - { start, end }
  3831. eventRange - { start, end, isStart, isEnd }
  3832. eventSpan - { start, end, isStart, isEnd, whatever }
  3833. eventSeg - { event, whatever }
  3834. seg - { whatever }
  3835. */
  3836. Grid.mixin({
  3837. // self-config, overridable by subclasses
  3838. segSelector: '.fc-event-container > *', // what constitutes an event element?
  3839. mousedOverSeg: null, // the segment object the user's mouse is over. null if over nothing
  3840. isDraggingSeg: false, // is a segment being dragged? boolean
  3841. isResizingSeg: false, // is a segment being resized? boolean
  3842. isDraggingExternal: false, // jqui-dragging an external element? boolean
  3843. segs: null, // the *event* segments currently rendered in the grid. TODO: rename to `eventSegs`
  3844. // Renders the given events onto the grid
  3845. renderEvents: function(events) {
  3846. var bgEvents = [];
  3847. var fgEvents = [];
  3848. var i;
  3849. for (i = 0; i < events.length; i++) {
  3850. (isBgEvent(events[i]) ? bgEvents : fgEvents).push(events[i]);
  3851. }
  3852. this.segs = [].concat( // record all segs
  3853. this.renderBgEvents(bgEvents),
  3854. this.renderFgEvents(fgEvents)
  3855. );
  3856. },
  3857. renderBgEvents: function(events) {
  3858. var segs = this.eventsToSegs(events);
  3859. // renderBgSegs might return a subset of segs, segs that were actually rendered
  3860. return this.renderBgSegs(segs) || segs;
  3861. },
  3862. renderFgEvents: function(events) {
  3863. var segs = this.eventsToSegs(events);
  3864. // renderFgSegs might return a subset of segs, segs that were actually rendered
  3865. return this.renderFgSegs(segs) || segs;
  3866. },
  3867. // Unrenders all events currently rendered on the grid
  3868. unrenderEvents: function() {
  3869. this.handleSegMouseout(); // trigger an eventMouseout if user's mouse is over an event
  3870. this.clearDragListeners();
  3871. this.unrenderFgSegs();
  3872. this.unrenderBgSegs();
  3873. this.segs = null;
  3874. },
  3875. // Retrieves all rendered segment objects currently rendered on the grid
  3876. getEventSegs: function() {
  3877. return this.segs || [];
  3878. },
  3879. /* Foreground Segment Rendering
  3880. ------------------------------------------------------------------------------------------------------------------*/
  3881. // Renders foreground event segments onto the grid. May return a subset of segs that were rendered.
  3882. renderFgSegs: function(segs) {
  3883. // subclasses must implement
  3884. },
  3885. // Unrenders all currently rendered foreground segments
  3886. unrenderFgSegs: function() {
  3887. // subclasses must implement
  3888. },
  3889. // Renders and assigns an `el` property for each foreground event segment.
  3890. // Only returns segments that successfully rendered.
  3891. // A utility that subclasses may use.
  3892. renderFgSegEls: function(segs, disableResizing) {
  3893. var view = this.view;
  3894. var html = '';
  3895. var renderedSegs = [];
  3896. var i;
  3897. if (segs.length) { // don't build an empty html string
  3898. // build a large concatenation of event segment HTML
  3899. for (i = 0; i < segs.length; i++) {
  3900. html += this.fgSegHtml(segs[i], disableResizing);
  3901. }
  3902. // Grab individual elements from the combined HTML string. Use each as the default rendering.
  3903. // Then, compute the 'el' for each segment. An el might be null if the eventRender callback returned false.
  3904. $(html).each(function(i, node) {
  3905. var seg = segs[i];
  3906. var el = view.resolveEventEl(seg.event, $(node));
  3907. if (el) {
  3908. el.data('fc-seg', seg); // used by handlers
  3909. seg.el = el;
  3910. renderedSegs.push(seg);
  3911. }
  3912. });
  3913. }
  3914. return renderedSegs;
  3915. },
  3916. // Generates the HTML for the default rendering of a foreground event segment. Used by renderFgSegEls()
  3917. fgSegHtml: function(seg, disableResizing) {
  3918. // subclasses should implement
  3919. },
  3920. /* Background Segment Rendering
  3921. ------------------------------------------------------------------------------------------------------------------*/
  3922. // Renders the given background event segments onto the grid.
  3923. // Returns a subset of the segs that were actually rendered.
  3924. renderBgSegs: function(segs) {
  3925. return this.renderFill('bgEvent', segs);
  3926. },
  3927. // Unrenders all the currently rendered background event segments
  3928. unrenderBgSegs: function() {
  3929. this.unrenderFill('bgEvent');
  3930. },
  3931. // Renders a background event element, given the default rendering. Called by the fill system.
  3932. bgEventSegEl: function(seg, el) {
  3933. return this.view.resolveEventEl(seg.event, el); // will filter through eventRender
  3934. },
  3935. // Generates an array of classNames to be used for the default rendering of a background event.
  3936. // Called by fillSegHtml.
  3937. bgEventSegClasses: function(seg) {
  3938. var event = seg.event;
  3939. var source = event.source || {};
  3940. return [ 'fc-bgevent' ].concat(
  3941. event.className,
  3942. source.className || []
  3943. );
  3944. },
  3945. // Generates a semicolon-separated CSS string to be used for the default rendering of a background event.
  3946. // Called by fillSegHtml.
  3947. bgEventSegCss: function(seg) {
  3948. return {
  3949. 'background-color': this.getSegSkinCss(seg)['background-color']
  3950. };
  3951. },
  3952. // Generates an array of classNames to be used for the rendering business hours overlay. Called by the fill system.
  3953. // Called by fillSegHtml.
  3954. businessHoursSegClasses: function(seg) {
  3955. return [ 'fc-nonbusiness', 'fc-bgevent' ];
  3956. },
  3957. /* Business Hours
  3958. ------------------------------------------------------------------------------------------------------------------*/
  3959. // Compute business hour segs for the grid's current date range.
  3960. // Caller must ask if whole-day business hours are needed.
  3961. // If no `businessHours` configuration value is specified, assumes the calendar default.
  3962. buildBusinessHourSegs: function(wholeDay, businessHours) {
  3963. return this.eventsToSegs(
  3964. this.buildBusinessHourEvents(wholeDay, businessHours)
  3965. );
  3966. },
  3967. // Compute business hour *events* for the grid's current date range.
  3968. // Caller must ask if whole-day business hours are needed.
  3969. // If no `businessHours` configuration value is specified, assumes the calendar default.
  3970. buildBusinessHourEvents: function(wholeDay, businessHours) {
  3971. var calendar = this.view.calendar;
  3972. var events;
  3973. if (businessHours == null) {
  3974. // fallback
  3975. // access from calendawr. don't access from view. doesn't update with dynamic options.
  3976. businessHours = calendar.opt('businessHours');
  3977. }
  3978. events = calendar.computeBusinessHourEvents(wholeDay, businessHours);
  3979. // HACK. Eventually refactor business hours "events" system.
  3980. // If no events are given, but businessHours is activated, this means the entire visible range should be
  3981. // marked as *not* business-hours, via inverse-background rendering.
  3982. if (!events.length && businessHours) {
  3983. events = [
  3984. $.extend({}, BUSINESS_HOUR_EVENT_DEFAULTS, {
  3985. start: this.view.activeRange.end, // guaranteed out-of-range
  3986. end: this.view.activeRange.end, // "
  3987. dow: null
  3988. })
  3989. ];
  3990. }
  3991. return events;
  3992. },
  3993. /* Handlers
  3994. ------------------------------------------------------------------------------------------------------------------*/
  3995. // Attaches event-element-related handlers for *all* rendered event segments of the view.
  3996. bindSegHandlers: function() {
  3997. this.bindSegHandlersToEl(this.el);
  3998. },
  3999. // Attaches event-element-related handlers to an arbitrary container element. leverages bubbling.
  4000. bindSegHandlersToEl: function(el) {
  4001. this.bindSegHandlerToEl(el, 'touchstart', this.handleSegTouchStart);
  4002. this.bindSegHandlerToEl(el, 'mouseenter', this.handleSegMouseover);
  4003. this.bindSegHandlerToEl(el, 'mouseleave', this.handleSegMouseout);
  4004. this.bindSegHandlerToEl(el, 'mousedown', this.handleSegMousedown);
  4005. this.bindSegHandlerToEl(el, 'click', this.handleSegClick);
  4006. },
  4007. // Executes a handler for any a user-interaction on a segment.
  4008. // Handler gets called with (seg, ev), and with the `this` context of the Grid
  4009. bindSegHandlerToEl: function(el, name, handler) {
  4010. var _this = this;
  4011. el.on(name, this.segSelector, function(ev) {
  4012. var seg = $(this).data('fc-seg'); // grab segment data. put there by View::renderEvents
  4013. // only call the handlers if there is not a drag/resize in progress
  4014. if (seg && !_this.isDraggingSeg && !_this.isResizingSeg) {
  4015. return handler.call(_this, seg, ev); // context will be the Grid
  4016. }
  4017. });
  4018. },
  4019. handleSegClick: function(seg, ev) {
  4020. var res = this.view.publiclyTrigger('eventClick', seg.el[0], seg.event, ev); // can return `false` to cancel
  4021. if (res === false) {
  4022. ev.preventDefault();
  4023. }
  4024. },
  4025. // Updates internal state and triggers handlers for when an event element is moused over
  4026. handleSegMouseover: function(seg, ev) {
  4027. if (
  4028. !GlobalEmitter.get().shouldIgnoreMouse() &&
  4029. !this.mousedOverSeg
  4030. ) {
  4031. this.mousedOverSeg = seg;
  4032. if (this.view.isEventResizable(seg.event)) {
  4033. seg.el.addClass('fc-allow-mouse-resize');
  4034. }
  4035. this.view.publiclyTrigger('eventMouseover', seg.el[0], seg.event, ev);
  4036. }
  4037. },
  4038. // Updates internal state and triggers handlers for when an event element is moused out.
  4039. // Can be given no arguments, in which case it will mouseout the segment that was previously moused over.
  4040. handleSegMouseout: function(seg, ev) {
  4041. ev = ev || {}; // if given no args, make a mock mouse event
  4042. if (this.mousedOverSeg) {
  4043. seg = seg || this.mousedOverSeg; // if given no args, use the currently moused-over segment
  4044. this.mousedOverSeg = null;
  4045. if (this.view.isEventResizable(seg.event)) {
  4046. seg.el.removeClass('fc-allow-mouse-resize');
  4047. }
  4048. this.view.publiclyTrigger('eventMouseout', seg.el[0], seg.event, ev);
  4049. }
  4050. },
  4051. handleSegMousedown: function(seg, ev) {
  4052. var isResizing = this.startSegResize(seg, ev, { distance: 5 });
  4053. if (!isResizing && this.view.isEventDraggable(seg.event)) {
  4054. this.buildSegDragListener(seg)
  4055. .startInteraction(ev, {
  4056. distance: 5
  4057. });
  4058. }
  4059. },
  4060. handleSegTouchStart: function(seg, ev) {
  4061. var view = this.view;
  4062. var event = seg.event;
  4063. var isSelected = view.isEventSelected(event);
  4064. var isDraggable = view.isEventDraggable(event);
  4065. var isResizable = view.isEventResizable(event);
  4066. var isResizing = false;
  4067. var dragListener;
  4068. var eventLongPressDelay;
  4069. if (isSelected && isResizable) {
  4070. // only allow resizing of the event is selected
  4071. isResizing = this.startSegResize(seg, ev);
  4072. }
  4073. if (!isResizing && (isDraggable || isResizable)) { // allowed to be selected?
  4074. eventLongPressDelay = view.opt('eventLongPressDelay');
  4075. if (eventLongPressDelay == null) {
  4076. eventLongPressDelay = view.opt('longPressDelay'); // fallback
  4077. }
  4078. dragListener = isDraggable ?
  4079. this.buildSegDragListener(seg) :
  4080. this.buildSegSelectListener(seg); // seg isn't draggable, but still needs to be selected
  4081. dragListener.startInteraction(ev, { // won't start if already started
  4082. delay: isSelected ? 0 : eventLongPressDelay // do delay if not already selected
  4083. });
  4084. }
  4085. },
  4086. // returns boolean whether resizing actually started or not.
  4087. // assumes the seg allows resizing.
  4088. // `dragOptions` are optional.
  4089. startSegResize: function(seg, ev, dragOptions) {
  4090. if ($(ev.target).is('.fc-resizer')) {
  4091. this.buildSegResizeListener(seg, $(ev.target).is('.fc-start-resizer'))
  4092. .startInteraction(ev, dragOptions);
  4093. return true;
  4094. }
  4095. return false;
  4096. },
  4097. /* Event Dragging
  4098. ------------------------------------------------------------------------------------------------------------------*/
  4099. // Builds a listener that will track user-dragging on an event segment.
  4100. // Generic enough to work with any type of Grid.
  4101. // Has side effect of setting/unsetting `segDragListener`
  4102. buildSegDragListener: function(seg) {
  4103. var _this = this;
  4104. var view = this.view;
  4105. var el = seg.el;
  4106. var event = seg.event;
  4107. var isDragging;
  4108. var mouseFollower; // A clone of the original element that will move with the mouse
  4109. var dropLocation; // zoned event date properties
  4110. if (this.segDragListener) {
  4111. return this.segDragListener;
  4112. }
  4113. // Tracks mouse movement over the *view's* coordinate map. Allows dragging and dropping between subcomponents
  4114. // of the view.
  4115. var dragListener = this.segDragListener = new HitDragListener(view, {
  4116. scroll: view.opt('dragScroll'),
  4117. subjectEl: el,
  4118. subjectCenter: true,
  4119. interactionStart: function(ev) {
  4120. seg.component = _this; // for renderDrag
  4121. isDragging = false;
  4122. mouseFollower = new MouseFollower(seg.el, {
  4123. additionalClass: 'fc-dragging',
  4124. parentEl: view.el,
  4125. opacity: dragListener.isTouch ? null : view.opt('dragOpacity'),
  4126. revertDuration: view.opt('dragRevertDuration'),
  4127. zIndex: 2 // one above the .fc-view
  4128. });
  4129. mouseFollower.hide(); // don't show until we know this is a real drag
  4130. mouseFollower.start(ev);
  4131. },
  4132. dragStart: function(ev) {
  4133. if (dragListener.isTouch && !view.isEventSelected(event)) {
  4134. // if not previously selected, will fire after a delay. then, select the event
  4135. view.selectEvent(event);
  4136. }
  4137. isDragging = true;
  4138. _this.handleSegMouseout(seg, ev); // ensure a mouseout on the manipulated event has been reported
  4139. _this.segDragStart(seg, ev);
  4140. view.hideEvent(event); // hide all event segments. our mouseFollower will take over
  4141. },
  4142. hitOver: function(hit, isOrig, origHit) {
  4143. var isAllowed = true;
  4144. var origHitSpan;
  4145. var hitSpan;
  4146. var dragHelperEls;
  4147. // starting hit could be forced (DayGrid.limit)
  4148. if (seg.hit) {
  4149. origHit = seg.hit;
  4150. }
  4151. // hit might not belong to this grid, so query origin grid
  4152. origHitSpan = origHit.component.getSafeHitSpan(origHit);
  4153. hitSpan = hit.component.getSafeHitSpan(hit);
  4154. if (origHitSpan && hitSpan) {
  4155. dropLocation = _this.computeEventDrop(origHitSpan, hitSpan, event);
  4156. isAllowed = dropLocation && _this.isEventLocationAllowed(dropLocation, event);
  4157. }
  4158. else {
  4159. isAllowed = false;
  4160. }
  4161. if (!isAllowed) {
  4162. dropLocation = null;
  4163. disableCursor();
  4164. }
  4165. // if a valid drop location, have the subclass render a visual indication
  4166. if (dropLocation && (dragHelperEls = view.renderDrag(dropLocation, seg))) {
  4167. dragHelperEls.addClass('fc-dragging');
  4168. if (!dragListener.isTouch) {
  4169. _this.applyDragOpacity(dragHelperEls);
  4170. }
  4171. mouseFollower.hide(); // if the subclass is already using a mock event "helper", hide our own
  4172. }
  4173. else {
  4174. mouseFollower.show(); // otherwise, have the helper follow the mouse (no snapping)
  4175. }
  4176. if (isOrig) {
  4177. dropLocation = null; // needs to have moved hits to be a valid drop
  4178. }
  4179. },
  4180. hitOut: function() { // called before mouse moves to a different hit OR moved out of all hits
  4181. view.unrenderDrag(); // unrender whatever was done in renderDrag
  4182. mouseFollower.show(); // show in case we are moving out of all hits
  4183. dropLocation = null;
  4184. },
  4185. hitDone: function() { // Called after a hitOut OR before a dragEnd
  4186. enableCursor();
  4187. },
  4188. interactionEnd: function(ev) {
  4189. delete seg.component; // prevent side effects
  4190. // do revert animation if hasn't changed. calls a callback when finished (whether animation or not)
  4191. mouseFollower.stop(!dropLocation, function() {
  4192. if (isDragging) {
  4193. view.unrenderDrag();
  4194. _this.segDragStop(seg, ev);
  4195. }
  4196. if (dropLocation) {
  4197. // no need to re-show original, will rerender all anyways. esp important if eventRenderWait
  4198. view.reportSegDrop(seg, dropLocation, _this.largeUnit, el, ev);
  4199. }
  4200. else {
  4201. view.showEvent(event);
  4202. }
  4203. });
  4204. _this.segDragListener = null;
  4205. }
  4206. });
  4207. return dragListener;
  4208. },
  4209. // seg isn't draggable, but let's use a generic DragListener
  4210. // simply for the delay, so it can be selected.
  4211. // Has side effect of setting/unsetting `segDragListener`
  4212. buildSegSelectListener: function(seg) {
  4213. var _this = this;
  4214. var view = this.view;
  4215. var event = seg.event;
  4216. if (this.segDragListener) {
  4217. return this.segDragListener;
  4218. }
  4219. var dragListener = this.segDragListener = new DragListener({
  4220. dragStart: function(ev) {
  4221. if (dragListener.isTouch && !view.isEventSelected(event)) {
  4222. // if not previously selected, will fire after a delay. then, select the event
  4223. view.selectEvent(event);
  4224. }
  4225. },
  4226. interactionEnd: function(ev) {
  4227. _this.segDragListener = null;
  4228. }
  4229. });
  4230. return dragListener;
  4231. },
  4232. // Called before event segment dragging starts
  4233. segDragStart: function(seg, ev) {
  4234. this.isDraggingSeg = true;
  4235. this.view.publiclyTrigger('eventDragStart', seg.el[0], seg.event, ev, {}); // last argument is jqui dummy
  4236. },
  4237. // Called after event segment dragging stops
  4238. segDragStop: function(seg, ev) {
  4239. this.isDraggingSeg = false;
  4240. this.view.publiclyTrigger('eventDragStop', seg.el[0], seg.event, ev, {}); // last argument is jqui dummy
  4241. },
  4242. // Given the spans an event drag began, and the span event was dropped, calculates the new zoned start/end/allDay
  4243. // values for the event. Subclasses may override and set additional properties to be used by renderDrag.
  4244. // A falsy returned value indicates an invalid drop.
  4245. // DOES NOT consider overlap/constraint.
  4246. computeEventDrop: function(startSpan, endSpan, event) {
  4247. var calendar = this.view.calendar;
  4248. var dragStart = startSpan.start;
  4249. var dragEnd = endSpan.start;
  4250. var delta;
  4251. var dropLocation; // zoned event date properties
  4252. if (dragStart.hasTime() === dragEnd.hasTime()) {
  4253. delta = this.diffDates(dragEnd, dragStart);
  4254. // if an all-day event was in a timed area and it was dragged to a different time,
  4255. // guarantee an end and adjust start/end to have times
  4256. if (event.allDay && durationHasTime(delta)) {
  4257. dropLocation = {
  4258. start: event.start.clone(),
  4259. end: calendar.getEventEnd(event), // will be an ambig day
  4260. allDay: false // for normalizeEventTimes
  4261. };
  4262. calendar.normalizeEventTimes(dropLocation);
  4263. }
  4264. // othewise, work off existing values
  4265. else {
  4266. dropLocation = pluckEventDateProps(event);
  4267. }
  4268. dropLocation.start.add(delta);
  4269. if (dropLocation.end) {
  4270. dropLocation.end.add(delta);
  4271. }
  4272. }
  4273. else {
  4274. // if switching from day <-> timed, start should be reset to the dropped date, and the end cleared
  4275. dropLocation = {
  4276. start: dragEnd.clone(),
  4277. end: null, // end should be cleared
  4278. allDay: !dragEnd.hasTime()
  4279. };
  4280. }
  4281. return dropLocation;
  4282. },
  4283. // Utility for apply dragOpacity to a jQuery set
  4284. applyDragOpacity: function(els) {
  4285. var opacity = this.view.opt('dragOpacity');
  4286. if (opacity != null) {
  4287. els.css('opacity', opacity);
  4288. }
  4289. },
  4290. /* External Element Dragging
  4291. ------------------------------------------------------------------------------------------------------------------*/
  4292. // Called when a jQuery UI drag is initiated anywhere in the DOM
  4293. externalDragStart: function(ev, ui) {
  4294. var view = this.view;
  4295. var el;
  4296. var accept;
  4297. if (view.opt('droppable')) { // only listen if this setting is on
  4298. el = $((ui ? ui.item : null) || ev.target);
  4299. // Test that the dragged element passes the dropAccept selector or filter function.
  4300. // FYI, the default is "*" (matches all)
  4301. accept = view.opt('dropAccept');
  4302. if ($.isFunction(accept) ? accept.call(el[0], el) : el.is(accept)) {
  4303. if (!this.isDraggingExternal) { // prevent double-listening if fired twice
  4304. this.listenToExternalDrag(el, ev, ui);
  4305. }
  4306. }
  4307. }
  4308. },
  4309. // Called when a jQuery UI drag starts and it needs to be monitored for dropping
  4310. listenToExternalDrag: function(el, ev, ui) {
  4311. var _this = this;
  4312. var view = this.view;
  4313. var meta = getDraggedElMeta(el); // extra data about event drop, including possible event to create
  4314. var dropLocation; // a null value signals an unsuccessful drag
  4315. // listener that tracks mouse movement over date-associated pixel regions
  4316. var dragListener = _this.externalDragListener = new HitDragListener(this, {
  4317. interactionStart: function() {
  4318. _this.isDraggingExternal = true;
  4319. },
  4320. hitOver: function(hit) {
  4321. var isAllowed = true;
  4322. var hitSpan = hit.component.getSafeHitSpan(hit); // hit might not belong to this grid
  4323. if (hitSpan) {
  4324. dropLocation = _this.computeExternalDrop(hitSpan, meta);
  4325. isAllowed = dropLocation && _this.isExternalLocationAllowed(dropLocation, meta.eventProps);
  4326. }
  4327. else {
  4328. isAllowed = false;
  4329. }
  4330. if (!isAllowed) {
  4331. dropLocation = null;
  4332. disableCursor();
  4333. }
  4334. if (dropLocation) {
  4335. _this.renderDrag(dropLocation); // called without a seg parameter
  4336. }
  4337. },
  4338. hitOut: function() {
  4339. dropLocation = null; // signal unsuccessful
  4340. },
  4341. hitDone: function() { // Called after a hitOut OR before a dragEnd
  4342. enableCursor();
  4343. _this.unrenderDrag();
  4344. },
  4345. interactionEnd: function(ev) {
  4346. if (dropLocation) { // element was dropped on a valid hit
  4347. view.reportExternalDrop(meta, dropLocation, el, ev, ui);
  4348. }
  4349. _this.isDraggingExternal = false;
  4350. _this.externalDragListener = null;
  4351. }
  4352. });
  4353. dragListener.startDrag(ev); // start listening immediately
  4354. },
  4355. // Given a hit to be dropped upon, and misc data associated with the jqui drag (guaranteed to be a plain object),
  4356. // returns the zoned start/end dates for the event that would result from the hypothetical drop. end might be null.
  4357. // Returning a null value signals an invalid drop hit.
  4358. // DOES NOT consider overlap/constraint.
  4359. computeExternalDrop: function(span, meta) {
  4360. var calendar = this.view.calendar;
  4361. var dropLocation = {
  4362. start: calendar.applyTimezone(span.start), // simulate a zoned event start date
  4363. end: null
  4364. };
  4365. // if dropped on an all-day span, and element's metadata specified a time, set it
  4366. if (meta.startTime && !dropLocation.start.hasTime()) {
  4367. dropLocation.start.time(meta.startTime);
  4368. }
  4369. if (meta.duration) {
  4370. dropLocation.end = dropLocation.start.clone().add(meta.duration);
  4371. }
  4372. return dropLocation;
  4373. },
  4374. /* Drag Rendering (for both events and an external elements)
  4375. ------------------------------------------------------------------------------------------------------------------*/
  4376. // Renders a visual indication of an event or external element being dragged.
  4377. // `dropLocation` contains hypothetical start/end/allDay values the event would have if dropped. end can be null.
  4378. // `seg` is the internal segment object that is being dragged. If dragging an external element, `seg` is null.
  4379. // A truthy returned value indicates this method has rendered a helper element.
  4380. // Must return elements used for any mock events.
  4381. renderDrag: function(dropLocation, seg) {
  4382. // subclasses must implement
  4383. },
  4384. // Unrenders a visual indication of an event or external element being dragged
  4385. unrenderDrag: function() {
  4386. // subclasses must implement
  4387. },
  4388. /* Resizing
  4389. ------------------------------------------------------------------------------------------------------------------*/
  4390. // Creates a listener that tracks the user as they resize an event segment.
  4391. // Generic enough to work with any type of Grid.
  4392. buildSegResizeListener: function(seg, isStart) {
  4393. var _this = this;
  4394. var view = this.view;
  4395. var calendar = view.calendar;
  4396. var el = seg.el;
  4397. var event = seg.event;
  4398. var eventEnd = calendar.getEventEnd(event);
  4399. var isDragging;
  4400. var resizeLocation; // zoned event date properties. falsy if invalid resize
  4401. // Tracks mouse movement over the *grid's* coordinate map
  4402. var dragListener = this.segResizeListener = new HitDragListener(this, {
  4403. scroll: view.opt('dragScroll'),
  4404. subjectEl: el,
  4405. interactionStart: function() {
  4406. isDragging = false;
  4407. },
  4408. dragStart: function(ev) {
  4409. isDragging = true;
  4410. _this.handleSegMouseout(seg, ev); // ensure a mouseout on the manipulated event has been reported
  4411. _this.segResizeStart(seg, ev);
  4412. },
  4413. hitOver: function(hit, isOrig, origHit) {
  4414. var isAllowed = true;
  4415. var origHitSpan = _this.getSafeHitSpan(origHit);
  4416. var hitSpan = _this.getSafeHitSpan(hit);
  4417. if (origHitSpan && hitSpan) {
  4418. resizeLocation = isStart ?
  4419. _this.computeEventStartResize(origHitSpan, hitSpan, event) :
  4420. _this.computeEventEndResize(origHitSpan, hitSpan, event);
  4421. isAllowed = resizeLocation && _this.isEventLocationAllowed(resizeLocation, event);
  4422. }
  4423. else {
  4424. isAllowed = false;
  4425. }
  4426. if (!isAllowed) {
  4427. resizeLocation = null;
  4428. disableCursor();
  4429. }
  4430. else {
  4431. if (
  4432. resizeLocation.start.isSame(event.start.clone().stripZone()) &&
  4433. resizeLocation.end.isSame(eventEnd.clone().stripZone())
  4434. ) {
  4435. // no change. (FYI, event dates might have zones)
  4436. resizeLocation = null;
  4437. }
  4438. }
  4439. if (resizeLocation) {
  4440. view.hideEvent(event);
  4441. _this.renderEventResize(resizeLocation, seg);
  4442. }
  4443. },
  4444. hitOut: function() { // called before mouse moves to a different hit OR moved out of all hits
  4445. resizeLocation = null;
  4446. view.showEvent(event); // for when out-of-bounds. show original
  4447. },
  4448. hitDone: function() { // resets the rendering to show the original event
  4449. _this.unrenderEventResize();
  4450. enableCursor();
  4451. },
  4452. interactionEnd: function(ev) {
  4453. if (isDragging) {
  4454. _this.segResizeStop(seg, ev);
  4455. }
  4456. if (resizeLocation) { // valid date to resize to?
  4457. // no need to re-show original, will rerender all anyways. esp important if eventRenderWait
  4458. view.reportSegResize(seg, resizeLocation, _this.largeUnit, el, ev);
  4459. }
  4460. else {
  4461. view.showEvent(event);
  4462. }
  4463. _this.segResizeListener = null;
  4464. }
  4465. });
  4466. return dragListener;
  4467. },
  4468. // Called before event segment resizing starts
  4469. segResizeStart: function(seg, ev) {
  4470. this.isResizingSeg = true;
  4471. this.view.publiclyTrigger('eventResizeStart', seg.el[0], seg.event, ev, {}); // last argument is jqui dummy
  4472. },
  4473. // Called after event segment resizing stops
  4474. segResizeStop: function(seg, ev) {
  4475. this.isResizingSeg = false;
  4476. this.view.publiclyTrigger('eventResizeStop', seg.el[0], seg.event, ev, {}); // last argument is jqui dummy
  4477. },
  4478. // Returns new date-information for an event segment being resized from its start
  4479. computeEventStartResize: function(startSpan, endSpan, event) {
  4480. return this.computeEventResize('start', startSpan, endSpan, event);
  4481. },
  4482. // Returns new date-information for an event segment being resized from its end
  4483. computeEventEndResize: function(startSpan, endSpan, event) {
  4484. return this.computeEventResize('end', startSpan, endSpan, event);
  4485. },
  4486. // Returns new zoned date information for an event segment being resized from its start OR end
  4487. // `type` is either 'start' or 'end'.
  4488. // DOES NOT consider overlap/constraint.
  4489. computeEventResize: function(type, startSpan, endSpan, event) {
  4490. var calendar = this.view.calendar;
  4491. var delta = this.diffDates(endSpan[type], startSpan[type]);
  4492. var resizeLocation; // zoned event date properties
  4493. var defaultDuration;
  4494. // build original values to work from, guaranteeing a start and end
  4495. resizeLocation = {
  4496. start: event.start.clone(),
  4497. end: calendar.getEventEnd(event),
  4498. allDay: event.allDay
  4499. };
  4500. // if an all-day event was in a timed area and was resized to a time, adjust start/end to have times
  4501. if (resizeLocation.allDay && durationHasTime(delta)) {
  4502. resizeLocation.allDay = false;
  4503. calendar.normalizeEventTimes(resizeLocation);
  4504. }
  4505. resizeLocation[type].add(delta); // apply delta to start or end
  4506. // if the event was compressed too small, find a new reasonable duration for it
  4507. if (!resizeLocation.start.isBefore(resizeLocation.end)) {
  4508. defaultDuration =
  4509. this.minResizeDuration || // TODO: hack
  4510. (event.allDay ?
  4511. calendar.defaultAllDayEventDuration :
  4512. calendar.defaultTimedEventDuration);
  4513. if (type == 'start') { // resizing the start?
  4514. resizeLocation.start = resizeLocation.end.clone().subtract(defaultDuration);
  4515. }
  4516. else { // resizing the end?
  4517. resizeLocation.end = resizeLocation.start.clone().add(defaultDuration);
  4518. }
  4519. }
  4520. return resizeLocation;
  4521. },
  4522. // Renders a visual indication of an event being resized.
  4523. // `range` has the updated dates of the event. `seg` is the original segment object involved in the drag.
  4524. // Must return elements used for any mock events.
  4525. renderEventResize: function(range, seg) {
  4526. // subclasses must implement
  4527. },
  4528. // Unrenders a visual indication of an event being resized.
  4529. unrenderEventResize: function() {
  4530. // subclasses must implement
  4531. },
  4532. /* Rendering Utils
  4533. ------------------------------------------------------------------------------------------------------------------*/
  4534. // Compute the text that should be displayed on an event's element.
  4535. // `range` can be the Event object itself, or something range-like, with at least a `start`.
  4536. // If event times are disabled, or the event has no time, will return a blank string.
  4537. // If not specified, formatStr will default to the eventTimeFormat setting,
  4538. // and displayEnd will default to the displayEventEnd setting.
  4539. getEventTimeText: function(range, formatStr, displayEnd) {
  4540. if (formatStr == null) {
  4541. formatStr = this.eventTimeFormat;
  4542. }
  4543. if (displayEnd == null) {
  4544. displayEnd = this.displayEventEnd;
  4545. }
  4546. if (this.displayEventTime && range.start.hasTime()) {
  4547. if (displayEnd && range.end) {
  4548. return this.view.formatRange(range, formatStr);
  4549. }
  4550. else {
  4551. return range.start.format(formatStr);
  4552. }
  4553. }
  4554. return '';
  4555. },
  4556. // Generic utility for generating the HTML classNames for an event segment's element
  4557. getSegClasses: function(seg, isDraggable, isResizable) {
  4558. var view = this.view;
  4559. var classes = [
  4560. 'fc-event',
  4561. seg.isStart ? 'fc-start' : 'fc-not-start',
  4562. seg.isEnd ? 'fc-end' : 'fc-not-end'
  4563. ].concat(this.getSegCustomClasses(seg));
  4564. if (isDraggable) {
  4565. classes.push('fc-draggable');
  4566. }
  4567. if (isResizable) {
  4568. classes.push('fc-resizable');
  4569. }
  4570. // event is currently selected? attach a className.
  4571. if (view.isEventSelected(seg.event)) {
  4572. classes.push('fc-selected');
  4573. }
  4574. return classes;
  4575. },
  4576. // List of classes that were defined by the caller of the API in some way
  4577. getSegCustomClasses: function(seg) {
  4578. var event = seg.event;
  4579. return [].concat(
  4580. event.className, // guaranteed to be an array
  4581. event.source ? event.source.className : []
  4582. );
  4583. },
  4584. // Utility for generating event skin-related CSS properties
  4585. getSegSkinCss: function(seg) {
  4586. return {
  4587. 'background-color': this.getSegBackgroundColor(seg),
  4588. 'border-color': this.getSegBorderColor(seg),
  4589. color: this.getSegTextColor(seg)
  4590. };
  4591. },
  4592. // Queries for caller-specified color, then falls back to default
  4593. getSegBackgroundColor: function(seg) {
  4594. return seg.event.backgroundColor ||
  4595. seg.event.color ||
  4596. this.getSegDefaultBackgroundColor(seg);
  4597. },
  4598. getSegDefaultBackgroundColor: function(seg) {
  4599. var source = seg.event.source || {};
  4600. return source.backgroundColor ||
  4601. source.color ||
  4602. this.view.opt('eventBackgroundColor') ||
  4603. this.view.opt('eventColor');
  4604. },
  4605. // Queries for caller-specified color, then falls back to default
  4606. getSegBorderColor: function(seg) {
  4607. return seg.event.borderColor ||
  4608. seg.event.color ||
  4609. this.getSegDefaultBorderColor(seg);
  4610. },
  4611. getSegDefaultBorderColor: function(seg) {
  4612. var source = seg.event.source || {};
  4613. return source.borderColor ||
  4614. source.color ||
  4615. this.view.opt('eventBorderColor') ||
  4616. this.view.opt('eventColor');
  4617. },
  4618. // Queries for caller-specified color, then falls back to default
  4619. getSegTextColor: function(seg) {
  4620. return seg.event.textColor ||
  4621. this.getSegDefaultTextColor(seg);
  4622. },
  4623. getSegDefaultTextColor: function(seg) {
  4624. var source = seg.event.source || {};
  4625. return source.textColor ||
  4626. this.view.opt('eventTextColor');
  4627. },
  4628. /* Event Location Validation
  4629. ------------------------------------------------------------------------------------------------------------------*/
  4630. isEventLocationAllowed: function(eventLocation, event) {
  4631. if (this.isEventLocationInRange(eventLocation)) {
  4632. var calendar = this.view.calendar;
  4633. var eventSpans = this.eventToSpans(eventLocation);
  4634. var i;
  4635. if (eventSpans.length) {
  4636. for (i = 0; i < eventSpans.length; i++) {
  4637. if (!calendar.isEventSpanAllowed(eventSpans[i], event)) {
  4638. return false;
  4639. }
  4640. }
  4641. return true;
  4642. }
  4643. }
  4644. return false;
  4645. },
  4646. isExternalLocationAllowed: function(eventLocation, metaProps) { // FOR the external element
  4647. if (this.isEventLocationInRange(eventLocation)) {
  4648. var calendar = this.view.calendar;
  4649. var eventSpans = this.eventToSpans(eventLocation);
  4650. var i;
  4651. if (eventSpans.length) {
  4652. for (i = 0; i < eventSpans.length; i++) {
  4653. if (!calendar.isExternalSpanAllowed(eventSpans[i], eventLocation, metaProps)) {
  4654. return false;
  4655. }
  4656. }
  4657. return true;
  4658. }
  4659. }
  4660. return false;
  4661. },
  4662. isEventLocationInRange: function(eventLocation) {
  4663. return isRangeWithinRange(
  4664. this.eventToRawRange(eventLocation),
  4665. this.view.validRange
  4666. );
  4667. },
  4668. /* Converting events -> eventRange -> eventSpan -> eventSegs
  4669. ------------------------------------------------------------------------------------------------------------------*/
  4670. // Generates an array of segments for the given single event
  4671. // Can accept an event "location" as well (which only has start/end and no allDay)
  4672. eventToSegs: function(event) {
  4673. return this.eventsToSegs([ event ]);
  4674. },
  4675. // Generates spans (always unzoned) for the given event.
  4676. // Does not do any inverting for inverse-background events.
  4677. // Can accept an event "location" as well (which only has start/end and no allDay)
  4678. eventToSpans: function(event) {
  4679. var eventRange = this.eventToRange(event); // { start, end, isStart, isEnd }
  4680. if (eventRange) {
  4681. return this.eventRangeToSpans(eventRange, event);
  4682. }
  4683. else { // out of view's valid range
  4684. return [];
  4685. }
  4686. },
  4687. // Converts an array of event objects into an array of event segment objects.
  4688. // A custom `segSliceFunc` may be given for arbitrarily slicing up events.
  4689. // Doesn't guarantee an order for the resulting array.
  4690. eventsToSegs: function(allEvents, segSliceFunc) {
  4691. var _this = this;
  4692. var eventsById = groupEventsById(allEvents);
  4693. var segs = [];
  4694. $.each(eventsById, function(id, events) {
  4695. var visibleEvents = [];
  4696. var eventRanges = [];
  4697. var eventRange; // { start, end, isStart, isEnd }
  4698. var i;
  4699. for (i = 0; i < events.length; i++) {
  4700. eventRange = _this.eventToRange(events[i]); // might be null if completely out of range
  4701. if (eventRange) {
  4702. eventRanges.push(eventRange);
  4703. visibleEvents.push(events[i]);
  4704. }
  4705. }
  4706. // inverse-background events (utilize only the first event in calculations)
  4707. if (isInverseBgEvent(events[0])) {
  4708. eventRanges = _this.invertRanges(eventRanges); // will lose isStart/isEnd
  4709. for (i = 0; i < eventRanges.length; i++) {
  4710. segs.push.apply(segs, // append to
  4711. _this.eventRangeToSegs(eventRanges[i], events[0], segSliceFunc)
  4712. );
  4713. }
  4714. }
  4715. // normal event ranges
  4716. else {
  4717. for (i = 0; i < eventRanges.length; i++) {
  4718. segs.push.apply(segs, // append to
  4719. _this.eventRangeToSegs(eventRanges[i], visibleEvents[i], segSliceFunc)
  4720. );
  4721. }
  4722. }
  4723. });
  4724. return segs;
  4725. },
  4726. // Generates the unzoned start/end dates an event appears to occupy
  4727. // Can accept an event "location" as well (which only has start/end and no allDay)
  4728. // returns { start, end, isStart, isEnd }
  4729. // If the event is completely outside of the grid's valid range, will return undefined.
  4730. eventToRange: function(event) {
  4731. return this.refineRawEventRange(
  4732. this.eventToRawRange(event)
  4733. );
  4734. },
  4735. // Ensures the given range is within the view's activeRange and is correctly localized.
  4736. // Always returns a result
  4737. refineRawEventRange: function(rawRange) {
  4738. var view = this.view;
  4739. var calendar = view.calendar;
  4740. var range = intersectRanges(rawRange, view.activeRange);
  4741. if (range) { // otherwise, event doesn't have valid range
  4742. // hack: dynamic locale change forgets to upate stored event localed
  4743. calendar.localizeMoment(range.start);
  4744. calendar.localizeMoment(range.end);
  4745. return range;
  4746. }
  4747. },
  4748. // not constrained to valid dates
  4749. // not given localizeMoment hack
  4750. eventToRawRange: function(event) {
  4751. var calendar = this.view.calendar;
  4752. var start = event.start.clone().stripZone();
  4753. var end = (
  4754. event.end ?
  4755. event.end.clone() :
  4756. // derive the end from the start and allDay. compute allDay if necessary
  4757. calendar.getDefaultEventEnd(
  4758. event.allDay != null ?
  4759. event.allDay :
  4760. !event.start.hasTime(),
  4761. event.start
  4762. )
  4763. ).stripZone();
  4764. return { start: start, end: end };
  4765. },
  4766. // Given an event's range (unzoned start/end), and the event itself,
  4767. // slice into segments (using the segSliceFunc function if specified)
  4768. // eventRange - { start, end, isStart, isEnd }
  4769. eventRangeToSegs: function(eventRange, event, segSliceFunc) {
  4770. var eventSpans = this.eventRangeToSpans(eventRange, event);
  4771. var segs = [];
  4772. var i;
  4773. for (i = 0; i < eventSpans.length; i++) {
  4774. segs.push.apply(segs, // append to
  4775. this.eventSpanToSegs(eventSpans[i], event, segSliceFunc)
  4776. );
  4777. }
  4778. return segs;
  4779. },
  4780. // Given an event's unzoned date range, return an array of eventSpan objects.
  4781. // eventSpan - { start, end, isStart, isEnd, otherthings... }
  4782. // Subclasses can override.
  4783. // Subclasses are obligated to forward eventRange.isStart/isEnd to the resulting spans.
  4784. eventRangeToSpans: function(eventRange, event) {
  4785. return [ $.extend({}, eventRange) ]; // copy into a single-item array
  4786. },
  4787. // Given an event's span (unzoned start/end and other misc data), and the event itself,
  4788. // slices into segments and attaches event-derived properties to them.
  4789. // eventSpan - { start, end, isStart, isEnd, otherthings... }
  4790. eventSpanToSegs: function(eventSpan, event, segSliceFunc) {
  4791. var segs = segSliceFunc ? segSliceFunc(eventSpan) : this.spanToSegs(eventSpan);
  4792. var i, seg;
  4793. for (i = 0; i < segs.length; i++) {
  4794. seg = segs[i];
  4795. // the eventSpan's isStart/isEnd takes precedence over the seg's
  4796. if (!eventSpan.isStart) {
  4797. seg.isStart = false;
  4798. }
  4799. if (!eventSpan.isEnd) {
  4800. seg.isEnd = false;
  4801. }
  4802. seg.event = event;
  4803. seg.eventStartMS = +eventSpan.start; // TODO: not the best name after making spans unzoned
  4804. seg.eventDurationMS = eventSpan.end - eventSpan.start;
  4805. }
  4806. return segs;
  4807. },
  4808. // Produces a new array of range objects that will cover all the time NOT covered by the given ranges.
  4809. // SIDE EFFECT: will mutate the given array and will use its date references.
  4810. invertRanges: function(ranges) {
  4811. var view = this.view;
  4812. var viewStart = view.activeRange.start.clone(); // need a copy
  4813. var viewEnd = view.activeRange.end.clone(); // need a copy
  4814. var inverseRanges = [];
  4815. var start = viewStart; // the end of the previous range. the start of the new range
  4816. var i, range;
  4817. // ranges need to be in order. required for our date-walking algorithm
  4818. ranges.sort(compareRanges);
  4819. for (i = 0; i < ranges.length; i++) {
  4820. range = ranges[i];
  4821. // add the span of time before the event (if there is any)
  4822. if (range.start > start) { // compare millisecond time (skip any ambig logic)
  4823. inverseRanges.push({
  4824. start: start,
  4825. end: range.start
  4826. });
  4827. }
  4828. if (range.end > start) {
  4829. start = range.end;
  4830. }
  4831. }
  4832. // add the span of time after the last event (if there is any)
  4833. if (start < viewEnd) { // compare millisecond time (skip any ambig logic)
  4834. inverseRanges.push({
  4835. start: start,
  4836. end: viewEnd
  4837. });
  4838. }
  4839. return inverseRanges;
  4840. },
  4841. sortEventSegs: function(segs) {
  4842. segs.sort(proxy(this, 'compareEventSegs'));
  4843. },
  4844. // A cmp function for determining which segments should take visual priority
  4845. compareEventSegs: function(seg1, seg2) {
  4846. return seg1.eventStartMS - seg2.eventStartMS || // earlier events go first
  4847. seg2.eventDurationMS - seg1.eventDurationMS || // tie? longer events go first
  4848. seg2.event.allDay - seg1.event.allDay || // tie? put all-day events first (booleans cast to 0/1)
  4849. compareByFieldSpecs(seg1.event, seg2.event, this.view.eventOrderSpecs);
  4850. }
  4851. });
  4852. /* Utilities
  4853. ----------------------------------------------------------------------------------------------------------------------*/
  4854. function pluckEventDateProps(event) {
  4855. return {
  4856. start: event.start.clone(),
  4857. end: event.end ? event.end.clone() : null,
  4858. allDay: event.allDay // keep it the same
  4859. };
  4860. }
  4861. FC.pluckEventDateProps = pluckEventDateProps;
  4862. function isBgEvent(event) { // returns true if background OR inverse-background
  4863. var rendering = getEventRendering(event);
  4864. return rendering === 'background' || rendering === 'inverse-background';
  4865. }
  4866. FC.isBgEvent = isBgEvent; // export
  4867. function isInverseBgEvent(event) {
  4868. return getEventRendering(event) === 'inverse-background';
  4869. }
  4870. function getEventRendering(event) {
  4871. return firstDefined((event.source || {}).rendering, event.rendering);
  4872. }
  4873. function groupEventsById(events) {
  4874. var eventsById = {};
  4875. var i, event;
  4876. for (i = 0; i < events.length; i++) {
  4877. event = events[i];
  4878. (eventsById[event._id] || (eventsById[event._id] = [])).push(event);
  4879. }
  4880. return eventsById;
  4881. }
  4882. // A cmp function for determining which non-inverted "ranges" (see above) happen earlier
  4883. function compareRanges(range1, range2) {
  4884. return range1.start - range2.start; // earlier ranges go first
  4885. }
  4886. /* External-Dragging-Element Data
  4887. ----------------------------------------------------------------------------------------------------------------------*/
  4888. // Require all HTML5 data-* attributes used by FullCalendar to have this prefix.
  4889. // A value of '' will query attributes like data-event. A value of 'fc' will query attributes like data-fc-event.
  4890. FC.dataAttrPrefix = '';
  4891. // Given a jQuery element that might represent a dragged FullCalendar event, returns an intermediate data structure
  4892. // to be used for Event Object creation.
  4893. // A defined `.eventProps`, even when empty, indicates that an event should be created.
  4894. function getDraggedElMeta(el) {
  4895. var prefix = FC.dataAttrPrefix;
  4896. var eventProps; // properties for creating the event, not related to date/time
  4897. var startTime; // a Duration
  4898. var duration;
  4899. var stick;
  4900. if (prefix) { prefix += '-'; }
  4901. eventProps = el.data(prefix + 'event') || null;
  4902. if (eventProps) {
  4903. if (typeof eventProps === 'object') {
  4904. eventProps = $.extend({}, eventProps); // make a copy
  4905. }
  4906. else { // something like 1 or true. still signal event creation
  4907. eventProps = {};
  4908. }
  4909. // pluck special-cased date/time properties
  4910. startTime = eventProps.start;
  4911. if (startTime == null) { startTime = eventProps.time; } // accept 'time' as well
  4912. duration = eventProps.duration;
  4913. stick = eventProps.stick;
  4914. delete eventProps.start;
  4915. delete eventProps.time;
  4916. delete eventProps.duration;
  4917. delete eventProps.stick;
  4918. }
  4919. // fallback to standalone attribute values for each of the date/time properties
  4920. if (startTime == null) { startTime = el.data(prefix + 'start'); }
  4921. if (startTime == null) { startTime = el.data(prefix + 'time'); } // accept 'time' as well
  4922. if (duration == null) { duration = el.data(prefix + 'duration'); }
  4923. if (stick == null) { stick = el.data(prefix + 'stick'); }
  4924. // massage into correct data types
  4925. startTime = startTime != null ? moment.duration(startTime) : null;
  4926. duration = duration != null ? moment.duration(duration) : null;
  4927. stick = Boolean(stick);
  4928. return { eventProps: eventProps, startTime: startTime, duration: duration, stick: stick };
  4929. }
  4930. ;;
  4931. /*
  4932. A set of rendering and date-related methods for a visual component comprised of one or more rows of day columns.
  4933. Prerequisite: the object being mixed into needs to be a *Grid*
  4934. */
  4935. var DayTableMixin = FC.DayTableMixin = {
  4936. breakOnWeeks: false, // should create a new row for each week?
  4937. dayDates: null, // whole-day dates for each column. left to right
  4938. dayIndices: null, // for each day from start, the offset
  4939. daysPerRow: null,
  4940. rowCnt: null,
  4941. colCnt: null,
  4942. colHeadFormat: null,
  4943. // Populates internal variables used for date calculation and rendering
  4944. updateDayTable: function() {
  4945. var view = this.view;
  4946. var date = this.start.clone();
  4947. var dayIndex = -1;
  4948. var dayIndices = [];
  4949. var dayDates = [];
  4950. var daysPerRow;
  4951. var firstDay;
  4952. var rowCnt;
  4953. while (date.isBefore(this.end)) { // loop each day from start to end
  4954. if (view.isHiddenDay(date)) {
  4955. dayIndices.push(dayIndex + 0.5); // mark that it's between indices
  4956. }
  4957. else {
  4958. dayIndex++;
  4959. dayIndices.push(dayIndex);
  4960. dayDates.push(date.clone());
  4961. }
  4962. date.add(1, 'days');
  4963. }
  4964. if (this.breakOnWeeks) {
  4965. // count columns until the day-of-week repeats
  4966. firstDay = dayDates[0].day();
  4967. for (daysPerRow = 1; daysPerRow < dayDates.length; daysPerRow++) {
  4968. if (dayDates[daysPerRow].day() == firstDay) {
  4969. break;
  4970. }
  4971. }
  4972. rowCnt = Math.ceil(dayDates.length / daysPerRow);
  4973. }
  4974. else {
  4975. rowCnt = 1;
  4976. daysPerRow = dayDates.length;
  4977. }
  4978. this.dayDates = dayDates;
  4979. this.dayIndices = dayIndices;
  4980. this.daysPerRow = daysPerRow;
  4981. this.rowCnt = rowCnt;
  4982. this.updateDayTableCols();
  4983. },
  4984. // Computes and assigned the colCnt property and updates any options that may be computed from it
  4985. updateDayTableCols: function() {
  4986. this.colCnt = this.computeColCnt();
  4987. this.colHeadFormat = this.view.opt('columnFormat') || this.computeColHeadFormat();
  4988. },
  4989. // Determines how many columns there should be in the table
  4990. computeColCnt: function() {
  4991. return this.daysPerRow;
  4992. },
  4993. // Computes the ambiguously-timed moment for the given cell
  4994. getCellDate: function(row, col) {
  4995. return this.dayDates[
  4996. this.getCellDayIndex(row, col)
  4997. ].clone();
  4998. },
  4999. // Computes the ambiguously-timed date range for the given cell
  5000. getCellRange: function(row, col) {
  5001. var start = this.getCellDate(row, col);
  5002. var end = start.clone().add(1, 'days');
  5003. return { start: start, end: end };
  5004. },
  5005. // Returns the number of day cells, chronologically, from the first of the grid (0-based)
  5006. getCellDayIndex: function(row, col) {
  5007. return row * this.daysPerRow + this.getColDayIndex(col);
  5008. },
  5009. // Returns the numner of day cells, chronologically, from the first cell in *any given row*
  5010. getColDayIndex: function(col) {
  5011. if (this.isRTL) {
  5012. return this.colCnt - 1 - col;
  5013. }
  5014. else {
  5015. return col;
  5016. }
  5017. },
  5018. // Given a date, returns its chronolocial cell-index from the first cell of the grid.
  5019. // If the date lies between cells (because of hiddenDays), returns a floating-point value between offsets.
  5020. // If before the first offset, returns a negative number.
  5021. // If after the last offset, returns an offset past the last cell offset.
  5022. // Only works for *start* dates of cells. Will not work for exclusive end dates for cells.
  5023. getDateDayIndex: function(date) {
  5024. var dayIndices = this.dayIndices;
  5025. var dayOffset = date.diff(this.start, 'days');
  5026. if (dayOffset < 0) {
  5027. return dayIndices[0] - 1;
  5028. }
  5029. else if (dayOffset >= dayIndices.length) {
  5030. return dayIndices[dayIndices.length - 1] + 1;
  5031. }
  5032. else {
  5033. return dayIndices[dayOffset];
  5034. }
  5035. },
  5036. /* Options
  5037. ------------------------------------------------------------------------------------------------------------------*/
  5038. // Computes a default column header formatting string if `colFormat` is not explicitly defined
  5039. computeColHeadFormat: function() {
  5040. // if more than one week row, or if there are a lot of columns with not much space,
  5041. // put just the day numbers will be in each cell
  5042. if (this.rowCnt > 1 || this.colCnt > 10) {
  5043. return 'ddd'; // "Sat"
  5044. }
  5045. // multiple days, so full single date string WON'T be in title text
  5046. else if (this.colCnt > 1) {
  5047. return this.view.opt('dayOfMonthFormat'); // "Sat 12/10"
  5048. }
  5049. // single day, so full single date string will probably be in title text
  5050. else {
  5051. return 'dddd'; // "Saturday"
  5052. }
  5053. },
  5054. /* Slicing
  5055. ------------------------------------------------------------------------------------------------------------------*/
  5056. // Slices up a date range into a segment for every week-row it intersects with
  5057. sliceRangeByRow: function(range) {
  5058. var daysPerRow = this.daysPerRow;
  5059. var normalRange = this.view.computeDayRange(range); // make whole-day range, considering nextDayThreshold
  5060. var rangeFirst = this.getDateDayIndex(normalRange.start); // inclusive first index
  5061. var rangeLast = this.getDateDayIndex(normalRange.end.clone().subtract(1, 'days')); // inclusive last index
  5062. var segs = [];
  5063. var row;
  5064. var rowFirst, rowLast; // inclusive day-index range for current row
  5065. var segFirst, segLast; // inclusive day-index range for segment
  5066. for (row = 0; row < this.rowCnt; row++) {
  5067. rowFirst = row * daysPerRow;
  5068. rowLast = rowFirst + daysPerRow - 1;
  5069. // intersect segment's offset range with the row's
  5070. segFirst = Math.max(rangeFirst, rowFirst);
  5071. segLast = Math.min(rangeLast, rowLast);
  5072. // deal with in-between indices
  5073. segFirst = Math.ceil(segFirst); // in-between starts round to next cell
  5074. segLast = Math.floor(segLast); // in-between ends round to prev cell
  5075. if (segFirst <= segLast) { // was there any intersection with the current row?
  5076. segs.push({
  5077. row: row,
  5078. // normalize to start of row
  5079. firstRowDayIndex: segFirst - rowFirst,
  5080. lastRowDayIndex: segLast - rowFirst,
  5081. // must be matching integers to be the segment's start/end
  5082. isStart: segFirst === rangeFirst,
  5083. isEnd: segLast === rangeLast
  5084. });
  5085. }
  5086. }
  5087. return segs;
  5088. },
  5089. // Slices up a date range into a segment for every day-cell it intersects with.
  5090. // TODO: make more DRY with sliceRangeByRow somehow.
  5091. sliceRangeByDay: function(range) {
  5092. var daysPerRow = this.daysPerRow;
  5093. var normalRange = this.view.computeDayRange(range); // make whole-day range, considering nextDayThreshold
  5094. var rangeFirst = this.getDateDayIndex(normalRange.start); // inclusive first index
  5095. var rangeLast = this.getDateDayIndex(normalRange.end.clone().subtract(1, 'days')); // inclusive last index
  5096. var segs = [];
  5097. var row;
  5098. var rowFirst, rowLast; // inclusive day-index range for current row
  5099. var i;
  5100. var segFirst, segLast; // inclusive day-index range for segment
  5101. for (row = 0; row < this.rowCnt; row++) {
  5102. rowFirst = row * daysPerRow;
  5103. rowLast = rowFirst + daysPerRow - 1;
  5104. for (i = rowFirst; i <= rowLast; i++) {
  5105. // intersect segment's offset range with the row's
  5106. segFirst = Math.max(rangeFirst, i);
  5107. segLast = Math.min(rangeLast, i);
  5108. // deal with in-between indices
  5109. segFirst = Math.ceil(segFirst); // in-between starts round to next cell
  5110. segLast = Math.floor(segLast); // in-between ends round to prev cell
  5111. if (segFirst <= segLast) { // was there any intersection with the current row?
  5112. segs.push({
  5113. row: row,
  5114. // normalize to start of row
  5115. firstRowDayIndex: segFirst - rowFirst,
  5116. lastRowDayIndex: segLast - rowFirst,
  5117. // must be matching integers to be the segment's start/end
  5118. isStart: segFirst === rangeFirst,
  5119. isEnd: segLast === rangeLast
  5120. });
  5121. }
  5122. }
  5123. }
  5124. return segs;
  5125. },
  5126. /* Header Rendering
  5127. ------------------------------------------------------------------------------------------------------------------*/
  5128. renderHeadHtml: function() {
  5129. var view = this.view;
  5130. return '' +
  5131. '<div class="fc-row ' + view.widgetHeaderClass + '">' +
  5132. '<table>' +
  5133. '<thead>' +
  5134. this.renderHeadTrHtml() +
  5135. '</thead>' +
  5136. '</table>' +
  5137. '</div>';
  5138. },
  5139. renderHeadIntroHtml: function() {
  5140. return this.renderIntroHtml(); // fall back to generic
  5141. },
  5142. renderHeadTrHtml: function() {
  5143. return '' +
  5144. '<tr>' +
  5145. (this.isRTL ? '' : this.renderHeadIntroHtml()) +
  5146. this.renderHeadDateCellsHtml() +
  5147. (this.isRTL ? this.renderHeadIntroHtml() : '') +
  5148. '</tr>';
  5149. },
  5150. renderHeadDateCellsHtml: function() {
  5151. var htmls = [];
  5152. var col, date;
  5153. for (col = 0; col < this.colCnt; col++) {
  5154. date = this.getCellDate(0, col);
  5155. htmls.push(this.renderHeadDateCellHtml(date));
  5156. }
  5157. return htmls.join('');
  5158. },
  5159. // TODO: when internalApiVersion, accept an object for HTML attributes
  5160. // (colspan should be no different)
  5161. renderHeadDateCellHtml: function(date, colspan, otherAttrs) {
  5162. var view = this.view;
  5163. var isDateValid = isDateWithinRange(date, view.activeRange); // TODO: called too frequently. cache somehow.
  5164. var classNames = [
  5165. 'fc-day-header',
  5166. view.widgetHeaderClass
  5167. ];
  5168. var innerHtml = htmlEscape(date.format(this.colHeadFormat));
  5169. // if only one row of days, the classNames on the header can represent the specific days beneath
  5170. if (this.rowCnt === 1) {
  5171. classNames = classNames.concat(
  5172. // includes the day-of-week class
  5173. // noThemeHighlight=true (don't highlight the header)
  5174. this.getDayClasses(date, true)
  5175. );
  5176. }
  5177. else {
  5178. classNames.push('fc-' + dayIDs[date.day()]); // only add the day-of-week class
  5179. }
  5180. return '' +
  5181. '<th class="' + classNames.join(' ') + '"' +
  5182. ((isDateValid && this.rowCnt) === 1 ?
  5183. ' data-date="' + date.format('YYYY-MM-DD') + '"' :
  5184. '') +
  5185. (colspan > 1 ?
  5186. ' colspan="' + colspan + '"' :
  5187. '') +
  5188. (otherAttrs ?
  5189. ' ' + otherAttrs :
  5190. '') +
  5191. '>' +
  5192. (isDateValid ?
  5193. // don't make a link if the heading could represent multiple days, or if there's only one day (forceOff)
  5194. view.buildGotoAnchorHtml(
  5195. { date: date, forceOff: this.rowCnt > 1 || this.colCnt === 1 },
  5196. innerHtml
  5197. ) :
  5198. // if not valid, display text, but no link
  5199. innerHtml
  5200. ) +
  5201. '</th>';
  5202. },
  5203. /* Background Rendering
  5204. ------------------------------------------------------------------------------------------------------------------*/
  5205. renderBgTrHtml: function(row) {
  5206. return '' +
  5207. '<tr>' +
  5208. (this.isRTL ? '' : this.renderBgIntroHtml(row)) +
  5209. this.renderBgCellsHtml(row) +
  5210. (this.isRTL ? this.renderBgIntroHtml(row) : '') +
  5211. '</tr>';
  5212. },
  5213. renderBgIntroHtml: function(row) {
  5214. return this.renderIntroHtml(); // fall back to generic
  5215. },
  5216. renderBgCellsHtml: function(row) {
  5217. var htmls = [];
  5218. var col, date;
  5219. for (col = 0; col < this.colCnt; col++) {
  5220. date = this.getCellDate(row, col);
  5221. htmls.push(this.renderBgCellHtml(date));
  5222. }
  5223. return htmls.join('');
  5224. },
  5225. renderBgCellHtml: function(date, otherAttrs) {
  5226. var view = this.view;
  5227. var isDateValid = isDateWithinRange(date, view.activeRange); // TODO: called too frequently. cache somehow.
  5228. var classes = this.getDayClasses(date);
  5229. classes.unshift('fc-day', view.widgetContentClass);
  5230. return '<td class="' + classes.join(' ') + '"' +
  5231. (isDateValid ?
  5232. ' data-date="' + date.format('YYYY-MM-DD') + '"' : // if date has a time, won't format it
  5233. '') +
  5234. (otherAttrs ?
  5235. ' ' + otherAttrs :
  5236. '') +
  5237. '></td>';
  5238. },
  5239. /* Generic
  5240. ------------------------------------------------------------------------------------------------------------------*/
  5241. // Generates the default HTML intro for any row. User classes should override
  5242. renderIntroHtml: function() {
  5243. },
  5244. // TODO: a generic method for dealing with <tr>, RTL, intro
  5245. // when increment internalApiVersion
  5246. // wrapTr (scheduler)
  5247. /* Utils
  5248. ------------------------------------------------------------------------------------------------------------------*/
  5249. // Applies the generic "intro" and "outro" HTML to the given cells.
  5250. // Intro means the leftmost cell when the calendar is LTR and the rightmost cell when RTL. Vice-versa for outro.
  5251. bookendCells: function(trEl) {
  5252. var introHtml = this.renderIntroHtml();
  5253. if (introHtml) {
  5254. if (this.isRTL) {
  5255. trEl.append(introHtml);
  5256. }
  5257. else {
  5258. trEl.prepend(introHtml);
  5259. }
  5260. }
  5261. }
  5262. };
  5263. ;;
  5264. /* A component that renders a grid of whole-days that runs horizontally. There can be multiple rows, one per week.
  5265. ----------------------------------------------------------------------------------------------------------------------*/
  5266. var DayGrid = FC.DayGrid = Grid.extend(DayTableMixin, {
  5267. numbersVisible: false, // should render a row for day/week numbers? set by outside view. TODO: make internal
  5268. bottomCoordPadding: 0, // hack for extending the hit area for the last row of the coordinate grid
  5269. rowEls: null, // set of fake row elements
  5270. cellEls: null, // set of whole-day elements comprising the row's background
  5271. helperEls: null, // set of cell skeleton elements for rendering the mock event "helper"
  5272. rowCoordCache: null,
  5273. colCoordCache: null,
  5274. // Renders the rows and columns into the component's `this.el`, which should already be assigned.
  5275. // isRigid determins whether the individual rows should ignore the contents and be a constant height.
  5276. // Relies on the view's colCnt and rowCnt. In the future, this component should probably be self-sufficient.
  5277. renderDates: function(isRigid) {
  5278. var view = this.view;
  5279. var rowCnt = this.rowCnt;
  5280. var colCnt = this.colCnt;
  5281. var html = '';
  5282. var row;
  5283. var col;
  5284. for (row = 0; row < rowCnt; row++) {
  5285. html += this.renderDayRowHtml(row, isRigid);
  5286. }
  5287. this.el.html(html);
  5288. this.rowEls = this.el.find('.fc-row');
  5289. this.cellEls = this.el.find('.fc-day, .fc-disabled-day');
  5290. this.rowCoordCache = new CoordCache({
  5291. els: this.rowEls,
  5292. isVertical: true
  5293. });
  5294. this.colCoordCache = new CoordCache({
  5295. els: this.cellEls.slice(0, this.colCnt), // only the first row
  5296. isHorizontal: true
  5297. });
  5298. // trigger dayRender with each cell's element
  5299. for (row = 0; row < rowCnt; row++) {
  5300. for (col = 0; col < colCnt; col++) {
  5301. view.publiclyTrigger(
  5302. 'dayRender',
  5303. null,
  5304. this.getCellDate(row, col),
  5305. this.getCellEl(row, col)
  5306. );
  5307. }
  5308. }
  5309. },
  5310. unrenderDates: function() {
  5311. this.removeSegPopover();
  5312. },
  5313. renderBusinessHours: function() {
  5314. var segs = this.buildBusinessHourSegs(true); // wholeDay=true
  5315. this.renderFill('businessHours', segs, 'bgevent');
  5316. },
  5317. unrenderBusinessHours: function() {
  5318. this.unrenderFill('businessHours');
  5319. },
  5320. // Generates the HTML for a single row, which is a div that wraps a table.
  5321. // `row` is the row number.
  5322. renderDayRowHtml: function(row, isRigid) {
  5323. var view = this.view;
  5324. var classes = [ 'fc-row', 'fc-week', view.widgetContentClass ];
  5325. if (isRigid) {
  5326. classes.push('fc-rigid');
  5327. }
  5328. return '' +
  5329. '<div class="' + classes.join(' ') + '">' +
  5330. '<div class="fc-bg">' +
  5331. '<table>' +
  5332. this.renderBgTrHtml(row) +
  5333. '</table>' +
  5334. '</div>' +
  5335. '<div class="fc-content-skeleton">' +
  5336. '<table>' +
  5337. (this.numbersVisible ?
  5338. '<thead>' +
  5339. this.renderNumberTrHtml(row) +
  5340. '</thead>' :
  5341. ''
  5342. ) +
  5343. '</table>' +
  5344. '</div>' +
  5345. '</div>';
  5346. },
  5347. /* Grid Number Rendering
  5348. ------------------------------------------------------------------------------------------------------------------*/
  5349. renderNumberTrHtml: function(row) {
  5350. return '' +
  5351. '<tr>' +
  5352. (this.isRTL ? '' : this.renderNumberIntroHtml(row)) +
  5353. this.renderNumberCellsHtml(row) +
  5354. (this.isRTL ? this.renderNumberIntroHtml(row) : '') +
  5355. '</tr>';
  5356. },
  5357. renderNumberIntroHtml: function(row) {
  5358. return this.renderIntroHtml();
  5359. },
  5360. renderNumberCellsHtml: function(row) {
  5361. var htmls = [];
  5362. var col, date;
  5363. for (col = 0; col < this.colCnt; col++) {
  5364. date = this.getCellDate(row, col);
  5365. htmls.push(this.renderNumberCellHtml(date));
  5366. }
  5367. return htmls.join('');
  5368. },
  5369. // Generates the HTML for the <td>s of the "number" row in the DayGrid's content skeleton.
  5370. // The number row will only exist if either day numbers or week numbers are turned on.
  5371. renderNumberCellHtml: function(date) {
  5372. var view = this.view;
  5373. var html = '';
  5374. var isDateValid = isDateWithinRange(date, view.activeRange); // TODO: called too frequently. cache somehow.
  5375. var isDayNumberVisible = view.dayNumbersVisible && isDateValid;
  5376. var classes;
  5377. var weekCalcFirstDoW;
  5378. if (!isDayNumberVisible && !view.cellWeekNumbersVisible) {
  5379. // no numbers in day cell (week number must be along the side)
  5380. return '<td/>'; // will create an empty space above events :(
  5381. }
  5382. classes = this.getDayClasses(date);
  5383. classes.unshift('fc-day-top');
  5384. if (view.cellWeekNumbersVisible) {
  5385. // To determine the day of week number change under ISO, we cannot
  5386. // rely on moment.js methods such as firstDayOfWeek() or weekday(),
  5387. // because they rely on the locale's dow (possibly overridden by
  5388. // our firstDay option), which may not be Monday. We cannot change
  5389. // dow, because that would affect the calendar start day as well.
  5390. if (date._locale._fullCalendar_weekCalc === 'ISO') {
  5391. weekCalcFirstDoW = 1; // Monday by ISO 8601 definition
  5392. }
  5393. else {
  5394. weekCalcFirstDoW = date._locale.firstDayOfWeek();
  5395. }
  5396. }
  5397. html += '<td class="' + classes.join(' ') + '"' +
  5398. (isDateValid ?
  5399. ' data-date="' + date.format() + '"' :
  5400. ''
  5401. ) +
  5402. '>';
  5403. if (view.cellWeekNumbersVisible && (date.day() == weekCalcFirstDoW)) {
  5404. html += view.buildGotoAnchorHtml(
  5405. { date: date, type: 'week' },
  5406. { 'class': 'fc-week-number' },
  5407. date.format('w') // inner HTML
  5408. );
  5409. }
  5410. if (isDayNumberVisible) {
  5411. html += view.buildGotoAnchorHtml(
  5412. date,
  5413. { 'class': 'fc-day-number' },
  5414. date.date() // inner HTML
  5415. );
  5416. }
  5417. html += '</td>';
  5418. return html;
  5419. },
  5420. /* Options
  5421. ------------------------------------------------------------------------------------------------------------------*/
  5422. // Computes a default event time formatting string if `timeFormat` is not explicitly defined
  5423. computeEventTimeFormat: function() {
  5424. return this.view.opt('extraSmallTimeFormat'); // like "6p" or "6:30p"
  5425. },
  5426. // Computes a default `displayEventEnd` value if one is not expliclty defined
  5427. computeDisplayEventEnd: function() {
  5428. return this.colCnt == 1; // we'll likely have space if there's only one day
  5429. },
  5430. /* Dates
  5431. ------------------------------------------------------------------------------------------------------------------*/
  5432. rangeUpdated: function() {
  5433. this.updateDayTable();
  5434. },
  5435. // Slices up the given span (unzoned start/end with other misc data) into an array of segments
  5436. spanToSegs: function(span) {
  5437. var segs = this.sliceRangeByRow(span);
  5438. var i, seg;
  5439. for (i = 0; i < segs.length; i++) {
  5440. seg = segs[i];
  5441. if (this.isRTL) {
  5442. seg.leftCol = this.daysPerRow - 1 - seg.lastRowDayIndex;
  5443. seg.rightCol = this.daysPerRow - 1 - seg.firstRowDayIndex;
  5444. }
  5445. else {
  5446. seg.leftCol = seg.firstRowDayIndex;
  5447. seg.rightCol = seg.lastRowDayIndex;
  5448. }
  5449. }
  5450. return segs;
  5451. },
  5452. /* Hit System
  5453. ------------------------------------------------------------------------------------------------------------------*/
  5454. prepareHits: function() {
  5455. this.colCoordCache.build();
  5456. this.rowCoordCache.build();
  5457. this.rowCoordCache.bottoms[this.rowCnt - 1] += this.bottomCoordPadding; // hack
  5458. },
  5459. releaseHits: function() {
  5460. this.colCoordCache.clear();
  5461. this.rowCoordCache.clear();
  5462. },
  5463. queryHit: function(leftOffset, topOffset) {
  5464. if (this.colCoordCache.isLeftInBounds(leftOffset) && this.rowCoordCache.isTopInBounds(topOffset)) {
  5465. var col = this.colCoordCache.getHorizontalIndex(leftOffset);
  5466. var row = this.rowCoordCache.getVerticalIndex(topOffset);
  5467. if (row != null && col != null) {
  5468. return this.getCellHit(row, col);
  5469. }
  5470. }
  5471. },
  5472. getHitSpan: function(hit) {
  5473. return this.getCellRange(hit.row, hit.col);
  5474. },
  5475. getHitEl: function(hit) {
  5476. return this.getCellEl(hit.row, hit.col);
  5477. },
  5478. /* Cell System
  5479. ------------------------------------------------------------------------------------------------------------------*/
  5480. // FYI: the first column is the leftmost column, regardless of date
  5481. getCellHit: function(row, col) {
  5482. return {
  5483. row: row,
  5484. col: col,
  5485. component: this, // needed unfortunately :(
  5486. left: this.colCoordCache.getLeftOffset(col),
  5487. right: this.colCoordCache.getRightOffset(col),
  5488. top: this.rowCoordCache.getTopOffset(row),
  5489. bottom: this.rowCoordCache.getBottomOffset(row)
  5490. };
  5491. },
  5492. getCellEl: function(row, col) {
  5493. return this.cellEls.eq(row * this.colCnt + col);
  5494. },
  5495. /* Event Drag Visualization
  5496. ------------------------------------------------------------------------------------------------------------------*/
  5497. // TODO: move to DayGrid.event, similar to what we did with Grid's drag methods
  5498. // Renders a visual indication of an event or external element being dragged.
  5499. // `eventLocation` has zoned start and end (optional)
  5500. renderDrag: function(eventLocation, seg) {
  5501. var eventSpans = this.eventToSpans(eventLocation);
  5502. var i;
  5503. // always render a highlight underneath
  5504. for (i = 0; i < eventSpans.length; i++) {
  5505. this.renderHighlight(eventSpans[i]);
  5506. }
  5507. // if a segment from the same calendar but another component is being dragged, render a helper event
  5508. if (seg && seg.component !== this) {
  5509. return this.renderEventLocationHelper(eventLocation, seg); // returns mock event elements
  5510. }
  5511. },
  5512. // Unrenders any visual indication of a hovering event
  5513. unrenderDrag: function() {
  5514. this.unrenderHighlight();
  5515. this.unrenderHelper();
  5516. },
  5517. /* Event Resize Visualization
  5518. ------------------------------------------------------------------------------------------------------------------*/
  5519. // Renders a visual indication of an event being resized
  5520. renderEventResize: function(eventLocation, seg) {
  5521. var eventSpans = this.eventToSpans(eventLocation);
  5522. var i;
  5523. for (i = 0; i < eventSpans.length; i++) {
  5524. this.renderHighlight(eventSpans[i]);
  5525. }
  5526. return this.renderEventLocationHelper(eventLocation, seg); // returns mock event elements
  5527. },
  5528. // Unrenders a visual indication of an event being resized
  5529. unrenderEventResize: function() {
  5530. this.unrenderHighlight();
  5531. this.unrenderHelper();
  5532. },
  5533. /* Event Helper
  5534. ------------------------------------------------------------------------------------------------------------------*/
  5535. // Renders a mock "helper" event. `sourceSeg` is the associated internal segment object. It can be null.
  5536. renderHelper: function(event, sourceSeg) {
  5537. var helperNodes = [];
  5538. var segs = this.eventToSegs(event);
  5539. var rowStructs;
  5540. segs = this.renderFgSegEls(segs); // assigns each seg's el and returns a subset of segs that were rendered
  5541. rowStructs = this.renderSegRows(segs);
  5542. // inject each new event skeleton into each associated row
  5543. this.rowEls.each(function(row, rowNode) {
  5544. var rowEl = $(rowNode); // the .fc-row
  5545. var skeletonEl = $('<div class="fc-helper-skeleton"><table/></div>'); // will be absolutely positioned
  5546. var skeletonTop;
  5547. // If there is an original segment, match the top position. Otherwise, put it at the row's top level
  5548. if (sourceSeg && sourceSeg.row === row) {
  5549. skeletonTop = sourceSeg.el.position().top;
  5550. }
  5551. else {
  5552. skeletonTop = rowEl.find('.fc-content-skeleton tbody').position().top;
  5553. }
  5554. skeletonEl.css('top', skeletonTop)
  5555. .find('table')
  5556. .append(rowStructs[row].tbodyEl);
  5557. rowEl.append(skeletonEl);
  5558. helperNodes.push(skeletonEl[0]);
  5559. });
  5560. return ( // must return the elements rendered
  5561. this.helperEls = $(helperNodes) // array -> jQuery set
  5562. );
  5563. },
  5564. // Unrenders any visual indication of a mock helper event
  5565. unrenderHelper: function() {
  5566. if (this.helperEls) {
  5567. this.helperEls.remove();
  5568. this.helperEls = null;
  5569. }
  5570. },
  5571. /* Fill System (highlight, background events, business hours)
  5572. ------------------------------------------------------------------------------------------------------------------*/
  5573. fillSegTag: 'td', // override the default tag name
  5574. // Renders a set of rectangles over the given segments of days.
  5575. // Only returns segments that successfully rendered.
  5576. renderFill: function(type, segs, className) {
  5577. var nodes = [];
  5578. var i, seg;
  5579. var skeletonEl;
  5580. segs = this.renderFillSegEls(type, segs); // assignes `.el` to each seg. returns successfully rendered segs
  5581. for (i = 0; i < segs.length; i++) {
  5582. seg = segs[i];
  5583. skeletonEl = this.renderFillRow(type, seg, className);
  5584. this.rowEls.eq(seg.row).append(skeletonEl);
  5585. nodes.push(skeletonEl[0]);
  5586. }
  5587. this.elsByFill[type] = $(nodes);
  5588. return segs;
  5589. },
  5590. // Generates the HTML needed for one row of a fill. Requires the seg's el to be rendered.
  5591. renderFillRow: function(type, seg, className) {
  5592. var colCnt = this.colCnt;
  5593. var startCol = seg.leftCol;
  5594. var endCol = seg.rightCol + 1;
  5595. var skeletonEl;
  5596. var trEl;
  5597. className = className || type.toLowerCase();
  5598. skeletonEl = $(
  5599. '<div class="fc-' + className + '-skeleton">' +
  5600. '<table><tr/></table>' +
  5601. '</div>'
  5602. );
  5603. trEl = skeletonEl.find('tr');
  5604. if (startCol > 0) {
  5605. trEl.append('<td colspan="' + startCol + '"/>');
  5606. }
  5607. trEl.append(
  5608. seg.el.attr('colspan', endCol - startCol)
  5609. );
  5610. if (endCol < colCnt) {
  5611. trEl.append('<td colspan="' + (colCnt - endCol) + '"/>');
  5612. }
  5613. this.bookendCells(trEl);
  5614. return skeletonEl;
  5615. }
  5616. });
  5617. ;;
  5618. /* Event-rendering methods for the DayGrid class
  5619. ----------------------------------------------------------------------------------------------------------------------*/
  5620. DayGrid.mixin({
  5621. rowStructs: null, // an array of objects, each holding information about a row's foreground event-rendering
  5622. // Unrenders all events currently rendered on the grid
  5623. unrenderEvents: function() {
  5624. this.removeSegPopover(); // removes the "more.." events popover
  5625. Grid.prototype.unrenderEvents.apply(this, arguments); // calls the super-method
  5626. },
  5627. // Retrieves all rendered segment objects currently rendered on the grid
  5628. getEventSegs: function() {
  5629. return Grid.prototype.getEventSegs.call(this) // get the segments from the super-method
  5630. .concat(this.popoverSegs || []); // append the segments from the "more..." popover
  5631. },
  5632. // Renders the given background event segments onto the grid
  5633. renderBgSegs: function(segs) {
  5634. // don't render timed background events
  5635. var allDaySegs = $.grep(segs, function(seg) {
  5636. return seg.event.allDay;
  5637. });
  5638. return Grid.prototype.renderBgSegs.call(this, allDaySegs); // call the super-method
  5639. },
  5640. // Renders the given foreground event segments onto the grid
  5641. renderFgSegs: function(segs) {
  5642. var rowStructs;
  5643. // render an `.el` on each seg
  5644. // returns a subset of the segs. segs that were actually rendered
  5645. segs = this.renderFgSegEls(segs);
  5646. rowStructs = this.rowStructs = this.renderSegRows(segs);
  5647. // append to each row's content skeleton
  5648. this.rowEls.each(function(i, rowNode) {
  5649. $(rowNode).find('.fc-content-skeleton > table').append(
  5650. rowStructs[i].tbodyEl
  5651. );
  5652. });
  5653. return segs; // return only the segs that were actually rendered
  5654. },
  5655. // Unrenders all currently rendered foreground event segments
  5656. unrenderFgSegs: function() {
  5657. var rowStructs = this.rowStructs || [];
  5658. var rowStruct;
  5659. while ((rowStruct = rowStructs.pop())) {
  5660. rowStruct.tbodyEl.remove();
  5661. }
  5662. this.rowStructs = null;
  5663. },
  5664. // Uses the given events array to generate <tbody> elements that should be appended to each row's content skeleton.
  5665. // Returns an array of rowStruct objects (see the bottom of `renderSegRow`).
  5666. // PRECONDITION: each segment shoud already have a rendered and assigned `.el`
  5667. renderSegRows: function(segs) {
  5668. var rowStructs = [];
  5669. var segRows;
  5670. var row;
  5671. segRows = this.groupSegRows(segs); // group into nested arrays
  5672. // iterate each row of segment groupings
  5673. for (row = 0; row < segRows.length; row++) {
  5674. rowStructs.push(
  5675. this.renderSegRow(row, segRows[row])
  5676. );
  5677. }
  5678. return rowStructs;
  5679. },
  5680. // Builds the HTML to be used for the default element for an individual segment
  5681. fgSegHtml: function(seg, disableResizing) {
  5682. var view = this.view;
  5683. var event = seg.event;
  5684. var isDraggable = view.isEventDraggable(event);
  5685. var isResizableFromStart = !disableResizing && event.allDay &&
  5686. seg.isStart && view.isEventResizableFromStart(event);
  5687. var isResizableFromEnd = !disableResizing && event.allDay &&
  5688. seg.isEnd && view.isEventResizableFromEnd(event);
  5689. var classes = this.getSegClasses(seg, isDraggable, isResizableFromStart || isResizableFromEnd);
  5690. var skinCss = cssToStr(this.getSegSkinCss(seg));
  5691. var timeHtml = '';
  5692. var timeText;
  5693. var titleHtml;
  5694. classes.unshift('fc-day-grid-event', 'fc-h-event');
  5695. // Only display a timed events time if it is the starting segment
  5696. if (seg.isStart) {
  5697. timeText = this.getEventTimeText(event);
  5698. if (timeText) {
  5699. timeHtml = '<span class="fc-time">' + htmlEscape(timeText) + '</span>';
  5700. }
  5701. }
  5702. titleHtml =
  5703. '<span class="fc-title">' +
  5704. (htmlEscape(event.title || '') || '&nbsp;') + // we always want one line of height
  5705. '</span>';
  5706. return '<a class="' + classes.join(' ') + '"' +
  5707. (event.url ?
  5708. ' href="' + htmlEscape(event.url) + '"' :
  5709. ''
  5710. ) +
  5711. (skinCss ?
  5712. ' style="' + skinCss + '"' :
  5713. ''
  5714. ) +
  5715. '>' +
  5716. '<div class="fc-content">' +
  5717. (this.isRTL ?
  5718. titleHtml + ' ' + timeHtml : // put a natural space in between
  5719. timeHtml + ' ' + titleHtml //
  5720. ) +
  5721. '</div>' +
  5722. (isResizableFromStart ?
  5723. '<div class="fc-resizer fc-start-resizer" />' :
  5724. ''
  5725. ) +
  5726. (isResizableFromEnd ?
  5727. '<div class="fc-resizer fc-end-resizer" />' :
  5728. ''
  5729. ) +
  5730. '</a>';
  5731. },
  5732. // Given a row # and an array of segments all in the same row, render a <tbody> element, a skeleton that contains
  5733. // the segments. Returns object with a bunch of internal data about how the render was calculated.
  5734. // NOTE: modifies rowSegs
  5735. renderSegRow: function(row, rowSegs) {
  5736. var colCnt = this.colCnt;
  5737. var segLevels = this.buildSegLevels(rowSegs); // group into sub-arrays of levels
  5738. var levelCnt = Math.max(1, segLevels.length); // ensure at least one level
  5739. var tbody = $('<tbody/>');
  5740. var segMatrix = []; // lookup for which segments are rendered into which level+col cells
  5741. var cellMatrix = []; // lookup for all <td> elements of the level+col matrix
  5742. var loneCellMatrix = []; // lookup for <td> elements that only take up a single column
  5743. var i, levelSegs;
  5744. var col;
  5745. var tr;
  5746. var j, seg;
  5747. var td;
  5748. // populates empty cells from the current column (`col`) to `endCol`
  5749. function emptyCellsUntil(endCol) {
  5750. while (col < endCol) {
  5751. // try to grab a cell from the level above and extend its rowspan. otherwise, create a fresh cell
  5752. td = (loneCellMatrix[i - 1] || [])[col];
  5753. if (td) {
  5754. td.attr(
  5755. 'rowspan',
  5756. parseInt(td.attr('rowspan') || 1, 10) + 1
  5757. );
  5758. }
  5759. else {
  5760. td = $('<td/>');
  5761. tr.append(td);
  5762. }
  5763. cellMatrix[i][col] = td;
  5764. loneCellMatrix[i][col] = td;
  5765. col++;
  5766. }
  5767. }
  5768. for (i = 0; i < levelCnt; i++) { // iterate through all levels
  5769. levelSegs = segLevels[i];
  5770. col = 0;
  5771. tr = $('<tr/>');
  5772. segMatrix.push([]);
  5773. cellMatrix.push([]);
  5774. loneCellMatrix.push([]);
  5775. // levelCnt might be 1 even though there are no actual levels. protect against this.
  5776. // this single empty row is useful for styling.
  5777. if (levelSegs) {
  5778. for (j = 0; j < levelSegs.length; j++) { // iterate through segments in level
  5779. seg = levelSegs[j];
  5780. emptyCellsUntil(seg.leftCol);
  5781. // create a container that occupies or more columns. append the event element.
  5782. td = $('<td class="fc-event-container"/>').append(seg.el);
  5783. if (seg.leftCol != seg.rightCol) {
  5784. td.attr('colspan', seg.rightCol - seg.leftCol + 1);
  5785. }
  5786. else { // a single-column segment
  5787. loneCellMatrix[i][col] = td;
  5788. }
  5789. while (col <= seg.rightCol) {
  5790. cellMatrix[i][col] = td;
  5791. segMatrix[i][col] = seg;
  5792. col++;
  5793. }
  5794. tr.append(td);
  5795. }
  5796. }
  5797. emptyCellsUntil(colCnt); // finish off the row
  5798. this.bookendCells(tr);
  5799. tbody.append(tr);
  5800. }
  5801. return { // a "rowStruct"
  5802. row: row, // the row number
  5803. tbodyEl: tbody,
  5804. cellMatrix: cellMatrix,
  5805. segMatrix: segMatrix,
  5806. segLevels: segLevels,
  5807. segs: rowSegs
  5808. };
  5809. },
  5810. // Stacks a flat array of segments, which are all assumed to be in the same row, into subarrays of vertical levels.
  5811. // NOTE: modifies segs
  5812. buildSegLevels: function(segs) {
  5813. var levels = [];
  5814. var i, seg;
  5815. var j;
  5816. // Give preference to elements with certain criteria, so they have
  5817. // a chance to be closer to the top.
  5818. this.sortEventSegs(segs);
  5819. for (i = 0; i < segs.length; i++) {
  5820. seg = segs[i];
  5821. // loop through levels, starting with the topmost, until the segment doesn't collide with other segments
  5822. for (j = 0; j < levels.length; j++) {
  5823. if (!isDaySegCollision(seg, levels[j])) {
  5824. break;
  5825. }
  5826. }
  5827. // `j` now holds the desired subrow index
  5828. seg.level = j;
  5829. // create new level array if needed and append segment
  5830. (levels[j] || (levels[j] = [])).push(seg);
  5831. }
  5832. // order segments left-to-right. very important if calendar is RTL
  5833. for (j = 0; j < levels.length; j++) {
  5834. levels[j].sort(compareDaySegCols);
  5835. }
  5836. return levels;
  5837. },
  5838. // Given a flat array of segments, return an array of sub-arrays, grouped by each segment's row
  5839. groupSegRows: function(segs) {
  5840. var segRows = [];
  5841. var i;
  5842. for (i = 0; i < this.rowCnt; i++) {
  5843. segRows.push([]);
  5844. }
  5845. for (i = 0; i < segs.length; i++) {
  5846. segRows[segs[i].row].push(segs[i]);
  5847. }
  5848. return segRows;
  5849. }
  5850. });
  5851. // Computes whether two segments' columns collide. They are assumed to be in the same row.
  5852. function isDaySegCollision(seg, otherSegs) {
  5853. var i, otherSeg;
  5854. for (i = 0; i < otherSegs.length; i++) {
  5855. otherSeg = otherSegs[i];
  5856. if (
  5857. otherSeg.leftCol <= seg.rightCol &&
  5858. otherSeg.rightCol >= seg.leftCol
  5859. ) {
  5860. return true;
  5861. }
  5862. }
  5863. return false;
  5864. }
  5865. // A cmp function for determining the leftmost event
  5866. function compareDaySegCols(a, b) {
  5867. return a.leftCol - b.leftCol;
  5868. }
  5869. ;;
  5870. /* Methods relate to limiting the number events for a given day on a DayGrid
  5871. ----------------------------------------------------------------------------------------------------------------------*/
  5872. // NOTE: all the segs being passed around in here are foreground segs
  5873. DayGrid.mixin({
  5874. segPopover: null, // the Popover that holds events that can't fit in a cell. null when not visible
  5875. popoverSegs: null, // an array of segment objects that the segPopover holds. null when not visible
  5876. removeSegPopover: function() {
  5877. if (this.segPopover) {
  5878. this.segPopover.hide(); // in handler, will call segPopover's removeElement
  5879. }
  5880. },
  5881. // Limits the number of "levels" (vertically stacking layers of events) for each row of the grid.
  5882. // `levelLimit` can be false (don't limit), a number, or true (should be computed).
  5883. limitRows: function(levelLimit) {
  5884. var rowStructs = this.rowStructs || [];
  5885. var row; // row #
  5886. var rowLevelLimit;
  5887. for (row = 0; row < rowStructs.length; row++) {
  5888. this.unlimitRow(row);
  5889. if (!levelLimit) {
  5890. rowLevelLimit = false;
  5891. }
  5892. else if (typeof levelLimit === 'number') {
  5893. rowLevelLimit = levelLimit;
  5894. }
  5895. else {
  5896. rowLevelLimit = this.computeRowLevelLimit(row);
  5897. }
  5898. if (rowLevelLimit !== false) {
  5899. this.limitRow(row, rowLevelLimit);
  5900. }
  5901. }
  5902. },
  5903. // Computes the number of levels a row will accomodate without going outside its bounds.
  5904. // Assumes the row is "rigid" (maintains a constant height regardless of what is inside).
  5905. // `row` is the row number.
  5906. computeRowLevelLimit: function(row) {
  5907. var rowEl = this.rowEls.eq(row); // the containing "fake" row div
  5908. var rowHeight = rowEl.height(); // TODO: cache somehow?
  5909. var trEls = this.rowStructs[row].tbodyEl.children();
  5910. var i, trEl;
  5911. var trHeight;
  5912. function iterInnerHeights(i, childNode) {
  5913. trHeight = Math.max(trHeight, $(childNode).outerHeight());
  5914. }
  5915. // Reveal one level <tr> at a time and stop when we find one out of bounds
  5916. for (i = 0; i < trEls.length; i++) {
  5917. trEl = trEls.eq(i).removeClass('fc-limited'); // reset to original state (reveal)
  5918. // with rowspans>1 and IE8, trEl.outerHeight() would return the height of the largest cell,
  5919. // so instead, find the tallest inner content element.
  5920. trHeight = 0;
  5921. trEl.find('> td > :first-child').each(iterInnerHeights);
  5922. if (trEl.position().top + trHeight > rowHeight) {
  5923. return i;
  5924. }
  5925. }
  5926. return false; // should not limit at all
  5927. },
  5928. // Limits the given grid row to the maximum number of levels and injects "more" links if necessary.
  5929. // `row` is the row number.
  5930. // `levelLimit` is a number for the maximum (inclusive) number of levels allowed.
  5931. limitRow: function(row, levelLimit) {
  5932. var _this = this;
  5933. var rowStruct = this.rowStructs[row];
  5934. var moreNodes = []; // array of "more" <a> links and <td> DOM nodes
  5935. var col = 0; // col #, left-to-right (not chronologically)
  5936. var levelSegs; // array of segment objects in the last allowable level, ordered left-to-right
  5937. var cellMatrix; // a matrix (by level, then column) of all <td> jQuery elements in the row
  5938. var limitedNodes; // array of temporarily hidden level <tr> and segment <td> DOM nodes
  5939. var i, seg;
  5940. var segsBelow; // array of segment objects below `seg` in the current `col`
  5941. var totalSegsBelow; // total number of segments below `seg` in any of the columns `seg` occupies
  5942. var colSegsBelow; // array of segment arrays, below seg, one for each column (offset from segs's first column)
  5943. var td, rowspan;
  5944. var segMoreNodes; // array of "more" <td> cells that will stand-in for the current seg's cell
  5945. var j;
  5946. var moreTd, moreWrap, moreLink;
  5947. // Iterates through empty level cells and places "more" links inside if need be
  5948. function emptyCellsUntil(endCol) { // goes from current `col` to `endCol`
  5949. while (col < endCol) {
  5950. segsBelow = _this.getCellSegs(row, col, levelLimit);
  5951. if (segsBelow.length) {
  5952. td = cellMatrix[levelLimit - 1][col];
  5953. moreLink = _this.renderMoreLink(row, col, segsBelow);
  5954. moreWrap = $('<div/>').append(moreLink);
  5955. td.append(moreWrap);
  5956. moreNodes.push(moreWrap[0]);
  5957. }
  5958. col++;
  5959. }
  5960. }
  5961. if (levelLimit && levelLimit < rowStruct.segLevels.length) { // is it actually over the limit?
  5962. levelSegs = rowStruct.segLevels[levelLimit - 1];
  5963. cellMatrix = rowStruct.cellMatrix;
  5964. limitedNodes = rowStruct.tbodyEl.children().slice(levelLimit) // get level <tr> elements past the limit
  5965. .addClass('fc-limited').get(); // hide elements and get a simple DOM-nodes array
  5966. // iterate though segments in the last allowable level
  5967. for (i = 0; i < levelSegs.length; i++) {
  5968. seg = levelSegs[i];
  5969. emptyCellsUntil(seg.leftCol); // process empty cells before the segment
  5970. // determine *all* segments below `seg` that occupy the same columns
  5971. colSegsBelow = [];
  5972. totalSegsBelow = 0;
  5973. while (col <= seg.rightCol) {
  5974. segsBelow = this.getCellSegs(row, col, levelLimit);
  5975. colSegsBelow.push(segsBelow);
  5976. totalSegsBelow += segsBelow.length;
  5977. col++;
  5978. }
  5979. if (totalSegsBelow) { // do we need to replace this segment with one or many "more" links?
  5980. td = cellMatrix[levelLimit - 1][seg.leftCol]; // the segment's parent cell
  5981. rowspan = td.attr('rowspan') || 1;
  5982. segMoreNodes = [];
  5983. // make a replacement <td> for each column the segment occupies. will be one for each colspan
  5984. for (j = 0; j < colSegsBelow.length; j++) {
  5985. moreTd = $('<td class="fc-more-cell"/>').attr('rowspan', rowspan);
  5986. segsBelow = colSegsBelow[j];
  5987. moreLink = this.renderMoreLink(
  5988. row,
  5989. seg.leftCol + j,
  5990. [ seg ].concat(segsBelow) // count seg as hidden too
  5991. );
  5992. moreWrap = $('<div/>').append(moreLink);
  5993. moreTd.append(moreWrap);
  5994. segMoreNodes.push(moreTd[0]);
  5995. moreNodes.push(moreTd[0]);
  5996. }
  5997. td.addClass('fc-limited').after($(segMoreNodes)); // hide original <td> and inject replacements
  5998. limitedNodes.push(td[0]);
  5999. }
  6000. }
  6001. emptyCellsUntil(this.colCnt); // finish off the level
  6002. rowStruct.moreEls = $(moreNodes); // for easy undoing later
  6003. rowStruct.limitedEls = $(limitedNodes); // for easy undoing later
  6004. }
  6005. },
  6006. // Reveals all levels and removes all "more"-related elements for a grid's row.
  6007. // `row` is a row number.
  6008. unlimitRow: function(row) {
  6009. var rowStruct = this.rowStructs[row];
  6010. if (rowStruct.moreEls) {
  6011. rowStruct.moreEls.remove();
  6012. rowStruct.moreEls = null;
  6013. }
  6014. if (rowStruct.limitedEls) {
  6015. rowStruct.limitedEls.removeClass('fc-limited');
  6016. rowStruct.limitedEls = null;
  6017. }
  6018. },
  6019. // Renders an <a> element that represents hidden event element for a cell.
  6020. // Responsible for attaching click handler as well.
  6021. renderMoreLink: function(row, col, hiddenSegs) {
  6022. var _this = this;
  6023. var view = this.view;
  6024. return $('<a class="fc-more"/>')
  6025. .text(
  6026. this.getMoreLinkText(hiddenSegs.length)
  6027. )
  6028. .on('click', function(ev) {
  6029. var clickOption = view.opt('eventLimitClick');
  6030. var date = _this.getCellDate(row, col);
  6031. var moreEl = $(this);
  6032. var dayEl = _this.getCellEl(row, col);
  6033. var allSegs = _this.getCellSegs(row, col);
  6034. // rescope the segments to be within the cell's date
  6035. var reslicedAllSegs = _this.resliceDaySegs(allSegs, date);
  6036. var reslicedHiddenSegs = _this.resliceDaySegs(hiddenSegs, date);
  6037. if (typeof clickOption === 'function') {
  6038. // the returned value can be an atomic option
  6039. clickOption = view.publiclyTrigger('eventLimitClick', null, {
  6040. date: date,
  6041. dayEl: dayEl,
  6042. moreEl: moreEl,
  6043. segs: reslicedAllSegs,
  6044. hiddenSegs: reslicedHiddenSegs
  6045. }, ev);
  6046. }
  6047. if (clickOption === 'popover') {
  6048. _this.showSegPopover(row, col, moreEl, reslicedAllSegs);
  6049. }
  6050. else if (typeof clickOption === 'string') { // a view name
  6051. view.calendar.zoomTo(date, clickOption);
  6052. }
  6053. });
  6054. },
  6055. // Reveals the popover that displays all events within a cell
  6056. showSegPopover: function(row, col, moreLink, segs) {
  6057. var _this = this;
  6058. var view = this.view;
  6059. var moreWrap = moreLink.parent(); // the <div> wrapper around the <a>
  6060. var topEl; // the element we want to match the top coordinate of
  6061. var options;
  6062. if (this.rowCnt == 1) {
  6063. topEl = view.el; // will cause the popover to cover any sort of header
  6064. }
  6065. else {
  6066. topEl = this.rowEls.eq(row); // will align with top of row
  6067. }
  6068. options = {
  6069. className: 'fc-more-popover',
  6070. content: this.renderSegPopoverContent(row, col, segs),
  6071. parentEl: this.view.el, // attach to root of view. guarantees outside of scrollbars.
  6072. top: topEl.offset().top,
  6073. autoHide: true, // when the user clicks elsewhere, hide the popover
  6074. viewportConstrain: view.opt('popoverViewportConstrain'),
  6075. hide: function() {
  6076. // kill everything when the popover is hidden
  6077. // notify events to be removed
  6078. if (_this.popoverSegs) {
  6079. var seg;
  6080. for (var i = 0; i < _this.popoverSegs.length; ++i) {
  6081. seg = _this.popoverSegs[i];
  6082. view.publiclyTrigger('eventDestroy', seg.event, seg.event, seg.el);
  6083. }
  6084. }
  6085. _this.segPopover.removeElement();
  6086. _this.segPopover = null;
  6087. _this.popoverSegs = null;
  6088. }
  6089. };
  6090. // Determine horizontal coordinate.
  6091. // We use the moreWrap instead of the <td> to avoid border confusion.
  6092. if (this.isRTL) {
  6093. options.right = moreWrap.offset().left + moreWrap.outerWidth() + 1; // +1 to be over cell border
  6094. }
  6095. else {
  6096. options.left = moreWrap.offset().left - 1; // -1 to be over cell border
  6097. }
  6098. this.segPopover = new Popover(options);
  6099. this.segPopover.show();
  6100. // the popover doesn't live within the grid's container element, and thus won't get the event
  6101. // delegated-handlers for free. attach event-related handlers to the popover.
  6102. this.bindSegHandlersToEl(this.segPopover.el);
  6103. },
  6104. // Builds the inner DOM contents of the segment popover
  6105. renderSegPopoverContent: function(row, col, segs) {
  6106. var view = this.view;
  6107. var isTheme = view.opt('theme');
  6108. var title = this.getCellDate(row, col).format(view.opt('dayPopoverFormat'));
  6109. var content = $(
  6110. '<div class="fc-header ' + view.widgetHeaderClass + '">' +
  6111. '<span class="fc-close ' +
  6112. (isTheme ? 'ui-icon ui-icon-closethick' : 'fc-icon fc-icon-x') +
  6113. '"></span>' +
  6114. '<span class="fc-title">' +
  6115. htmlEscape(title) +
  6116. '</span>' +
  6117. '<div class="fc-clear"/>' +
  6118. '</div>' +
  6119. '<div class="fc-body ' + view.widgetContentClass + '">' +
  6120. '<div class="fc-event-container"></div>' +
  6121. '</div>'
  6122. );
  6123. var segContainer = content.find('.fc-event-container');
  6124. var i;
  6125. // render each seg's `el` and only return the visible segs
  6126. segs = this.renderFgSegEls(segs, true); // disableResizing=true
  6127. this.popoverSegs = segs;
  6128. for (i = 0; i < segs.length; i++) {
  6129. // because segments in the popover are not part of a grid coordinate system, provide a hint to any
  6130. // grids that want to do drag-n-drop about which cell it came from
  6131. this.hitsNeeded();
  6132. segs[i].hit = this.getCellHit(row, col);
  6133. this.hitsNotNeeded();
  6134. segContainer.append(segs[i].el);
  6135. }
  6136. return content;
  6137. },
  6138. // Given the events within an array of segment objects, reslice them to be in a single day
  6139. resliceDaySegs: function(segs, dayDate) {
  6140. // build an array of the original events
  6141. var events = $.map(segs, function(seg) {
  6142. return seg.event;
  6143. });
  6144. var dayStart = dayDate.clone();
  6145. var dayEnd = dayStart.clone().add(1, 'days');
  6146. var dayRange = { start: dayStart, end: dayEnd };
  6147. // slice the events with a custom slicing function
  6148. segs = this.eventsToSegs(
  6149. events,
  6150. function(range) {
  6151. var seg = intersectRanges(range, dayRange); // undefind if no intersection
  6152. return seg ? [ seg ] : []; // must return an array of segments
  6153. }
  6154. );
  6155. // force an order because eventsToSegs doesn't guarantee one
  6156. this.sortEventSegs(segs);
  6157. return segs;
  6158. },
  6159. // Generates the text that should be inside a "more" link, given the number of events it represents
  6160. getMoreLinkText: function(num) {
  6161. var opt = this.view.opt('eventLimitText');
  6162. if (typeof opt === 'function') {
  6163. return opt(num);
  6164. }
  6165. else {
  6166. return '+' + num + ' ' + opt;
  6167. }
  6168. },
  6169. // Returns segments within a given cell.
  6170. // If `startLevel` is specified, returns only events including and below that level. Otherwise returns all segs.
  6171. getCellSegs: function(row, col, startLevel) {
  6172. var segMatrix = this.rowStructs[row].segMatrix;
  6173. var level = startLevel || 0;
  6174. var segs = [];
  6175. var seg;
  6176. while (level < segMatrix.length) {
  6177. seg = segMatrix[level][col];
  6178. if (seg) {
  6179. segs.push(seg);
  6180. }
  6181. level++;
  6182. }
  6183. return segs;
  6184. }
  6185. });
  6186. ;;
  6187. /* A component that renders one or more columns of vertical time slots
  6188. ----------------------------------------------------------------------------------------------------------------------*/
  6189. // We mixin DayTable, even though there is only a single row of days
  6190. var TimeGrid = FC.TimeGrid = Grid.extend(DayTableMixin, {
  6191. slotDuration: null, // duration of a "slot", a distinct time segment on given day, visualized by lines
  6192. snapDuration: null, // granularity of time for dragging and selecting
  6193. snapsPerSlot: null,
  6194. labelFormat: null, // formatting string for times running along vertical axis
  6195. labelInterval: null, // duration of how often a label should be displayed for a slot
  6196. colEls: null, // cells elements in the day-row background
  6197. slatContainerEl: null, // div that wraps all the slat rows
  6198. slatEls: null, // elements running horizontally across all columns
  6199. nowIndicatorEls: null,
  6200. colCoordCache: null,
  6201. slatCoordCache: null,
  6202. constructor: function() {
  6203. Grid.apply(this, arguments); // call the super-constructor
  6204. this.processOptions();
  6205. },
  6206. // Renders the time grid into `this.el`, which should already be assigned.
  6207. // Relies on the view's colCnt. In the future, this component should probably be self-sufficient.
  6208. renderDates: function() {
  6209. this.el.html(this.renderHtml());
  6210. this.colEls = this.el.find('.fc-day, .fc-disabled-day');
  6211. this.slatContainerEl = this.el.find('.fc-slats');
  6212. this.slatEls = this.slatContainerEl.find('tr');
  6213. this.colCoordCache = new CoordCache({
  6214. els: this.colEls,
  6215. isHorizontal: true
  6216. });
  6217. this.slatCoordCache = new CoordCache({
  6218. els: this.slatEls,
  6219. isVertical: true
  6220. });
  6221. this.renderContentSkeleton();
  6222. },
  6223. // Renders the basic HTML skeleton for the grid
  6224. renderHtml: function() {
  6225. return '' +
  6226. '<div class="fc-bg">' +
  6227. '<table>' +
  6228. this.renderBgTrHtml(0) + // row=0
  6229. '</table>' +
  6230. '</div>' +
  6231. '<div class="fc-slats">' +
  6232. '<table>' +
  6233. this.renderSlatRowHtml() +
  6234. '</table>' +
  6235. '</div>';
  6236. },
  6237. // Generates the HTML for the horizontal "slats" that run width-wise. Has a time axis on a side. Depends on RTL.
  6238. renderSlatRowHtml: function() {
  6239. var view = this.view;
  6240. var isRTL = this.isRTL;
  6241. var html = '';
  6242. var slotTime = moment.duration(+this.view.minTime); // wish there was .clone() for durations
  6243. var slotDate; // will be on the view's first day, but we only care about its time
  6244. var isLabeled;
  6245. var axisHtml;
  6246. // Calculate the time for each slot
  6247. while (slotTime < this.view.maxTime) {
  6248. slotDate = this.start.clone().time(slotTime);
  6249. isLabeled = isInt(divideDurationByDuration(slotTime, this.labelInterval));
  6250. axisHtml =
  6251. '<td class="fc-axis fc-time ' + view.widgetContentClass + '" ' + view.axisStyleAttr() + '>' +
  6252. (isLabeled ?
  6253. '<span>' + // for matchCellWidths
  6254. htmlEscape(slotDate.format(this.labelFormat)) +
  6255. '</span>' :
  6256. ''
  6257. ) +
  6258. '</td>';
  6259. html +=
  6260. '<tr data-time="' + slotDate.format('HH:mm:ss') + '"' +
  6261. (isLabeled ? '' : ' class="fc-minor"') +
  6262. '>' +
  6263. (!isRTL ? axisHtml : '') +
  6264. '<td class="' + view.widgetContentClass + '"/>' +
  6265. (isRTL ? axisHtml : '') +
  6266. "</tr>";
  6267. slotTime.add(this.slotDuration);
  6268. }
  6269. return html;
  6270. },
  6271. /* Options
  6272. ------------------------------------------------------------------------------------------------------------------*/
  6273. // Parses various options into properties of this object
  6274. processOptions: function() {
  6275. var view = this.view;
  6276. var slotDuration = view.opt('slotDuration');
  6277. var snapDuration = view.opt('snapDuration');
  6278. var input;
  6279. slotDuration = moment.duration(slotDuration);
  6280. snapDuration = snapDuration ? moment.duration(snapDuration) : slotDuration;
  6281. this.slotDuration = slotDuration;
  6282. this.snapDuration = snapDuration;
  6283. this.snapsPerSlot = slotDuration / snapDuration; // TODO: ensure an integer multiple?
  6284. this.minResizeDuration = snapDuration; // hack
  6285. // might be an array value (for TimelineView).
  6286. // if so, getting the most granular entry (the last one probably).
  6287. input = view.opt('slotLabelFormat');
  6288. if ($.isArray(input)) {
  6289. input = input[input.length - 1];
  6290. }
  6291. this.labelFormat =
  6292. input ||
  6293. view.opt('smallTimeFormat'); // the computed default
  6294. input = view.opt('slotLabelInterval');
  6295. this.labelInterval = input ?
  6296. moment.duration(input) :
  6297. this.computeLabelInterval(slotDuration);
  6298. },
  6299. // Computes an automatic value for slotLabelInterval
  6300. computeLabelInterval: function(slotDuration) {
  6301. var i;
  6302. var labelInterval;
  6303. var slotsPerLabel;
  6304. // find the smallest stock label interval that results in more than one slots-per-label
  6305. for (i = AGENDA_STOCK_SUB_DURATIONS.length - 1; i >= 0; i--) {
  6306. labelInterval = moment.duration(AGENDA_STOCK_SUB_DURATIONS[i]);
  6307. slotsPerLabel = divideDurationByDuration(labelInterval, slotDuration);
  6308. if (isInt(slotsPerLabel) && slotsPerLabel > 1) {
  6309. return labelInterval;
  6310. }
  6311. }
  6312. return moment.duration(slotDuration); // fall back. clone
  6313. },
  6314. // Computes a default event time formatting string if `timeFormat` is not explicitly defined
  6315. computeEventTimeFormat: function() {
  6316. return this.view.opt('noMeridiemTimeFormat'); // like "6:30" (no AM/PM)
  6317. },
  6318. // Computes a default `displayEventEnd` value if one is not expliclty defined
  6319. computeDisplayEventEnd: function() {
  6320. return true;
  6321. },
  6322. /* Hit System
  6323. ------------------------------------------------------------------------------------------------------------------*/
  6324. prepareHits: function() {
  6325. this.colCoordCache.build();
  6326. this.slatCoordCache.build();
  6327. },
  6328. releaseHits: function() {
  6329. this.colCoordCache.clear();
  6330. // NOTE: don't clear slatCoordCache because we rely on it for computeTimeTop
  6331. },
  6332. queryHit: function(leftOffset, topOffset) {
  6333. var snapsPerSlot = this.snapsPerSlot;
  6334. var colCoordCache = this.colCoordCache;
  6335. var slatCoordCache = this.slatCoordCache;
  6336. if (colCoordCache.isLeftInBounds(leftOffset) && slatCoordCache.isTopInBounds(topOffset)) {
  6337. var colIndex = colCoordCache.getHorizontalIndex(leftOffset);
  6338. var slatIndex = slatCoordCache.getVerticalIndex(topOffset);
  6339. if (colIndex != null && slatIndex != null) {
  6340. var slatTop = slatCoordCache.getTopOffset(slatIndex);
  6341. var slatHeight = slatCoordCache.getHeight(slatIndex);
  6342. var partial = (topOffset - slatTop) / slatHeight; // floating point number between 0 and 1
  6343. var localSnapIndex = Math.floor(partial * snapsPerSlot); // the snap # relative to start of slat
  6344. var snapIndex = slatIndex * snapsPerSlot + localSnapIndex;
  6345. var snapTop = slatTop + (localSnapIndex / snapsPerSlot) * slatHeight;
  6346. var snapBottom = slatTop + ((localSnapIndex + 1) / snapsPerSlot) * slatHeight;
  6347. return {
  6348. col: colIndex,
  6349. snap: snapIndex,
  6350. component: this, // needed unfortunately :(
  6351. left: colCoordCache.getLeftOffset(colIndex),
  6352. right: colCoordCache.getRightOffset(colIndex),
  6353. top: snapTop,
  6354. bottom: snapBottom
  6355. };
  6356. }
  6357. }
  6358. },
  6359. getHitSpan: function(hit) {
  6360. var start = this.getCellDate(0, hit.col); // row=0
  6361. var time = this.computeSnapTime(hit.snap); // pass in the snap-index
  6362. var end;
  6363. start.time(time);
  6364. end = start.clone().add(this.snapDuration);
  6365. return { start: start, end: end };
  6366. },
  6367. getHitEl: function(hit) {
  6368. return this.colEls.eq(hit.col);
  6369. },
  6370. /* Dates
  6371. ------------------------------------------------------------------------------------------------------------------*/
  6372. rangeUpdated: function() {
  6373. this.updateDayTable();
  6374. },
  6375. // Given a row number of the grid, representing a "snap", returns a time (Duration) from its start-of-day
  6376. computeSnapTime: function(snapIndex) {
  6377. return moment.duration(this.view.minTime + this.snapDuration * snapIndex);
  6378. },
  6379. // Slices up the given span (unzoned start/end with other misc data) into an array of segments
  6380. spanToSegs: function(span) {
  6381. var segs = this.sliceRangeByTimes(span);
  6382. var i;
  6383. for (i = 0; i < segs.length; i++) {
  6384. if (this.isRTL) {
  6385. segs[i].col = this.daysPerRow - 1 - segs[i].dayIndex;
  6386. }
  6387. else {
  6388. segs[i].col = segs[i].dayIndex;
  6389. }
  6390. }
  6391. return segs;
  6392. },
  6393. sliceRangeByTimes: function(range) {
  6394. var segs = [];
  6395. var seg;
  6396. var dayIndex;
  6397. var dayDate;
  6398. var dayRange;
  6399. for (dayIndex = 0; dayIndex < this.daysPerRow; dayIndex++) {
  6400. dayDate = this.dayDates[dayIndex].clone().time(0); // TODO: better API for this?
  6401. dayRange = {
  6402. start: dayDate.clone().add(this.view.minTime), // don't use .time() because it sux with negatives
  6403. end: dayDate.clone().add(this.view.maxTime)
  6404. };
  6405. seg = intersectRanges(range, dayRange); // both will be ambig timezone
  6406. if (seg) {
  6407. seg.dayIndex = dayIndex;
  6408. segs.push(seg);
  6409. }
  6410. }
  6411. return segs;
  6412. },
  6413. /* Coordinates
  6414. ------------------------------------------------------------------------------------------------------------------*/
  6415. updateSize: function(isResize) { // NOT a standard Grid method
  6416. this.slatCoordCache.build();
  6417. if (isResize) {
  6418. this.updateSegVerticals(
  6419. [].concat(this.fgSegs || [], this.bgSegs || [], this.businessSegs || [])
  6420. );
  6421. }
  6422. },
  6423. getTotalSlatHeight: function() {
  6424. return this.slatContainerEl.outerHeight();
  6425. },
  6426. // Computes the top coordinate, relative to the bounds of the grid, of the given date.
  6427. // A `startOfDayDate` must be given for avoiding ambiguity over how to treat midnight.
  6428. computeDateTop: function(date, startOfDayDate) {
  6429. return this.computeTimeTop(
  6430. moment.duration(
  6431. date - startOfDayDate.clone().stripTime()
  6432. )
  6433. );
  6434. },
  6435. // Computes the top coordinate, relative to the bounds of the grid, of the given time (a Duration).
  6436. computeTimeTop: function(time) {
  6437. var len = this.slatEls.length;
  6438. var slatCoverage = (time - this.view.minTime) / this.slotDuration; // floating-point value of # of slots covered
  6439. var slatIndex;
  6440. var slatRemainder;
  6441. // compute a floating-point number for how many slats should be progressed through.
  6442. // from 0 to number of slats (inclusive)
  6443. // constrained because minTime/maxTime might be customized.
  6444. slatCoverage = Math.max(0, slatCoverage);
  6445. slatCoverage = Math.min(len, slatCoverage);
  6446. // an integer index of the furthest whole slat
  6447. // from 0 to number slats (*exclusive*, so len-1)
  6448. slatIndex = Math.floor(slatCoverage);
  6449. slatIndex = Math.min(slatIndex, len - 1);
  6450. // how much further through the slatIndex slat (from 0.0-1.0) must be covered in addition.
  6451. // could be 1.0 if slatCoverage is covering *all* the slots
  6452. slatRemainder = slatCoverage - slatIndex;
  6453. return this.slatCoordCache.getTopPosition(slatIndex) +
  6454. this.slatCoordCache.getHeight(slatIndex) * slatRemainder;
  6455. },
  6456. /* Event Drag Visualization
  6457. ------------------------------------------------------------------------------------------------------------------*/
  6458. // Renders a visual indication of an event being dragged over the specified date(s).
  6459. // A returned value of `true` signals that a mock "helper" event has been rendered.
  6460. renderDrag: function(eventLocation, seg) {
  6461. var eventSpans;
  6462. var i;
  6463. if (seg) { // if there is event information for this drag, render a helper event
  6464. // returns mock event elements
  6465. // signal that a helper has been rendered
  6466. return this.renderEventLocationHelper(eventLocation, seg);
  6467. }
  6468. else { // otherwise, just render a highlight
  6469. eventSpans = this.eventToSpans(eventLocation);
  6470. for (i = 0; i < eventSpans.length; i++) {
  6471. this.renderHighlight(eventSpans[i]);
  6472. }
  6473. }
  6474. },
  6475. // Unrenders any visual indication of an event being dragged
  6476. unrenderDrag: function() {
  6477. this.unrenderHelper();
  6478. this.unrenderHighlight();
  6479. },
  6480. /* Event Resize Visualization
  6481. ------------------------------------------------------------------------------------------------------------------*/
  6482. // Renders a visual indication of an event being resized
  6483. renderEventResize: function(eventLocation, seg) {
  6484. return this.renderEventLocationHelper(eventLocation, seg); // returns mock event elements
  6485. },
  6486. // Unrenders any visual indication of an event being resized
  6487. unrenderEventResize: function() {
  6488. this.unrenderHelper();
  6489. },
  6490. /* Event Helper
  6491. ------------------------------------------------------------------------------------------------------------------*/
  6492. // Renders a mock "helper" event. `sourceSeg` is the original segment object and might be null (an external drag)
  6493. renderHelper: function(event, sourceSeg) {
  6494. return this.renderHelperSegs(this.eventToSegs(event), sourceSeg); // returns mock event elements
  6495. },
  6496. // Unrenders any mock helper event
  6497. unrenderHelper: function() {
  6498. this.unrenderHelperSegs();
  6499. },
  6500. /* Business Hours
  6501. ------------------------------------------------------------------------------------------------------------------*/
  6502. renderBusinessHours: function() {
  6503. this.renderBusinessSegs(
  6504. this.buildBusinessHourSegs()
  6505. );
  6506. },
  6507. unrenderBusinessHours: function() {
  6508. this.unrenderBusinessSegs();
  6509. },
  6510. /* Now Indicator
  6511. ------------------------------------------------------------------------------------------------------------------*/
  6512. getNowIndicatorUnit: function() {
  6513. return 'minute'; // will refresh on the minute
  6514. },
  6515. renderNowIndicator: function(date) {
  6516. // seg system might be overkill, but it handles scenario where line needs to be rendered
  6517. // more than once because of columns with the same date (resources columns for example)
  6518. var segs = this.spanToSegs({ start: date, end: date });
  6519. var top = this.computeDateTop(date, date);
  6520. var nodes = [];
  6521. var i;
  6522. // render lines within the columns
  6523. for (i = 0; i < segs.length; i++) {
  6524. nodes.push($('<div class="fc-now-indicator fc-now-indicator-line"></div>')
  6525. .css('top', top)
  6526. .appendTo(this.colContainerEls.eq(segs[i].col))[0]);
  6527. }
  6528. // render an arrow over the axis
  6529. if (segs.length > 0) { // is the current time in view?
  6530. nodes.push($('<div class="fc-now-indicator fc-now-indicator-arrow"></div>')
  6531. .css('top', top)
  6532. .appendTo(this.el.find('.fc-content-skeleton'))[0]);
  6533. }
  6534. this.nowIndicatorEls = $(nodes);
  6535. },
  6536. unrenderNowIndicator: function() {
  6537. if (this.nowIndicatorEls) {
  6538. this.nowIndicatorEls.remove();
  6539. this.nowIndicatorEls = null;
  6540. }
  6541. },
  6542. /* Selection
  6543. ------------------------------------------------------------------------------------------------------------------*/
  6544. // Renders a visual indication of a selection. Overrides the default, which was to simply render a highlight.
  6545. renderSelection: function(span) {
  6546. if (this.view.opt('selectHelper')) { // this setting signals that a mock helper event should be rendered
  6547. // normally acceps an eventLocation, span has a start/end, which is good enough
  6548. this.renderEventLocationHelper(span);
  6549. }
  6550. else {
  6551. this.renderHighlight(span);
  6552. }
  6553. },
  6554. // Unrenders any visual indication of a selection
  6555. unrenderSelection: function() {
  6556. this.unrenderHelper();
  6557. this.unrenderHighlight();
  6558. },
  6559. /* Highlight
  6560. ------------------------------------------------------------------------------------------------------------------*/
  6561. renderHighlight: function(span) {
  6562. this.renderHighlightSegs(this.spanToSegs(span));
  6563. },
  6564. unrenderHighlight: function() {
  6565. this.unrenderHighlightSegs();
  6566. }
  6567. });
  6568. ;;
  6569. /* Methods for rendering SEGMENTS, pieces of content that live on the view
  6570. ( this file is no longer just for events )
  6571. ----------------------------------------------------------------------------------------------------------------------*/
  6572. TimeGrid.mixin({
  6573. colContainerEls: null, // containers for each column
  6574. // inner-containers for each column where different types of segs live
  6575. fgContainerEls: null,
  6576. bgContainerEls: null,
  6577. helperContainerEls: null,
  6578. highlightContainerEls: null,
  6579. businessContainerEls: null,
  6580. // arrays of different types of displayed segments
  6581. fgSegs: null,
  6582. bgSegs: null,
  6583. helperSegs: null,
  6584. highlightSegs: null,
  6585. businessSegs: null,
  6586. // Renders the DOM that the view's content will live in
  6587. renderContentSkeleton: function() {
  6588. var cellHtml = '';
  6589. var i;
  6590. var skeletonEl;
  6591. for (i = 0; i < this.colCnt; i++) {
  6592. cellHtml +=
  6593. '<td>' +
  6594. '<div class="fc-content-col">' +
  6595. '<div class="fc-event-container fc-helper-container"></div>' +
  6596. '<div class="fc-event-container"></div>' +
  6597. '<div class="fc-highlight-container"></div>' +
  6598. '<div class="fc-bgevent-container"></div>' +
  6599. '<div class="fc-business-container"></div>' +
  6600. '</div>' +
  6601. '</td>';
  6602. }
  6603. skeletonEl = $(
  6604. '<div class="fc-content-skeleton">' +
  6605. '<table>' +
  6606. '<tr>' + cellHtml + '</tr>' +
  6607. '</table>' +
  6608. '</div>'
  6609. );
  6610. this.colContainerEls = skeletonEl.find('.fc-content-col');
  6611. this.helperContainerEls = skeletonEl.find('.fc-helper-container');
  6612. this.fgContainerEls = skeletonEl.find('.fc-event-container:not(.fc-helper-container)');
  6613. this.bgContainerEls = skeletonEl.find('.fc-bgevent-container');
  6614. this.highlightContainerEls = skeletonEl.find('.fc-highlight-container');
  6615. this.businessContainerEls = skeletonEl.find('.fc-business-container');
  6616. this.bookendCells(skeletonEl.find('tr')); // TODO: do this on string level
  6617. this.el.append(skeletonEl);
  6618. },
  6619. /* Foreground Events
  6620. ------------------------------------------------------------------------------------------------------------------*/
  6621. renderFgSegs: function(segs) {
  6622. segs = this.renderFgSegsIntoContainers(segs, this.fgContainerEls);
  6623. this.fgSegs = segs;
  6624. return segs; // needed for Grid::renderEvents
  6625. },
  6626. unrenderFgSegs: function() {
  6627. this.unrenderNamedSegs('fgSegs');
  6628. },
  6629. /* Foreground Helper Events
  6630. ------------------------------------------------------------------------------------------------------------------*/
  6631. renderHelperSegs: function(segs, sourceSeg) {
  6632. var helperEls = [];
  6633. var i, seg;
  6634. var sourceEl;
  6635. segs = this.renderFgSegsIntoContainers(segs, this.helperContainerEls);
  6636. // Try to make the segment that is in the same row as sourceSeg look the same
  6637. for (i = 0; i < segs.length; i++) {
  6638. seg = segs[i];
  6639. if (sourceSeg && sourceSeg.col === seg.col) {
  6640. sourceEl = sourceSeg.el;
  6641. seg.el.css({
  6642. left: sourceEl.css('left'),
  6643. right: sourceEl.css('right'),
  6644. 'margin-left': sourceEl.css('margin-left'),
  6645. 'margin-right': sourceEl.css('margin-right')
  6646. });
  6647. }
  6648. helperEls.push(seg.el[0]);
  6649. }
  6650. this.helperSegs = segs;
  6651. return $(helperEls); // must return rendered helpers
  6652. },
  6653. unrenderHelperSegs: function() {
  6654. this.unrenderNamedSegs('helperSegs');
  6655. },
  6656. /* Background Events
  6657. ------------------------------------------------------------------------------------------------------------------*/
  6658. renderBgSegs: function(segs) {
  6659. segs = this.renderFillSegEls('bgEvent', segs); // TODO: old fill system
  6660. this.updateSegVerticals(segs);
  6661. this.attachSegsByCol(this.groupSegsByCol(segs), this.bgContainerEls);
  6662. this.bgSegs = segs;
  6663. return segs; // needed for Grid::renderEvents
  6664. },
  6665. unrenderBgSegs: function() {
  6666. this.unrenderNamedSegs('bgSegs');
  6667. },
  6668. /* Highlight
  6669. ------------------------------------------------------------------------------------------------------------------*/
  6670. renderHighlightSegs: function(segs) {
  6671. segs = this.renderFillSegEls('highlight', segs); // TODO: old fill system
  6672. this.updateSegVerticals(segs);
  6673. this.attachSegsByCol(this.groupSegsByCol(segs), this.highlightContainerEls);
  6674. this.highlightSegs = segs;
  6675. },
  6676. unrenderHighlightSegs: function() {
  6677. this.unrenderNamedSegs('highlightSegs');
  6678. },
  6679. /* Business Hours
  6680. ------------------------------------------------------------------------------------------------------------------*/
  6681. renderBusinessSegs: function(segs) {
  6682. segs = this.renderFillSegEls('businessHours', segs); // TODO: old fill system
  6683. this.updateSegVerticals(segs);
  6684. this.attachSegsByCol(this.groupSegsByCol(segs), this.businessContainerEls);
  6685. this.businessSegs = segs;
  6686. },
  6687. unrenderBusinessSegs: function() {
  6688. this.unrenderNamedSegs('businessSegs');
  6689. },
  6690. /* Seg Rendering Utils
  6691. ------------------------------------------------------------------------------------------------------------------*/
  6692. // Given a flat array of segments, return an array of sub-arrays, grouped by each segment's col
  6693. groupSegsByCol: function(segs) {
  6694. var segsByCol = [];
  6695. var i;
  6696. for (i = 0; i < this.colCnt; i++) {
  6697. segsByCol.push([]);
  6698. }
  6699. for (i = 0; i < segs.length; i++) {
  6700. segsByCol[segs[i].col].push(segs[i]);
  6701. }
  6702. return segsByCol;
  6703. },
  6704. // Given segments grouped by column, insert the segments' elements into a parallel array of container
  6705. // elements, each living within a column.
  6706. attachSegsByCol: function(segsByCol, containerEls) {
  6707. var col;
  6708. var segs;
  6709. var i;
  6710. for (col = 0; col < this.colCnt; col++) { // iterate each column grouping
  6711. segs = segsByCol[col];
  6712. for (i = 0; i < segs.length; i++) {
  6713. containerEls.eq(col).append(segs[i].el);
  6714. }
  6715. }
  6716. },
  6717. // Given the name of a property of `this` object, assumed to be an array of segments,
  6718. // loops through each segment and removes from DOM. Will null-out the property afterwards.
  6719. unrenderNamedSegs: function(propName) {
  6720. var segs = this[propName];
  6721. var i;
  6722. if (segs) {
  6723. for (i = 0; i < segs.length; i++) {
  6724. segs[i].el.remove();
  6725. }
  6726. this[propName] = null;
  6727. }
  6728. },
  6729. /* Foreground Event Rendering Utils
  6730. ------------------------------------------------------------------------------------------------------------------*/
  6731. // Given an array of foreground segments, render a DOM element for each, computes position,
  6732. // and attaches to the column inner-container elements.
  6733. renderFgSegsIntoContainers: function(segs, containerEls) {
  6734. var segsByCol;
  6735. var col;
  6736. segs = this.renderFgSegEls(segs); // will call fgSegHtml
  6737. segsByCol = this.groupSegsByCol(segs);
  6738. for (col = 0; col < this.colCnt; col++) {
  6739. this.updateFgSegCoords(segsByCol[col]);
  6740. }
  6741. this.attachSegsByCol(segsByCol, containerEls);
  6742. return segs;
  6743. },
  6744. // Renders the HTML for a single event segment's default rendering
  6745. fgSegHtml: function(seg, disableResizing) {
  6746. var view = this.view;
  6747. var event = seg.event;
  6748. var isDraggable = view.isEventDraggable(event);
  6749. var isResizableFromStart = !disableResizing && seg.isStart && view.isEventResizableFromStart(event);
  6750. var isResizableFromEnd = !disableResizing && seg.isEnd && view.isEventResizableFromEnd(event);
  6751. var classes = this.getSegClasses(seg, isDraggable, isResizableFromStart || isResizableFromEnd);
  6752. var skinCss = cssToStr(this.getSegSkinCss(seg));
  6753. var timeText;
  6754. var fullTimeText; // more verbose time text. for the print stylesheet
  6755. var startTimeText; // just the start time text
  6756. classes.unshift('fc-time-grid-event', 'fc-v-event');
  6757. if (view.isMultiDayEvent(event)) { // if the event appears to span more than one day...
  6758. // Don't display time text on segments that run entirely through a day.
  6759. // That would appear as midnight-midnight and would look dumb.
  6760. // Otherwise, display the time text for the *segment's* times (like 6pm-midnight or midnight-10am)
  6761. if (seg.isStart || seg.isEnd) {
  6762. timeText = this.getEventTimeText(seg);
  6763. fullTimeText = this.getEventTimeText(seg, 'LT');
  6764. startTimeText = this.getEventTimeText(seg, null, false); // displayEnd=false
  6765. }
  6766. } else {
  6767. // Display the normal time text for the *event's* times
  6768. timeText = this.getEventTimeText(event);
  6769. fullTimeText = this.getEventTimeText(event, 'LT');
  6770. startTimeText = this.getEventTimeText(event, null, false); // displayEnd=false
  6771. }
  6772. return '<a class="' + classes.join(' ') + '"' +
  6773. (event.url ?
  6774. ' href="' + htmlEscape(event.url) + '"' :
  6775. ''
  6776. ) +
  6777. (skinCss ?
  6778. ' style="' + skinCss + '"' :
  6779. ''
  6780. ) +
  6781. '>' +
  6782. '<div class="fc-content">' +
  6783. (timeText ?
  6784. '<div class="fc-time"' +
  6785. ' data-start="' + htmlEscape(startTimeText) + '"' +
  6786. ' data-full="' + htmlEscape(fullTimeText) + '"' +
  6787. '>' +
  6788. '<span>' + htmlEscape(timeText) + '</span>' +
  6789. '</div>' :
  6790. ''
  6791. ) +
  6792. (event.title ?
  6793. '<div class="fc-title">' +
  6794. htmlEscape(event.title) +
  6795. '</div>' :
  6796. ''
  6797. ) +
  6798. '</div>' +
  6799. '<div class="fc-bg"/>' +
  6800. /* TODO: write CSS for this
  6801. (isResizableFromStart ?
  6802. '<div class="fc-resizer fc-start-resizer" />' :
  6803. ''
  6804. ) +
  6805. */
  6806. (isResizableFromEnd ?
  6807. '<div class="fc-resizer fc-end-resizer" />' :
  6808. ''
  6809. ) +
  6810. '</a>';
  6811. },
  6812. /* Seg Position Utils
  6813. ------------------------------------------------------------------------------------------------------------------*/
  6814. // Refreshes the CSS top/bottom coordinates for each segment element.
  6815. // Works when called after initial render, after a window resize/zoom for example.
  6816. updateSegVerticals: function(segs) {
  6817. this.computeSegVerticals(segs);
  6818. this.assignSegVerticals(segs);
  6819. },
  6820. // For each segment in an array, computes and assigns its top and bottom properties
  6821. computeSegVerticals: function(segs) {
  6822. var i, seg;
  6823. var dayDate;
  6824. for (i = 0; i < segs.length; i++) {
  6825. seg = segs[i];
  6826. dayDate = this.dayDates[seg.dayIndex];
  6827. seg.top = this.computeDateTop(seg.start, dayDate);
  6828. seg.bottom = this.computeDateTop(seg.end, dayDate);
  6829. }
  6830. },
  6831. // Given segments that already have their top/bottom properties computed, applies those values to
  6832. // the segments' elements.
  6833. assignSegVerticals: function(segs) {
  6834. var i, seg;
  6835. for (i = 0; i < segs.length; i++) {
  6836. seg = segs[i];
  6837. seg.el.css(this.generateSegVerticalCss(seg));
  6838. }
  6839. },
  6840. // Generates an object with CSS properties for the top/bottom coordinates of a segment element
  6841. generateSegVerticalCss: function(seg) {
  6842. return {
  6843. top: seg.top,
  6844. bottom: -seg.bottom // flipped because needs to be space beyond bottom edge of event container
  6845. };
  6846. },
  6847. /* Foreground Event Positioning Utils
  6848. ------------------------------------------------------------------------------------------------------------------*/
  6849. // Given segments that are assumed to all live in the *same column*,
  6850. // compute their verical/horizontal coordinates and assign to their elements.
  6851. updateFgSegCoords: function(segs) {
  6852. this.computeSegVerticals(segs); // horizontals relies on this
  6853. this.computeFgSegHorizontals(segs); // compute horizontal coordinates, z-index's, and reorder the array
  6854. this.assignSegVerticals(segs);
  6855. this.assignFgSegHorizontals(segs);
  6856. },
  6857. // Given an array of segments that are all in the same column, sets the backwardCoord and forwardCoord on each.
  6858. // NOTE: Also reorders the given array by date!
  6859. computeFgSegHorizontals: function(segs) {
  6860. var levels;
  6861. var level0;
  6862. var i;
  6863. this.sortEventSegs(segs); // order by certain criteria
  6864. levels = buildSlotSegLevels(segs);
  6865. computeForwardSlotSegs(levels);
  6866. if ((level0 = levels[0])) {
  6867. for (i = 0; i < level0.length; i++) {
  6868. computeSlotSegPressures(level0[i]);
  6869. }
  6870. for (i = 0; i < level0.length; i++) {
  6871. this.computeFgSegForwardBack(level0[i], 0, 0);
  6872. }
  6873. }
  6874. },
  6875. // Calculate seg.forwardCoord and seg.backwardCoord for the segment, where both values range
  6876. // from 0 to 1. If the calendar is left-to-right, the seg.backwardCoord maps to "left" and
  6877. // seg.forwardCoord maps to "right" (via percentage). Vice-versa if the calendar is right-to-left.
  6878. //
  6879. // The segment might be part of a "series", which means consecutive segments with the same pressure
  6880. // who's width is unknown until an edge has been hit. `seriesBackwardPressure` is the number of
  6881. // segments behind this one in the current series, and `seriesBackwardCoord` is the starting
  6882. // coordinate of the first segment in the series.
  6883. computeFgSegForwardBack: function(seg, seriesBackwardPressure, seriesBackwardCoord) {
  6884. var forwardSegs = seg.forwardSegs;
  6885. var i;
  6886. if (seg.forwardCoord === undefined) { // not already computed
  6887. if (!forwardSegs.length) {
  6888. // if there are no forward segments, this segment should butt up against the edge
  6889. seg.forwardCoord = 1;
  6890. }
  6891. else {
  6892. // sort highest pressure first
  6893. this.sortForwardSegs(forwardSegs);
  6894. // this segment's forwardCoord will be calculated from the backwardCoord of the
  6895. // highest-pressure forward segment.
  6896. this.computeFgSegForwardBack(forwardSegs[0], seriesBackwardPressure + 1, seriesBackwardCoord);
  6897. seg.forwardCoord = forwardSegs[0].backwardCoord;
  6898. }
  6899. // calculate the backwardCoord from the forwardCoord. consider the series
  6900. seg.backwardCoord = seg.forwardCoord -
  6901. (seg.forwardCoord - seriesBackwardCoord) / // available width for series
  6902. (seriesBackwardPressure + 1); // # of segments in the series
  6903. // use this segment's coordinates to computed the coordinates of the less-pressurized
  6904. // forward segments
  6905. for (i=0; i<forwardSegs.length; i++) {
  6906. this.computeFgSegForwardBack(forwardSegs[i], 0, seg.forwardCoord);
  6907. }
  6908. }
  6909. },
  6910. sortForwardSegs: function(forwardSegs) {
  6911. forwardSegs.sort(proxy(this, 'compareForwardSegs'));
  6912. },
  6913. // A cmp function for determining which forward segment to rely on more when computing coordinates.
  6914. compareForwardSegs: function(seg1, seg2) {
  6915. // put higher-pressure first
  6916. return seg2.forwardPressure - seg1.forwardPressure ||
  6917. // put segments that are closer to initial edge first (and favor ones with no coords yet)
  6918. (seg1.backwardCoord || 0) - (seg2.backwardCoord || 0) ||
  6919. // do normal sorting...
  6920. this.compareEventSegs(seg1, seg2);
  6921. },
  6922. // Given foreground event segments that have already had their position coordinates computed,
  6923. // assigns position-related CSS values to their elements.
  6924. assignFgSegHorizontals: function(segs) {
  6925. var i, seg;
  6926. for (i = 0; i < segs.length; i++) {
  6927. seg = segs[i];
  6928. seg.el.css(this.generateFgSegHorizontalCss(seg));
  6929. // if the height is short, add a className for alternate styling
  6930. if (seg.bottom - seg.top < 30) {
  6931. seg.el.addClass('fc-short');
  6932. }
  6933. }
  6934. },
  6935. // Generates an object with CSS properties/values that should be applied to an event segment element.
  6936. // Contains important positioning-related properties that should be applied to any event element, customized or not.
  6937. generateFgSegHorizontalCss: function(seg) {
  6938. var shouldOverlap = this.view.opt('slotEventOverlap');
  6939. var backwardCoord = seg.backwardCoord; // the left side if LTR. the right side if RTL. floating-point
  6940. var forwardCoord = seg.forwardCoord; // the right side if LTR. the left side if RTL. floating-point
  6941. var props = this.generateSegVerticalCss(seg); // get top/bottom first
  6942. var left; // amount of space from left edge, a fraction of the total width
  6943. var right; // amount of space from right edge, a fraction of the total width
  6944. if (shouldOverlap) {
  6945. // double the width, but don't go beyond the maximum forward coordinate (1.0)
  6946. forwardCoord = Math.min(1, backwardCoord + (forwardCoord - backwardCoord) * 2);
  6947. }
  6948. if (this.isRTL) {
  6949. left = 1 - forwardCoord;
  6950. right = backwardCoord;
  6951. }
  6952. else {
  6953. left = backwardCoord;
  6954. right = 1 - forwardCoord;
  6955. }
  6956. props.zIndex = seg.level + 1; // convert from 0-base to 1-based
  6957. props.left = left * 100 + '%';
  6958. props.right = right * 100 + '%';
  6959. if (shouldOverlap && seg.forwardPressure) {
  6960. // add padding to the edge so that forward stacked events don't cover the resizer's icon
  6961. props[this.isRTL ? 'marginLeft' : 'marginRight'] = 10 * 2; // 10 is a guesstimate of the icon's width
  6962. }
  6963. return props;
  6964. }
  6965. });
  6966. // Builds an array of segments "levels". The first level will be the leftmost tier of segments if the calendar is
  6967. // left-to-right, or the rightmost if the calendar is right-to-left. Assumes the segments are already ordered by date.
  6968. function buildSlotSegLevels(segs) {
  6969. var levels = [];
  6970. var i, seg;
  6971. var j;
  6972. for (i=0; i<segs.length; i++) {
  6973. seg = segs[i];
  6974. // go through all the levels and stop on the first level where there are no collisions
  6975. for (j=0; j<levels.length; j++) {
  6976. if (!computeSlotSegCollisions(seg, levels[j]).length) {
  6977. break;
  6978. }
  6979. }
  6980. seg.level = j;
  6981. (levels[j] || (levels[j] = [])).push(seg);
  6982. }
  6983. return levels;
  6984. }
  6985. // For every segment, figure out the other segments that are in subsequent
  6986. // levels that also occupy the same vertical space. Accumulate in seg.forwardSegs
  6987. function computeForwardSlotSegs(levels) {
  6988. var i, level;
  6989. var j, seg;
  6990. var k;
  6991. for (i=0; i<levels.length; i++) {
  6992. level = levels[i];
  6993. for (j=0; j<level.length; j++) {
  6994. seg = level[j];
  6995. seg.forwardSegs = [];
  6996. for (k=i+1; k<levels.length; k++) {
  6997. computeSlotSegCollisions(seg, levels[k], seg.forwardSegs);
  6998. }
  6999. }
  7000. }
  7001. }
  7002. // Figure out which path forward (via seg.forwardSegs) results in the longest path until
  7003. // the furthest edge is reached. The number of segments in this path will be seg.forwardPressure
  7004. function computeSlotSegPressures(seg) {
  7005. var forwardSegs = seg.forwardSegs;
  7006. var forwardPressure = 0;
  7007. var i, forwardSeg;
  7008. if (seg.forwardPressure === undefined) { // not already computed
  7009. for (i=0; i<forwardSegs.length; i++) {
  7010. forwardSeg = forwardSegs[i];
  7011. // figure out the child's maximum forward path
  7012. computeSlotSegPressures(forwardSeg);
  7013. // either use the existing maximum, or use the child's forward pressure
  7014. // plus one (for the forwardSeg itself)
  7015. forwardPressure = Math.max(
  7016. forwardPressure,
  7017. 1 + forwardSeg.forwardPressure
  7018. );
  7019. }
  7020. seg.forwardPressure = forwardPressure;
  7021. }
  7022. }
  7023. // Find all the segments in `otherSegs` that vertically collide with `seg`.
  7024. // Append into an optionally-supplied `results` array and return.
  7025. function computeSlotSegCollisions(seg, otherSegs, results) {
  7026. results = results || [];
  7027. for (var i=0; i<otherSegs.length; i++) {
  7028. if (isSlotSegCollision(seg, otherSegs[i])) {
  7029. results.push(otherSegs[i]);
  7030. }
  7031. }
  7032. return results;
  7033. }
  7034. // Do these segments occupy the same vertical space?
  7035. function isSlotSegCollision(seg1, seg2) {
  7036. return seg1.bottom > seg2.top && seg1.top < seg2.bottom;
  7037. }
  7038. ;;
  7039. /* An abstract class from which other views inherit from
  7040. ----------------------------------------------------------------------------------------------------------------------*/
  7041. var View = FC.View = Model.extend({
  7042. type: null, // subclass' view name (string)
  7043. name: null, // deprecated. use `type` instead
  7044. title: null, // the text that will be displayed in the header's title
  7045. calendar: null, // owner Calendar object
  7046. viewSpec: null,
  7047. options: null, // hash containing all options. already merged with view-specific-options
  7048. el: null, // the view's containing element. set by Calendar
  7049. renderQueue: null,
  7050. batchRenderDepth: 0,
  7051. isDatesRendered: false,
  7052. isEventsRendered: false,
  7053. isBaseRendered: false, // related to viewRender/viewDestroy triggers
  7054. queuedScroll: null,
  7055. isRTL: false,
  7056. isSelected: false, // boolean whether a range of time is user-selected or not
  7057. selectedEvent: null,
  7058. eventOrderSpecs: null, // criteria for ordering events when they have same date/time
  7059. // classNames styled by jqui themes
  7060. widgetHeaderClass: null,
  7061. widgetContentClass: null,
  7062. highlightStateClass: null,
  7063. // for date utils, computed from options
  7064. nextDayThreshold: null,
  7065. isHiddenDayHash: null,
  7066. // now indicator
  7067. isNowIndicatorRendered: null,
  7068. initialNowDate: null, // result first getNow call
  7069. initialNowQueriedMs: null, // ms time the getNow was called
  7070. nowIndicatorTimeoutID: null, // for refresh timing of now indicator
  7071. nowIndicatorIntervalID: null, // "
  7072. constructor: function(calendar, viewSpec) {
  7073. Model.prototype.constructor.call(this);
  7074. this.calendar = calendar;
  7075. this.viewSpec = viewSpec;
  7076. // shortcuts
  7077. this.type = viewSpec.type;
  7078. this.options = viewSpec.options;
  7079. // .name is deprecated
  7080. this.name = this.type;
  7081. this.nextDayThreshold = moment.duration(this.opt('nextDayThreshold'));
  7082. this.initThemingProps();
  7083. this.initHiddenDays();
  7084. this.isRTL = this.opt('isRTL');
  7085. this.eventOrderSpecs = parseFieldSpecs(this.opt('eventOrder'));
  7086. this.renderQueue = this.buildRenderQueue();
  7087. this.initAutoBatchRender();
  7088. this.initialize();
  7089. },
  7090. buildRenderQueue: function() {
  7091. var _this = this;
  7092. var renderQueue = new RenderQueue({
  7093. event: this.opt('eventRenderWait')
  7094. });
  7095. renderQueue.on('start', function() {
  7096. _this.freezeHeight();
  7097. _this.addScroll(_this.queryScroll());
  7098. });
  7099. renderQueue.on('stop', function() {
  7100. _this.thawHeight();
  7101. _this.popScroll();
  7102. });
  7103. return renderQueue;
  7104. },
  7105. initAutoBatchRender: function() {
  7106. var _this = this;
  7107. this.on('before:change', function() {
  7108. _this.startBatchRender();
  7109. });
  7110. this.on('change', function() {
  7111. _this.stopBatchRender();
  7112. });
  7113. },
  7114. startBatchRender: function() {
  7115. if (!(this.batchRenderDepth++)) {
  7116. this.renderQueue.pause();
  7117. }
  7118. },
  7119. stopBatchRender: function() {
  7120. if (!(--this.batchRenderDepth)) {
  7121. this.renderQueue.resume();
  7122. }
  7123. },
  7124. // A good place for subclasses to initialize member variables
  7125. initialize: function() {
  7126. // subclasses can implement
  7127. },
  7128. // Retrieves an option with the given name
  7129. opt: function(name) {
  7130. return this.options[name];
  7131. },
  7132. // Triggers handlers that are view-related. Modifies args before passing to calendar.
  7133. publiclyTrigger: function(name, thisObj) { // arguments beyond thisObj are passed along
  7134. var calendar = this.calendar;
  7135. return calendar.publiclyTrigger.apply(
  7136. calendar,
  7137. [name, thisObj || this].concat(
  7138. Array.prototype.slice.call(arguments, 2), // arguments beyond thisObj
  7139. [ this ] // always make the last argument a reference to the view. TODO: deprecate
  7140. )
  7141. );
  7142. },
  7143. /* Title and Date Formatting
  7144. ------------------------------------------------------------------------------------------------------------------*/
  7145. // Sets the view's title property to the most updated computed value
  7146. updateTitle: function() {
  7147. this.title = this.computeTitle();
  7148. this.calendar.setToolbarsTitle(this.title);
  7149. },
  7150. // Computes what the title at the top of the calendar should be for this view
  7151. computeTitle: function() {
  7152. var range;
  7153. // for views that span a large unit of time, show the proper interval, ignoring stray days before and after
  7154. if (/^(year|month)$/.test(this.currentRangeUnit)) {
  7155. range = this.currentRange;
  7156. }
  7157. else { // for day units or smaller, use the actual day range
  7158. range = this.activeRange;
  7159. }
  7160. return this.formatRange(
  7161. {
  7162. // in case currentRange has a time, make sure timezone is correct
  7163. start: this.calendar.applyTimezone(range.start),
  7164. end: this.calendar.applyTimezone(range.end)
  7165. },
  7166. this.opt('titleFormat') || this.computeTitleFormat(),
  7167. this.opt('titleRangeSeparator')
  7168. );
  7169. },
  7170. // Generates the format string that should be used to generate the title for the current date range.
  7171. // Attempts to compute the most appropriate format if not explicitly specified with `titleFormat`.
  7172. computeTitleFormat: function() {
  7173. if (this.currentRangeUnit == 'year') {
  7174. return 'YYYY';
  7175. }
  7176. else if (this.currentRangeUnit == 'month') {
  7177. return this.opt('monthYearFormat'); // like "September 2014"
  7178. }
  7179. else if (this.currentRangeAs('days') > 1) {
  7180. return 'll'; // multi-day range. shorter, like "Sep 9 - 10 2014"
  7181. }
  7182. else {
  7183. return 'LL'; // one day. longer, like "September 9 2014"
  7184. }
  7185. },
  7186. // Utility for formatting a range. Accepts a range object, formatting string, and optional separator.
  7187. // Displays all-day ranges naturally, with an inclusive end. Takes the current isRTL into account.
  7188. // The timezones of the dates within `range` will be respected.
  7189. formatRange: function(range, formatStr, separator) {
  7190. var end = range.end;
  7191. if (!end.hasTime()) { // all-day?
  7192. end = end.clone().subtract(1); // convert to inclusive. last ms of previous day
  7193. }
  7194. return formatRange(range.start, end, formatStr, separator, this.opt('isRTL'));
  7195. },
  7196. getAllDayHtml: function() {
  7197. return this.opt('allDayHtml') || htmlEscape(this.opt('allDayText'));
  7198. },
  7199. /* Navigation
  7200. ------------------------------------------------------------------------------------------------------------------*/
  7201. // Generates HTML for an anchor to another view into the calendar.
  7202. // Will either generate an <a> tag or a non-clickable <span> tag, depending on enabled settings.
  7203. // `gotoOptions` can either be a moment input, or an object with the form:
  7204. // { date, type, forceOff }
  7205. // `type` is a view-type like "day" or "week". default value is "day".
  7206. // `attrs` and `innerHtml` are use to generate the rest of the HTML tag.
  7207. buildGotoAnchorHtml: function(gotoOptions, attrs, innerHtml) {
  7208. var date, type, forceOff;
  7209. var finalOptions;
  7210. if ($.isPlainObject(gotoOptions)) {
  7211. date = gotoOptions.date;
  7212. type = gotoOptions.type;
  7213. forceOff = gotoOptions.forceOff;
  7214. }
  7215. else {
  7216. date = gotoOptions; // a single moment input
  7217. }
  7218. date = FC.moment(date); // if a string, parse it
  7219. finalOptions = { // for serialization into the link
  7220. date: date.format('YYYY-MM-DD'),
  7221. type: type || 'day'
  7222. };
  7223. if (typeof attrs === 'string') {
  7224. innerHtml = attrs;
  7225. attrs = null;
  7226. }
  7227. attrs = attrs ? ' ' + attrsToStr(attrs) : ''; // will have a leading space
  7228. innerHtml = innerHtml || '';
  7229. if (!forceOff && this.opt('navLinks')) {
  7230. return '<a' + attrs +
  7231. ' data-goto="' + htmlEscape(JSON.stringify(finalOptions)) + '">' +
  7232. innerHtml +
  7233. '</a>';
  7234. }
  7235. else {
  7236. return '<span' + attrs + '>' +
  7237. innerHtml +
  7238. '</span>';
  7239. }
  7240. },
  7241. // Rendering Non-date-related Content
  7242. // -----------------------------------------------------------------------------------------------------------------
  7243. // Sets the container element that the view should render inside of, does global DOM-related initializations,
  7244. // and renders all the non-date-related content inside.
  7245. setElement: function(el) {
  7246. this.el = el;
  7247. this.bindGlobalHandlers();
  7248. this.bindBaseRenderHandlers();
  7249. this.renderSkeleton();
  7250. },
  7251. // Removes the view's container element from the DOM, clearing any content beforehand.
  7252. // Undoes any other DOM-related attachments.
  7253. removeElement: function() {
  7254. this.unsetDate();
  7255. this.unrenderSkeleton();
  7256. this.unbindGlobalHandlers();
  7257. this.unbindBaseRenderHandlers();
  7258. this.el.remove();
  7259. // NOTE: don't null-out this.el in case the View was destroyed within an API callback.
  7260. // We don't null-out the View's other jQuery element references upon destroy,
  7261. // so we shouldn't kill this.el either.
  7262. },
  7263. // Renders the basic structure of the view before any content is rendered
  7264. renderSkeleton: function() {
  7265. // subclasses should implement
  7266. },
  7267. // Unrenders the basic structure of the view
  7268. unrenderSkeleton: function() {
  7269. // subclasses should implement
  7270. },
  7271. // Date Setting/Unsetting
  7272. // -----------------------------------------------------------------------------------------------------------------
  7273. setDate: function(date) {
  7274. var currentDateProfile = this.get('dateProfile');
  7275. var newDateProfile = this.buildDateProfile(date, null, true); // forceToValid=true
  7276. if (
  7277. !currentDateProfile ||
  7278. !isRangesEqual(currentDateProfile.activeRange, newDateProfile.activeRange)
  7279. ) {
  7280. this.set('dateProfile', newDateProfile);
  7281. }
  7282. return newDateProfile.date;
  7283. },
  7284. unsetDate: function() {
  7285. this.unset('dateProfile');
  7286. },
  7287. // Date Rendering
  7288. // -----------------------------------------------------------------------------------------------------------------
  7289. requestDateRender: function(dateProfile) {
  7290. var _this = this;
  7291. this.renderQueue.queue(function() {
  7292. _this.executeDateRender(dateProfile);
  7293. }, 'date', 'init');
  7294. },
  7295. requestDateUnrender: function() {
  7296. var _this = this;
  7297. this.renderQueue.queue(function() {
  7298. _this.executeDateUnrender();
  7299. }, 'date', 'destroy');
  7300. },
  7301. // Event Data
  7302. // -----------------------------------------------------------------------------------------------------------------
  7303. fetchInitialEvents: function(dateProfile) {
  7304. return this.calendar.requestEvents(
  7305. dateProfile.activeRange.start,
  7306. dateProfile.activeRange.end
  7307. );
  7308. },
  7309. bindEventChanges: function() {
  7310. this.listenTo(this.calendar, 'eventsReset', this.resetEvents);
  7311. },
  7312. unbindEventChanges: function() {
  7313. this.stopListeningTo(this.calendar, 'eventsReset');
  7314. },
  7315. setEvents: function(events) {
  7316. this.set('currentEvents', events);
  7317. this.set('hasEvents', true);
  7318. },
  7319. unsetEvents: function() {
  7320. this.unset('currentEvents');
  7321. this.unset('hasEvents');
  7322. },
  7323. resetEvents: function(events) {
  7324. this.startBatchRender();
  7325. this.unsetEvents();
  7326. this.setEvents(events);
  7327. this.stopBatchRender();
  7328. },
  7329. // Event Rendering
  7330. // -----------------------------------------------------------------------------------------------------------------
  7331. requestEventsRender: function(events) {
  7332. var _this = this;
  7333. this.renderQueue.queue(function() {
  7334. _this.executeEventsRender(events);
  7335. }, 'event', 'init');
  7336. },
  7337. requestEventsUnrender: function() {
  7338. var _this = this;
  7339. this.renderQueue.queue(function() {
  7340. _this.executeEventsUnrender();
  7341. }, 'event', 'destroy');
  7342. },
  7343. // Date High-level Rendering
  7344. // -----------------------------------------------------------------------------------------------------------------
  7345. // if dateProfile not specified, uses current
  7346. executeDateRender: function(dateProfile, skipScroll) {
  7347. this.setDateProfileForRendering(dateProfile);
  7348. this.updateTitle();
  7349. this.calendar.updateToolbarButtons();
  7350. if (this.render) {
  7351. this.render(); // TODO: deprecate
  7352. }
  7353. this.renderDates();
  7354. this.updateSize();
  7355. this.renderBusinessHours(); // might need coordinates, so should go after updateSize()
  7356. this.startNowIndicator();
  7357. if (!skipScroll) {
  7358. this.addScroll(this.computeInitialDateScroll());
  7359. }
  7360. this.isDatesRendered = true;
  7361. this.trigger('datesRendered');
  7362. },
  7363. executeDateUnrender: function() {
  7364. this.unselect();
  7365. this.stopNowIndicator();
  7366. this.trigger('before:datesUnrendered');
  7367. this.unrenderBusinessHours();
  7368. this.unrenderDates();
  7369. if (this.destroy) {
  7370. this.destroy(); // TODO: deprecate
  7371. }
  7372. this.isDatesRendered = false;
  7373. },
  7374. // Date Low-level Rendering
  7375. // -----------------------------------------------------------------------------------------------------------------
  7376. // date-cell content only
  7377. renderDates: function() {
  7378. // subclasses should implement
  7379. },
  7380. // date-cell content only
  7381. unrenderDates: function() {
  7382. // subclasses should override
  7383. },
  7384. // Determing when the "meat" of the view is rendered (aka the base)
  7385. // -----------------------------------------------------------------------------------------------------------------
  7386. bindBaseRenderHandlers: function() {
  7387. var _this = this;
  7388. this.on('datesRendered.baseHandler', function() {
  7389. _this.onBaseRender();
  7390. });
  7391. this.on('before:datesUnrendered.baseHandler', function() {
  7392. _this.onBeforeBaseUnrender();
  7393. });
  7394. },
  7395. unbindBaseRenderHandlers: function() {
  7396. this.off('.baseHandler');
  7397. },
  7398. onBaseRender: function() {
  7399. this.applyScreenState();
  7400. this.publiclyTrigger('viewRender', this, this, this.el);
  7401. },
  7402. onBeforeBaseUnrender: function() {
  7403. this.applyScreenState();
  7404. this.publiclyTrigger('viewDestroy', this, this, this.el);
  7405. },
  7406. // Misc view rendering utils
  7407. // -----------------------------------------------------------------------------------------------------------------
  7408. // Binds DOM handlers to elements that reside outside the view container, such as the document
  7409. bindGlobalHandlers: function() {
  7410. this.listenTo(GlobalEmitter.get(), {
  7411. touchstart: this.processUnselect,
  7412. mousedown: this.handleDocumentMousedown
  7413. });
  7414. },
  7415. // Unbinds DOM handlers from elements that reside outside the view container
  7416. unbindGlobalHandlers: function() {
  7417. this.stopListeningTo(GlobalEmitter.get());
  7418. },
  7419. // Initializes internal variables related to theming
  7420. initThemingProps: function() {
  7421. var tm = this.opt('theme') ? 'ui' : 'fc';
  7422. this.widgetHeaderClass = tm + '-widget-header';
  7423. this.widgetContentClass = tm + '-widget-content';
  7424. this.highlightStateClass = tm + '-state-highlight';
  7425. },
  7426. /* Business Hours
  7427. ------------------------------------------------------------------------------------------------------------------*/
  7428. // Renders business-hours onto the view. Assumes updateSize has already been called.
  7429. renderBusinessHours: function() {
  7430. // subclasses should implement
  7431. },
  7432. // Unrenders previously-rendered business-hours
  7433. unrenderBusinessHours: function() {
  7434. // subclasses should implement
  7435. },
  7436. /* Now Indicator
  7437. ------------------------------------------------------------------------------------------------------------------*/
  7438. // Immediately render the current time indicator and begins re-rendering it at an interval,
  7439. // which is defined by this.getNowIndicatorUnit().
  7440. // TODO: somehow do this for the current whole day's background too
  7441. startNowIndicator: function() {
  7442. var _this = this;
  7443. var unit;
  7444. var update;
  7445. var delay; // ms wait value
  7446. if (this.opt('nowIndicator')) {
  7447. unit = this.getNowIndicatorUnit();
  7448. if (unit) {
  7449. update = proxy(this, 'updateNowIndicator'); // bind to `this`
  7450. this.initialNowDate = this.calendar.getNow();
  7451. this.initialNowQueriedMs = +new Date();
  7452. this.renderNowIndicator(this.initialNowDate);
  7453. this.isNowIndicatorRendered = true;
  7454. // wait until the beginning of the next interval
  7455. delay = this.initialNowDate.clone().startOf(unit).add(1, unit) - this.initialNowDate;
  7456. this.nowIndicatorTimeoutID = setTimeout(function() {
  7457. _this.nowIndicatorTimeoutID = null;
  7458. update();
  7459. delay = +moment.duration(1, unit);
  7460. delay = Math.max(100, delay); // prevent too frequent
  7461. _this.nowIndicatorIntervalID = setInterval(update, delay); // update every interval
  7462. }, delay);
  7463. }
  7464. }
  7465. },
  7466. // rerenders the now indicator, computing the new current time from the amount of time that has passed
  7467. // since the initial getNow call.
  7468. updateNowIndicator: function() {
  7469. if (this.isNowIndicatorRendered) {
  7470. this.unrenderNowIndicator();
  7471. this.renderNowIndicator(
  7472. this.initialNowDate.clone().add(new Date() - this.initialNowQueriedMs) // add ms
  7473. );
  7474. }
  7475. },
  7476. // Immediately unrenders the view's current time indicator and stops any re-rendering timers.
  7477. // Won't cause side effects if indicator isn't rendered.
  7478. stopNowIndicator: function() {
  7479. if (this.isNowIndicatorRendered) {
  7480. if (this.nowIndicatorTimeoutID) {
  7481. clearTimeout(this.nowIndicatorTimeoutID);
  7482. this.nowIndicatorTimeoutID = null;
  7483. }
  7484. if (this.nowIndicatorIntervalID) {
  7485. clearTimeout(this.nowIndicatorIntervalID);
  7486. this.nowIndicatorIntervalID = null;
  7487. }
  7488. this.unrenderNowIndicator();
  7489. this.isNowIndicatorRendered = false;
  7490. }
  7491. },
  7492. // Returns a string unit, like 'second' or 'minute' that defined how often the current time indicator
  7493. // should be refreshed. If something falsy is returned, no time indicator is rendered at all.
  7494. getNowIndicatorUnit: function() {
  7495. // subclasses should implement
  7496. },
  7497. // Renders a current time indicator at the given datetime
  7498. renderNowIndicator: function(date) {
  7499. // subclasses should implement
  7500. },
  7501. // Undoes the rendering actions from renderNowIndicator
  7502. unrenderNowIndicator: function() {
  7503. // subclasses should implement
  7504. },
  7505. /* Dimensions
  7506. ------------------------------------------------------------------------------------------------------------------*/
  7507. // Refreshes anything dependant upon sizing of the container element of the grid
  7508. updateSize: function(isResize) {
  7509. var scroll;
  7510. if (isResize) {
  7511. scroll = this.queryScroll();
  7512. }
  7513. this.updateHeight(isResize);
  7514. this.updateWidth(isResize);
  7515. this.updateNowIndicator();
  7516. if (isResize) {
  7517. this.applyScroll(scroll);
  7518. }
  7519. },
  7520. // Refreshes the horizontal dimensions of the calendar
  7521. updateWidth: function(isResize) {
  7522. // subclasses should implement
  7523. },
  7524. // Refreshes the vertical dimensions of the calendar
  7525. updateHeight: function(isResize) {
  7526. var calendar = this.calendar; // we poll the calendar for height information
  7527. this.setHeight(
  7528. calendar.getSuggestedViewHeight(),
  7529. calendar.isHeightAuto()
  7530. );
  7531. },
  7532. // Updates the vertical dimensions of the calendar to the specified height.
  7533. // if `isAuto` is set to true, height becomes merely a suggestion and the view should use its "natural" height.
  7534. setHeight: function(height, isAuto) {
  7535. // subclasses should implement
  7536. },
  7537. /* Scroller
  7538. ------------------------------------------------------------------------------------------------------------------*/
  7539. addForcedScroll: function(scroll) {
  7540. this.addScroll(
  7541. $.extend(scroll, { isForced: true })
  7542. );
  7543. },
  7544. addScroll: function(scroll) {
  7545. var queuedScroll = this.queuedScroll || (this.queuedScroll = {});
  7546. if (!queuedScroll.isForced) {
  7547. $.extend(queuedScroll, scroll);
  7548. }
  7549. },
  7550. popScroll: function() {
  7551. this.applyQueuedScroll();
  7552. this.queuedScroll = null;
  7553. },
  7554. applyQueuedScroll: function() {
  7555. if (this.queuedScroll) {
  7556. this.applyScroll(this.queuedScroll);
  7557. }
  7558. },
  7559. queryScroll: function() {
  7560. var scroll = {};
  7561. if (this.isDatesRendered) {
  7562. $.extend(scroll, this.queryDateScroll());
  7563. }
  7564. return scroll;
  7565. },
  7566. applyScroll: function(scroll) {
  7567. if (this.isDatesRendered) {
  7568. this.applyDateScroll(scroll);
  7569. }
  7570. },
  7571. computeInitialDateScroll: function() {
  7572. return {}; // subclasses must implement
  7573. },
  7574. queryDateScroll: function() {
  7575. return {}; // subclasses must implement
  7576. },
  7577. applyDateScroll: function(scroll) {
  7578. ; // subclasses must implement
  7579. },
  7580. /* Height Freezing
  7581. ------------------------------------------------------------------------------------------------------------------*/
  7582. freezeHeight: function() {
  7583. this.calendar.freezeContentHeight();
  7584. },
  7585. thawHeight: function() {
  7586. this.calendar.thawContentHeight();
  7587. },
  7588. // Event High-level Rendering
  7589. // -----------------------------------------------------------------------------------------------------------------
  7590. executeEventsRender: function(events) {
  7591. this.renderEvents(events);
  7592. this.isEventsRendered = true;
  7593. this.onEventsRender();
  7594. },
  7595. executeEventsUnrender: function() {
  7596. this.onBeforeEventsUnrender();
  7597. if (this.destroyEvents) {
  7598. this.destroyEvents(); // TODO: deprecate
  7599. }
  7600. this.unrenderEvents();
  7601. this.isEventsRendered = false;
  7602. },
  7603. // Event Rendering Triggers
  7604. // -----------------------------------------------------------------------------------------------------------------
  7605. // Signals that all events have been rendered
  7606. onEventsRender: function() {
  7607. this.applyScreenState();
  7608. this.renderedEventSegEach(function(seg) {
  7609. this.publiclyTrigger('eventAfterRender', seg.event, seg.event, seg.el);
  7610. });
  7611. this.publiclyTrigger('eventAfterAllRender');
  7612. },
  7613. // Signals that all event elements are about to be removed
  7614. onBeforeEventsUnrender: function() {
  7615. this.applyScreenState();
  7616. this.renderedEventSegEach(function(seg) {
  7617. this.publiclyTrigger('eventDestroy', seg.event, seg.event, seg.el);
  7618. });
  7619. },
  7620. applyScreenState: function() {
  7621. this.thawHeight();
  7622. this.freezeHeight();
  7623. this.applyQueuedScroll();
  7624. },
  7625. // Event Low-level Rendering
  7626. // -----------------------------------------------------------------------------------------------------------------
  7627. // Renders the events onto the view.
  7628. renderEvents: function(events) {
  7629. // subclasses should implement
  7630. },
  7631. // Removes event elements from the view.
  7632. unrenderEvents: function() {
  7633. // subclasses should implement
  7634. },
  7635. // Event Rendering Utils
  7636. // -----------------------------------------------------------------------------------------------------------------
  7637. // Given an event and the default element used for rendering, returns the element that should actually be used.
  7638. // Basically runs events and elements through the eventRender hook.
  7639. resolveEventEl: function(event, el) {
  7640. var custom = this.publiclyTrigger('eventRender', event, event, el);
  7641. if (custom === false) { // means don't render at all
  7642. el = null;
  7643. }
  7644. else if (custom && custom !== true) {
  7645. el = $(custom);
  7646. }
  7647. return el;
  7648. },
  7649. // Hides all rendered event segments linked to the given event
  7650. showEvent: function(event) {
  7651. this.renderedEventSegEach(function(seg) {
  7652. seg.el.css('visibility', '');
  7653. }, event);
  7654. },
  7655. // Shows all rendered event segments linked to the given event
  7656. hideEvent: function(event) {
  7657. this.renderedEventSegEach(function(seg) {
  7658. seg.el.css('visibility', 'hidden');
  7659. }, event);
  7660. },
  7661. // Iterates through event segments that have been rendered (have an el). Goes through all by default.
  7662. // If the optional `event` argument is specified, only iterates through segments linked to that event.
  7663. // The `this` value of the callback function will be the view.
  7664. renderedEventSegEach: function(func, event) {
  7665. var segs = this.getEventSegs();
  7666. var i;
  7667. for (i = 0; i < segs.length; i++) {
  7668. if (!event || segs[i].event._id === event._id) {
  7669. if (segs[i].el) {
  7670. func.call(this, segs[i]);
  7671. }
  7672. }
  7673. }
  7674. },
  7675. // Retrieves all the rendered segment objects for the view
  7676. getEventSegs: function() {
  7677. // subclasses must implement
  7678. return [];
  7679. },
  7680. /* Event Drag-n-Drop
  7681. ------------------------------------------------------------------------------------------------------------------*/
  7682. // Computes if the given event is allowed to be dragged by the user
  7683. isEventDraggable: function(event) {
  7684. return this.isEventStartEditable(event);
  7685. },
  7686. isEventStartEditable: function(event) {
  7687. return firstDefined(
  7688. event.startEditable,
  7689. (event.source || {}).startEditable,
  7690. this.opt('eventStartEditable'),
  7691. this.isEventGenerallyEditable(event)
  7692. );
  7693. },
  7694. isEventGenerallyEditable: function(event) {
  7695. return firstDefined(
  7696. event.editable,
  7697. (event.source || {}).editable,
  7698. this.opt('editable')
  7699. );
  7700. },
  7701. // Must be called when an event in the view is dropped onto new location.
  7702. // `dropLocation` is an object that contains the new zoned start/end/allDay values for the event.
  7703. reportSegDrop: function(seg, dropLocation, largeUnit, el, ev) {
  7704. var calendar = this.calendar;
  7705. var mutateResult = calendar.mutateSeg(seg, dropLocation, largeUnit);
  7706. var undoFunc = function() {
  7707. mutateResult.undo();
  7708. calendar.reportEventChange();
  7709. };
  7710. this.triggerEventDrop(seg.event, mutateResult.dateDelta, undoFunc, el, ev);
  7711. calendar.reportEventChange(); // will rerender events
  7712. },
  7713. // Triggers event-drop handlers that have subscribed via the API
  7714. triggerEventDrop: function(event, dateDelta, undoFunc, el, ev) {
  7715. this.publiclyTrigger('eventDrop', el[0], event, dateDelta, undoFunc, ev, {}); // {} = jqui dummy
  7716. },
  7717. /* External Element Drag-n-Drop
  7718. ------------------------------------------------------------------------------------------------------------------*/
  7719. // Must be called when an external element, via jQuery UI, has been dropped onto the calendar.
  7720. // `meta` is the parsed data that has been embedded into the dragging event.
  7721. // `dropLocation` is an object that contains the new zoned start/end/allDay values for the event.
  7722. reportExternalDrop: function(meta, dropLocation, el, ev, ui) {
  7723. var eventProps = meta.eventProps;
  7724. var eventInput;
  7725. var event;
  7726. // Try to build an event object and render it. TODO: decouple the two
  7727. if (eventProps) {
  7728. eventInput = $.extend({}, eventProps, dropLocation);
  7729. event = this.calendar.renderEvent(eventInput, meta.stick)[0]; // renderEvent returns an array
  7730. }
  7731. this.triggerExternalDrop(event, dropLocation, el, ev, ui);
  7732. },
  7733. // Triggers external-drop handlers that have subscribed via the API
  7734. triggerExternalDrop: function(event, dropLocation, el, ev, ui) {
  7735. // trigger 'drop' regardless of whether element represents an event
  7736. this.publiclyTrigger('drop', el[0], dropLocation.start, ev, ui);
  7737. if (event) {
  7738. this.publiclyTrigger('eventReceive', null, event); // signal an external event landed
  7739. }
  7740. },
  7741. /* Drag-n-Drop Rendering (for both events and external elements)
  7742. ------------------------------------------------------------------------------------------------------------------*/
  7743. // Renders a visual indication of a event or external-element drag over the given drop zone.
  7744. // If an external-element, seg will be `null`.
  7745. // Must return elements used for any mock events.
  7746. renderDrag: function(dropLocation, seg) {
  7747. // subclasses must implement
  7748. },
  7749. // Unrenders a visual indication of an event or external-element being dragged.
  7750. unrenderDrag: function() {
  7751. // subclasses must implement
  7752. },
  7753. /* Event Resizing
  7754. ------------------------------------------------------------------------------------------------------------------*/
  7755. // Computes if the given event is allowed to be resized from its starting edge
  7756. isEventResizableFromStart: function(event) {
  7757. return this.opt('eventResizableFromStart') && this.isEventResizable(event);
  7758. },
  7759. // Computes if the given event is allowed to be resized from its ending edge
  7760. isEventResizableFromEnd: function(event) {
  7761. return this.isEventResizable(event);
  7762. },
  7763. // Computes if the given event is allowed to be resized by the user at all
  7764. isEventResizable: function(event) {
  7765. var source = event.source || {};
  7766. return firstDefined(
  7767. event.durationEditable,
  7768. source.durationEditable,
  7769. this.opt('eventDurationEditable'),
  7770. event.editable,
  7771. source.editable,
  7772. this.opt('editable')
  7773. );
  7774. },
  7775. // Must be called when an event in the view has been resized to a new length
  7776. reportSegResize: function(seg, resizeLocation, largeUnit, el, ev) {
  7777. var calendar = this.calendar;
  7778. var mutateResult = calendar.mutateSeg(seg, resizeLocation, largeUnit);
  7779. var undoFunc = function() {
  7780. mutateResult.undo();
  7781. calendar.reportEventChange();
  7782. };
  7783. this.triggerEventResize(seg.event, mutateResult.durationDelta, undoFunc, el, ev);
  7784. calendar.reportEventChange(); // will rerender events
  7785. },
  7786. // Triggers event-resize handlers that have subscribed via the API
  7787. triggerEventResize: function(event, durationDelta, undoFunc, el, ev) {
  7788. this.publiclyTrigger('eventResize', el[0], event, durationDelta, undoFunc, ev, {}); // {} = jqui dummy
  7789. },
  7790. /* Selection (time range)
  7791. ------------------------------------------------------------------------------------------------------------------*/
  7792. // Selects a date span on the view. `start` and `end` are both Moments.
  7793. // `ev` is the native mouse event that begin the interaction.
  7794. select: function(span, ev) {
  7795. this.unselect(ev);
  7796. this.renderSelection(span);
  7797. this.reportSelection(span, ev);
  7798. },
  7799. // Renders a visual indication of the selection
  7800. renderSelection: function(span) {
  7801. // subclasses should implement
  7802. },
  7803. // Called when a new selection is made. Updates internal state and triggers handlers.
  7804. reportSelection: function(span, ev) {
  7805. this.isSelected = true;
  7806. this.triggerSelect(span, ev);
  7807. },
  7808. // Triggers handlers to 'select'
  7809. triggerSelect: function(span, ev) {
  7810. this.publiclyTrigger(
  7811. 'select',
  7812. null,
  7813. this.calendar.applyTimezone(span.start), // convert to calendar's tz for external API
  7814. this.calendar.applyTimezone(span.end), // "
  7815. ev
  7816. );
  7817. },
  7818. // Undoes a selection. updates in the internal state and triggers handlers.
  7819. // `ev` is the native mouse event that began the interaction.
  7820. unselect: function(ev) {
  7821. if (this.isSelected) {
  7822. this.isSelected = false;
  7823. if (this.destroySelection) {
  7824. this.destroySelection(); // TODO: deprecate
  7825. }
  7826. this.unrenderSelection();
  7827. this.publiclyTrigger('unselect', null, ev);
  7828. }
  7829. },
  7830. // Unrenders a visual indication of selection
  7831. unrenderSelection: function() {
  7832. // subclasses should implement
  7833. },
  7834. /* Event Selection
  7835. ------------------------------------------------------------------------------------------------------------------*/
  7836. selectEvent: function(event) {
  7837. if (!this.selectedEvent || this.selectedEvent !== event) {
  7838. this.unselectEvent();
  7839. this.renderedEventSegEach(function(seg) {
  7840. seg.el.addClass('fc-selected');
  7841. }, event);
  7842. this.selectedEvent = event;
  7843. }
  7844. },
  7845. unselectEvent: function() {
  7846. if (this.selectedEvent) {
  7847. this.renderedEventSegEach(function(seg) {
  7848. seg.el.removeClass('fc-selected');
  7849. }, this.selectedEvent);
  7850. this.selectedEvent = null;
  7851. }
  7852. },
  7853. isEventSelected: function(event) {
  7854. // event references might change on refetchEvents(), while selectedEvent doesn't,
  7855. // so compare IDs
  7856. return this.selectedEvent && this.selectedEvent._id === event._id;
  7857. },
  7858. /* Mouse / Touch Unselecting (time range & event unselection)
  7859. ------------------------------------------------------------------------------------------------------------------*/
  7860. // TODO: move consistently to down/start or up/end?
  7861. // TODO: don't kill previous selection if touch scrolling
  7862. handleDocumentMousedown: function(ev) {
  7863. if (isPrimaryMouseButton(ev)) {
  7864. this.processUnselect(ev);
  7865. }
  7866. },
  7867. processUnselect: function(ev) {
  7868. this.processRangeUnselect(ev);
  7869. this.processEventUnselect(ev);
  7870. },
  7871. processRangeUnselect: function(ev) {
  7872. var ignore;
  7873. // is there a time-range selection?
  7874. if (this.isSelected && this.opt('unselectAuto')) {
  7875. // only unselect if the clicked element is not identical to or inside of an 'unselectCancel' element
  7876. ignore = this.opt('unselectCancel');
  7877. if (!ignore || !$(ev.target).closest(ignore).length) {
  7878. this.unselect(ev);
  7879. }
  7880. }
  7881. },
  7882. processEventUnselect: function(ev) {
  7883. if (this.selectedEvent) {
  7884. if (!$(ev.target).closest('.fc-selected').length) {
  7885. this.unselectEvent();
  7886. }
  7887. }
  7888. },
  7889. /* Day Click
  7890. ------------------------------------------------------------------------------------------------------------------*/
  7891. // Triggers handlers to 'dayClick'
  7892. // Span has start/end of the clicked area. Only the start is useful.
  7893. triggerDayClick: function(span, dayEl, ev) {
  7894. this.publiclyTrigger(
  7895. 'dayClick',
  7896. dayEl,
  7897. this.calendar.applyTimezone(span.start), // convert to calendar's timezone for external API
  7898. ev
  7899. );
  7900. },
  7901. /* Date Utils
  7902. ------------------------------------------------------------------------------------------------------------------*/
  7903. // Returns the date range of the full days the given range visually appears to occupy.
  7904. // Returns a new range object.
  7905. computeDayRange: function(range) {
  7906. var startDay = range.start.clone().stripTime(); // the beginning of the day the range starts
  7907. var end = range.end;
  7908. var endDay = null;
  7909. var endTimeMS;
  7910. if (end) {
  7911. endDay = end.clone().stripTime(); // the beginning of the day the range exclusively ends
  7912. endTimeMS = +end.time(); // # of milliseconds into `endDay`
  7913. // If the end time is actually inclusively part of the next day and is equal to or
  7914. // beyond the next day threshold, adjust the end to be the exclusive end of `endDay`.
  7915. // Otherwise, leaving it as inclusive will cause it to exclude `endDay`.
  7916. if (endTimeMS && endTimeMS >= this.nextDayThreshold) {
  7917. endDay.add(1, 'days');
  7918. }
  7919. }
  7920. // If no end was specified, or if it is within `startDay` but not past nextDayThreshold,
  7921. // assign the default duration of one day.
  7922. if (!end || endDay <= startDay) {
  7923. endDay = startDay.clone().add(1, 'days');
  7924. }
  7925. return { start: startDay, end: endDay };
  7926. },
  7927. // Does the given event visually appear to occupy more than one day?
  7928. isMultiDayEvent: function(event) {
  7929. var range = this.computeDayRange(event); // event is range-ish
  7930. return range.end.diff(range.start, 'days') > 1;
  7931. }
  7932. });
  7933. View.watch('displayingDates', [ 'dateProfile' ], function(deps) {
  7934. this.requestDateRender(deps.dateProfile);
  7935. }, function() {
  7936. this.requestDateUnrender();
  7937. });
  7938. View.watch('initialEvents', [ 'dateProfile' ], function(deps) {
  7939. return this.fetchInitialEvents(deps.dateProfile);
  7940. });
  7941. View.watch('bindingEvents', [ 'initialEvents' ], function(deps) {
  7942. this.setEvents(deps.initialEvents);
  7943. this.bindEventChanges();
  7944. }, function() {
  7945. this.unbindEventChanges();
  7946. this.unsetEvents();
  7947. });
  7948. View.watch('displayingEvents', [ 'displayingDates', 'hasEvents' ], function() {
  7949. this.requestEventsRender(this.get('currentEvents')); // if there were event mutations after initialEvents
  7950. }, function() {
  7951. this.requestEventsUnrender();
  7952. });
  7953. ;;
  7954. View.mixin({
  7955. // range the view is formally responsible for.
  7956. // for example, a month view might have 1st-31st, excluding padded dates
  7957. currentRange: null,
  7958. currentRangeUnit: null, // name of largest unit being displayed, like "month" or "week"
  7959. // date range with a rendered skeleton
  7960. // includes not-active days that need some sort of DOM
  7961. renderRange: null,
  7962. // dates that display events and accept drag-n-drop
  7963. activeRange: null,
  7964. // constraint for where prev/next operations can go and where events can be dragged/resized to.
  7965. // an object with optional start and end properties.
  7966. validRange: null,
  7967. // how far the current date will move for a prev/next operation
  7968. dateIncrement: null,
  7969. minTime: null, // Duration object that denotes the first visible time of any given day
  7970. maxTime: null, // Duration object that denotes the exclusive visible end time of any given day
  7971. usesMinMaxTime: false, // whether minTime/maxTime will affect the activeRange. Views must opt-in.
  7972. // DEPRECATED
  7973. start: null, // use activeRange.start
  7974. end: null, // use activeRange.end
  7975. intervalStart: null, // use currentRange.start
  7976. intervalEnd: null, // use currentRange.end
  7977. /* Date Range Computation
  7978. ------------------------------------------------------------------------------------------------------------------*/
  7979. setDateProfileForRendering: function(dateProfile) {
  7980. this.currentRange = dateProfile.currentRange;
  7981. this.currentRangeUnit = dateProfile.currentRangeUnit;
  7982. this.renderRange = dateProfile.renderRange;
  7983. this.activeRange = dateProfile.activeRange;
  7984. this.validRange = dateProfile.validRange;
  7985. this.dateIncrement = dateProfile.dateIncrement;
  7986. this.minTime = dateProfile.minTime;
  7987. this.maxTime = dateProfile.maxTime;
  7988. // DEPRECATED, but we need to keep it updated
  7989. this.start = dateProfile.activeRange.start;
  7990. this.end = dateProfile.activeRange.end;
  7991. this.intervalStart = dateProfile.currentRange.start;
  7992. this.intervalEnd = dateProfile.currentRange.end;
  7993. },
  7994. // Builds a structure with info about what the dates/ranges will be for the "prev" view.
  7995. buildPrevDateProfile: function(date) {
  7996. var prevDate = date.clone().startOf(this.currentRangeUnit).subtract(this.dateIncrement);
  7997. return this.buildDateProfile(prevDate, -1);
  7998. },
  7999. // Builds a structure with info about what the dates/ranges will be for the "next" view.
  8000. buildNextDateProfile: function(date) {
  8001. var nextDate = date.clone().startOf(this.currentRangeUnit).add(this.dateIncrement);
  8002. return this.buildDateProfile(nextDate, 1);
  8003. },
  8004. // Builds a structure holding dates/ranges for rendering around the given date.
  8005. // Optional direction param indicates whether the date is being incremented/decremented
  8006. // from its previous value. decremented = -1, incremented = 1 (default).
  8007. buildDateProfile: function(date, direction, forceToValid) {
  8008. var validRange = this.buildValidRange();
  8009. var minTime = null;
  8010. var maxTime = null;
  8011. var currentInfo;
  8012. var renderRange;
  8013. var activeRange;
  8014. var isValid;
  8015. if (forceToValid) {
  8016. date = constrainDate(date, validRange);
  8017. }
  8018. currentInfo = this.buildCurrentRangeInfo(date, direction);
  8019. renderRange = this.buildRenderRange(currentInfo.range, currentInfo.unit);
  8020. activeRange = cloneRange(renderRange);
  8021. if (!this.opt('showNonCurrentDates')) {
  8022. activeRange = constrainRange(activeRange, currentInfo.range);
  8023. }
  8024. minTime = moment.duration(this.opt('minTime'));
  8025. maxTime = moment.duration(this.opt('maxTime'));
  8026. this.adjustActiveRange(activeRange, minTime, maxTime);
  8027. activeRange = constrainRange(activeRange, validRange);
  8028. date = constrainDate(date, activeRange);
  8029. // it's invalid if the originally requested date is not contained,
  8030. // or if the range is completely outside of the valid range.
  8031. isValid = doRangesIntersect(currentInfo.range, validRange);
  8032. return {
  8033. validRange: validRange,
  8034. currentRange: currentInfo.range,
  8035. currentRangeUnit: currentInfo.unit,
  8036. activeRange: activeRange,
  8037. renderRange: renderRange,
  8038. minTime: minTime,
  8039. maxTime: maxTime,
  8040. isValid: isValid,
  8041. date: date,
  8042. dateIncrement: this.buildDateIncrement(currentInfo.duration)
  8043. // pass a fallback (might be null) ^
  8044. };
  8045. },
  8046. // Builds an object with optional start/end properties.
  8047. // Indicates the minimum/maximum dates to display.
  8048. buildValidRange: function() {
  8049. return this.getRangeOption('validRange', this.calendar.getNow()) || {};
  8050. },
  8051. // Builds a structure with info about the "current" range, the range that is
  8052. // highlighted as being the current month for example.
  8053. // See buildDateProfile for a description of `direction`.
  8054. // Guaranteed to have `range` and `unit` properties. `duration` is optional.
  8055. buildCurrentRangeInfo: function(date, direction) {
  8056. var duration = null;
  8057. var unit = null;
  8058. var range = null;
  8059. var dayCount;
  8060. if (this.viewSpec.duration) {
  8061. duration = this.viewSpec.duration;
  8062. unit = this.viewSpec.durationUnit;
  8063. range = this.buildRangeFromDuration(date, direction, duration, unit);
  8064. }
  8065. else if ((dayCount = this.opt('dayCount'))) {
  8066. unit = 'day';
  8067. range = this.buildRangeFromDayCount(date, direction, dayCount);
  8068. }
  8069. else if ((range = this.buildCustomVisibleRange(date))) {
  8070. unit = computeGreatestUnit(range.start, range.end);
  8071. }
  8072. else {
  8073. duration = this.getFallbackDuration();
  8074. unit = computeGreatestUnit(duration);
  8075. range = this.buildRangeFromDuration(date, direction, duration, unit);
  8076. }
  8077. this.normalizeCurrentRange(range, unit); // modifies in-place
  8078. return { duration: duration, unit: unit, range: range };
  8079. },
  8080. getFallbackDuration: function() {
  8081. return moment.duration({ days: 1 });
  8082. },
  8083. // If the range has day units or larger, remove times. Otherwise, ensure times.
  8084. normalizeCurrentRange: function(range, unit) {
  8085. if (/^(year|month|week|day)$/.test(unit)) { // whole-days?
  8086. range.start.stripTime();
  8087. range.end.stripTime();
  8088. }
  8089. else { // needs to have a time?
  8090. if (!range.start.hasTime()) {
  8091. range.start.time(0); // give 00:00 time
  8092. }
  8093. if (!range.end.hasTime()) {
  8094. range.end.time(0); // give 00:00 time
  8095. }
  8096. }
  8097. },
  8098. // Mutates the given activeRange to have time values (un-ambiguate)
  8099. // if the minTime or maxTime causes the range to expand.
  8100. // TODO: eventually activeRange should *always* have times.
  8101. adjustActiveRange: function(range, minTime, maxTime) {
  8102. var hasSpecialTimes = false;
  8103. if (this.usesMinMaxTime) {
  8104. if (minTime < 0) {
  8105. range.start.time(0).add(minTime);
  8106. hasSpecialTimes = true;
  8107. }
  8108. if (maxTime > 24 * 60 * 60 * 1000) { // beyond 24 hours?
  8109. range.end.time(maxTime - (24 * 60 * 60 * 1000));
  8110. hasSpecialTimes = true;
  8111. }
  8112. if (hasSpecialTimes) {
  8113. if (!range.start.hasTime()) {
  8114. range.start.time(0);
  8115. }
  8116. if (!range.end.hasTime()) {
  8117. range.end.time(0);
  8118. }
  8119. }
  8120. }
  8121. },
  8122. // Builds the "current" range when it is specified as an explicit duration.
  8123. // `unit` is the already-computed computeGreatestUnit value of duration.
  8124. buildRangeFromDuration: function(date, direction, duration, unit) {
  8125. var alignment = this.opt('dateAlignment');
  8126. var start = date.clone();
  8127. var end;
  8128. var dateIncrementInput;
  8129. var dateIncrementDuration;
  8130. // if the view displays a single day or smaller
  8131. if (duration.as('days') <= 1) {
  8132. if (this.isHiddenDay(start)) {
  8133. start = this.skipHiddenDays(start, direction);
  8134. start.startOf('day');
  8135. }
  8136. }
  8137. // compute what the alignment should be
  8138. if (!alignment) {
  8139. dateIncrementInput = this.opt('dateIncrement');
  8140. if (dateIncrementInput) {
  8141. dateIncrementDuration = moment.duration(dateIncrementInput);
  8142. // use the smaller of the two units
  8143. if (dateIncrementDuration < duration) {
  8144. alignment = computeDurationGreatestUnit(dateIncrementDuration, dateIncrementInput);
  8145. }
  8146. else {
  8147. alignment = unit;
  8148. }
  8149. }
  8150. else {
  8151. alignment = unit;
  8152. }
  8153. }
  8154. start.startOf(alignment);
  8155. end = start.clone().add(duration);
  8156. return { start: start, end: end };
  8157. },
  8158. // Builds the "current" range when a dayCount is specified.
  8159. buildRangeFromDayCount: function(date, direction, dayCount) {
  8160. var customAlignment = this.opt('dateAlignment');
  8161. var runningCount = 0;
  8162. var start = date.clone();
  8163. var end;
  8164. if (customAlignment) {
  8165. start.startOf(customAlignment);
  8166. }
  8167. start.startOf('day');
  8168. start = this.skipHiddenDays(start, direction);
  8169. end = start.clone();
  8170. do {
  8171. end.add(1, 'day');
  8172. if (!this.isHiddenDay(end)) {
  8173. runningCount++;
  8174. }
  8175. } while (runningCount < dayCount);
  8176. return { start: start, end: end };
  8177. },
  8178. // Builds a normalized range object for the "visible" range,
  8179. // which is a way to define the currentRange and activeRange at the same time.
  8180. buildCustomVisibleRange: function(date) {
  8181. var visibleRange = this.getRangeOption(
  8182. 'visibleRange',
  8183. this.calendar.moment(date) // correct zone. also generates new obj that avoids mutations
  8184. );
  8185. if (visibleRange && (!visibleRange.start || !visibleRange.end)) {
  8186. return null;
  8187. }
  8188. return visibleRange;
  8189. },
  8190. // Computes the range that will represent the element/cells for *rendering*,
  8191. // but which may have voided days/times.
  8192. buildRenderRange: function(currentRange, currentRangeUnit) {
  8193. // cut off days in the currentRange that are hidden
  8194. return this.trimHiddenDays(currentRange);
  8195. },
  8196. // Compute the duration value that should be added/substracted to the current date
  8197. // when a prev/next operation happens.
  8198. buildDateIncrement: function(fallback) {
  8199. var dateIncrementInput = this.opt('dateIncrement');
  8200. var customAlignment;
  8201. if (dateIncrementInput) {
  8202. return moment.duration(dateIncrementInput);
  8203. }
  8204. else if ((customAlignment = this.opt('dateAlignment'))) {
  8205. return moment.duration(1, customAlignment);
  8206. }
  8207. else if (fallback) {
  8208. return fallback;
  8209. }
  8210. else {
  8211. return moment.duration({ days: 1 });
  8212. }
  8213. },
  8214. // Remove days from the beginning and end of the range that are computed as hidden.
  8215. trimHiddenDays: function(inputRange) {
  8216. return {
  8217. start: this.skipHiddenDays(inputRange.start),
  8218. end: this.skipHiddenDays(inputRange.end, -1, true) // exclusively move backwards
  8219. };
  8220. },
  8221. // Compute the number of the give units in the "current" range.
  8222. // Will return a floating-point number. Won't round.
  8223. currentRangeAs: function(unit) {
  8224. var currentRange = this.currentRange;
  8225. return currentRange.end.diff(currentRange.start, unit, true);
  8226. },
  8227. // Arguments after name will be forwarded to a hypothetical function value
  8228. // WARNING: passed-in arguments will be given to generator functions as-is and can cause side-effects.
  8229. // Always clone your objects if you fear mutation.
  8230. getRangeOption: function(name) {
  8231. var val = this.opt(name);
  8232. if (typeof val === 'function') {
  8233. val = val.apply(
  8234. null,
  8235. Array.prototype.slice.call(arguments, 1)
  8236. );
  8237. }
  8238. if (val) {
  8239. return this.calendar.parseRange(val);
  8240. }
  8241. },
  8242. /* Hidden Days
  8243. ------------------------------------------------------------------------------------------------------------------*/
  8244. // Initializes internal variables related to calculating hidden days-of-week
  8245. initHiddenDays: function() {
  8246. var hiddenDays = this.opt('hiddenDays') || []; // array of day-of-week indices that are hidden
  8247. var isHiddenDayHash = []; // is the day-of-week hidden? (hash with day-of-week-index -> bool)
  8248. var dayCnt = 0;
  8249. var i;
  8250. if (this.opt('weekends') === false) {
  8251. hiddenDays.push(0, 6); // 0=sunday, 6=saturday
  8252. }
  8253. for (i = 0; i < 7; i++) {
  8254. if (
  8255. !(isHiddenDayHash[i] = $.inArray(i, hiddenDays) !== -1)
  8256. ) {
  8257. dayCnt++;
  8258. }
  8259. }
  8260. if (!dayCnt) {
  8261. throw 'invalid hiddenDays'; // all days were hidden? bad.
  8262. }
  8263. this.isHiddenDayHash = isHiddenDayHash;
  8264. },
  8265. // Is the current day hidden?
  8266. // `day` is a day-of-week index (0-6), or a Moment
  8267. isHiddenDay: function(day) {
  8268. if (moment.isMoment(day)) {
  8269. day = day.day();
  8270. }
  8271. return this.isHiddenDayHash[day];
  8272. },
  8273. // Incrementing the current day until it is no longer a hidden day, returning a copy.
  8274. // DOES NOT CONSIDER validRange!
  8275. // If the initial value of `date` is not a hidden day, don't do anything.
  8276. // Pass `isExclusive` as `true` if you are dealing with an end date.
  8277. // `inc` defaults to `1` (increment one day forward each time)
  8278. skipHiddenDays: function(date, inc, isExclusive) {
  8279. var out = date.clone();
  8280. inc = inc || 1;
  8281. while (
  8282. this.isHiddenDayHash[(out.day() + (isExclusive ? inc : 0) + 7) % 7]
  8283. ) {
  8284. out.add(inc, 'days');
  8285. }
  8286. return out;
  8287. }
  8288. });
  8289. ;;
  8290. /*
  8291. Embodies a div that has potential scrollbars
  8292. */
  8293. var Scroller = FC.Scroller = Class.extend({
  8294. el: null, // the guaranteed outer element
  8295. scrollEl: null, // the element with the scrollbars
  8296. overflowX: null,
  8297. overflowY: null,
  8298. constructor: function(options) {
  8299. options = options || {};
  8300. this.overflowX = options.overflowX || options.overflow || 'auto';
  8301. this.overflowY = options.overflowY || options.overflow || 'auto';
  8302. },
  8303. render: function() {
  8304. this.el = this.renderEl();
  8305. this.applyOverflow();
  8306. },
  8307. renderEl: function() {
  8308. return (this.scrollEl = $('<div class="fc-scroller"></div>'));
  8309. },
  8310. // sets to natural height, unlocks overflow
  8311. clear: function() {
  8312. this.setHeight('auto');
  8313. this.applyOverflow();
  8314. },
  8315. destroy: function() {
  8316. this.el.remove();
  8317. },
  8318. // Overflow
  8319. // -----------------------------------------------------------------------------------------------------------------
  8320. applyOverflow: function() {
  8321. this.scrollEl.css({
  8322. 'overflow-x': this.overflowX,
  8323. 'overflow-y': this.overflowY
  8324. });
  8325. },
  8326. // Causes any 'auto' overflow values to resolves to 'scroll' or 'hidden'.
  8327. // Useful for preserving scrollbar widths regardless of future resizes.
  8328. // Can pass in scrollbarWidths for optimization.
  8329. lockOverflow: function(scrollbarWidths) {
  8330. var overflowX = this.overflowX;
  8331. var overflowY = this.overflowY;
  8332. scrollbarWidths = scrollbarWidths || this.getScrollbarWidths();
  8333. if (overflowX === 'auto') {
  8334. overflowX = (
  8335. scrollbarWidths.top || scrollbarWidths.bottom || // horizontal scrollbars?
  8336. // OR scrolling pane with massless scrollbars?
  8337. this.scrollEl[0].scrollWidth - 1 > this.scrollEl[0].clientWidth
  8338. // subtract 1 because of IE off-by-one issue
  8339. ) ? 'scroll' : 'hidden';
  8340. }
  8341. if (overflowY === 'auto') {
  8342. overflowY = (
  8343. scrollbarWidths.left || scrollbarWidths.right || // vertical scrollbars?
  8344. // OR scrolling pane with massless scrollbars?
  8345. this.scrollEl[0].scrollHeight - 1 > this.scrollEl[0].clientHeight
  8346. // subtract 1 because of IE off-by-one issue
  8347. ) ? 'scroll' : 'hidden';
  8348. }
  8349. this.scrollEl.css({ 'overflow-x': overflowX, 'overflow-y': overflowY });
  8350. },
  8351. // Getters / Setters
  8352. // -----------------------------------------------------------------------------------------------------------------
  8353. setHeight: function(height) {
  8354. this.scrollEl.height(height);
  8355. },
  8356. getScrollTop: function() {
  8357. return this.scrollEl.scrollTop();
  8358. },
  8359. setScrollTop: function(top) {
  8360. this.scrollEl.scrollTop(top);
  8361. },
  8362. getClientWidth: function() {
  8363. return this.scrollEl[0].clientWidth;
  8364. },
  8365. getClientHeight: function() {
  8366. return this.scrollEl[0].clientHeight;
  8367. },
  8368. getScrollbarWidths: function() {
  8369. return getScrollbarWidths(this.scrollEl);
  8370. }
  8371. });
  8372. ;;
  8373. function Iterator(items) {
  8374. this.items = items || [];
  8375. }
  8376. /* Calls a method on every item passing the arguments through */
  8377. Iterator.prototype.proxyCall = function(methodName) {
  8378. var args = Array.prototype.slice.call(arguments, 1);
  8379. var results = [];
  8380. this.items.forEach(function(item) {
  8381. results.push(item[methodName].apply(item, args));
  8382. });
  8383. return results;
  8384. };
  8385. ;;
  8386. /* Toolbar with buttons and title
  8387. ----------------------------------------------------------------------------------------------------------------------*/
  8388. function Toolbar(calendar, toolbarOptions) {
  8389. var t = this;
  8390. // exports
  8391. t.setToolbarOptions = setToolbarOptions;
  8392. t.render = render;
  8393. t.removeElement = removeElement;
  8394. t.updateTitle = updateTitle;
  8395. t.activateButton = activateButton;
  8396. t.deactivateButton = deactivateButton;
  8397. t.disableButton = disableButton;
  8398. t.enableButton = enableButton;
  8399. t.getViewsWithButtons = getViewsWithButtons;
  8400. t.el = null; // mirrors local `el`
  8401. // locals
  8402. var el;
  8403. var viewsWithButtons = [];
  8404. var tm;
  8405. // method to update toolbar-specific options, not calendar-wide options
  8406. function setToolbarOptions(newToolbarOptions) {
  8407. toolbarOptions = newToolbarOptions;
  8408. }
  8409. // can be called repeatedly and will rerender
  8410. function render() {
  8411. var sections = toolbarOptions.layout;
  8412. tm = calendar.opt('theme') ? 'ui' : 'fc';
  8413. if (sections) {
  8414. if (!el) {
  8415. el = this.el = $("<div class='fc-toolbar "+ toolbarOptions.extraClasses + "'/>");
  8416. }
  8417. else {
  8418. el.empty();
  8419. }
  8420. el.append(renderSection('left'))
  8421. .append(renderSection('right'))
  8422. .append(renderSection('center'))
  8423. .append('<div class="fc-clear"/>');
  8424. }
  8425. else {
  8426. removeElement();
  8427. }
  8428. }
  8429. function removeElement() {
  8430. if (el) {
  8431. el.remove();
  8432. el = t.el = null;
  8433. }
  8434. }
  8435. function renderSection(position) {
  8436. var sectionEl = $('<div class="fc-' + position + '"/>');
  8437. var buttonStr = toolbarOptions.layout[position];
  8438. var calendarCustomButtons = calendar.opt('customButtons') || {};
  8439. var calendarButtonText = calendar.opt('buttonText') || {};
  8440. if (buttonStr) {
  8441. $.each(buttonStr.split(' '), function(i) {
  8442. var groupChildren = $();
  8443. var isOnlyButtons = true;
  8444. var groupEl;
  8445. $.each(this.split(','), function(j, buttonName) {
  8446. var customButtonProps;
  8447. var viewSpec;
  8448. var buttonClick;
  8449. var overrideText; // text explicitly set by calendar's constructor options. overcomes icons
  8450. var defaultText;
  8451. var themeIcon;
  8452. var normalIcon;
  8453. var innerHtml;
  8454. var classes;
  8455. var button; // the element
  8456. if (buttonName == 'title') {
  8457. groupChildren = groupChildren.add($('<h2>&nbsp;</h2>')); // we always want it to take up height
  8458. isOnlyButtons = false;
  8459. }
  8460. else {
  8461. if ((customButtonProps = calendarCustomButtons[buttonName])) {
  8462. buttonClick = function(ev) {
  8463. if (customButtonProps.click) {
  8464. customButtonProps.click.call(button[0], ev);
  8465. }
  8466. };
  8467. overrideText = ''; // icons will override text
  8468. defaultText = customButtonProps.text;
  8469. }
  8470. else if ((viewSpec = calendar.getViewSpec(buttonName))) {
  8471. buttonClick = function() {
  8472. calendar.changeView(buttonName);
  8473. };
  8474. viewsWithButtons.push(buttonName);
  8475. overrideText = viewSpec.buttonTextOverride;
  8476. defaultText = viewSpec.buttonTextDefault;
  8477. }
  8478. else if (calendar[buttonName]) { // a calendar method
  8479. buttonClick = function() {
  8480. calendar[buttonName]();
  8481. };
  8482. overrideText = (calendar.overrides.buttonText || {})[buttonName];
  8483. defaultText = calendarButtonText[buttonName]; // everything else is considered default
  8484. }
  8485. if (buttonClick) {
  8486. themeIcon =
  8487. customButtonProps ?
  8488. customButtonProps.themeIcon :
  8489. calendar.opt('themeButtonIcons')[buttonName];
  8490. normalIcon =
  8491. customButtonProps ?
  8492. customButtonProps.icon :
  8493. calendar.opt('buttonIcons')[buttonName];
  8494. if (overrideText) {
  8495. innerHtml = htmlEscape(overrideText);
  8496. }
  8497. else if (themeIcon && calendar.opt('theme')) {
  8498. innerHtml = "<span class='ui-icon ui-icon-" + themeIcon + "'></span>";
  8499. }
  8500. else if (normalIcon && !calendar.opt('theme')) {
  8501. innerHtml = "<span class='fc-icon fc-icon-" + normalIcon + "'></span>";
  8502. }
  8503. else {
  8504. innerHtml = htmlEscape(defaultText);
  8505. }
  8506. classes = [
  8507. 'fc-' + buttonName + '-button',
  8508. tm + '-button',
  8509. tm + '-state-default'
  8510. ];
  8511. button = $( // type="button" so that it doesn't submit a form
  8512. '<button type="button" class="' + classes.join(' ') + '">' +
  8513. innerHtml +
  8514. '</button>'
  8515. )
  8516. .click(function(ev) {
  8517. // don't process clicks for disabled buttons
  8518. if (!button.hasClass(tm + '-state-disabled')) {
  8519. buttonClick(ev);
  8520. // after the click action, if the button becomes the "active" tab, or disabled,
  8521. // it should never have a hover class, so remove it now.
  8522. if (
  8523. button.hasClass(tm + '-state-active') ||
  8524. button.hasClass(tm + '-state-disabled')
  8525. ) {
  8526. button.removeClass(tm + '-state-hover');
  8527. }
  8528. }
  8529. })
  8530. .mousedown(function() {
  8531. // the *down* effect (mouse pressed in).
  8532. // only on buttons that are not the "active" tab, or disabled
  8533. button
  8534. .not('.' + tm + '-state-active')
  8535. .not('.' + tm + '-state-disabled')
  8536. .addClass(tm + '-state-down');
  8537. })
  8538. .mouseup(function() {
  8539. // undo the *down* effect
  8540. button.removeClass(tm + '-state-down');
  8541. })
  8542. .hover(
  8543. function() {
  8544. // the *hover* effect.
  8545. // only on buttons that are not the "active" tab, or disabled
  8546. button
  8547. .not('.' + tm + '-state-active')
  8548. .not('.' + tm + '-state-disabled')
  8549. .addClass(tm + '-state-hover');
  8550. },
  8551. function() {
  8552. // undo the *hover* effect
  8553. button
  8554. .removeClass(tm + '-state-hover')
  8555. .removeClass(tm + '-state-down'); // if mouseleave happens before mouseup
  8556. }
  8557. );
  8558. groupChildren = groupChildren.add(button);
  8559. }
  8560. }
  8561. });
  8562. if (isOnlyButtons) {
  8563. groupChildren
  8564. .first().addClass(tm + '-corner-left').end()
  8565. .last().addClass(tm + '-corner-right').end();
  8566. }
  8567. if (groupChildren.length > 1) {
  8568. groupEl = $('<div/>');
  8569. if (isOnlyButtons) {
  8570. groupEl.addClass('fc-button-group');
  8571. }
  8572. groupEl.append(groupChildren);
  8573. sectionEl.append(groupEl);
  8574. }
  8575. else {
  8576. sectionEl.append(groupChildren); // 1 or 0 children
  8577. }
  8578. });
  8579. }
  8580. return sectionEl;
  8581. }
  8582. function updateTitle(text) {
  8583. if (el) {
  8584. el.find('h2').text(text);
  8585. }
  8586. }
  8587. function activateButton(buttonName) {
  8588. if (el) {
  8589. el.find('.fc-' + buttonName + '-button')
  8590. .addClass(tm + '-state-active');
  8591. }
  8592. }
  8593. function deactivateButton(buttonName) {
  8594. if (el) {
  8595. el.find('.fc-' + buttonName + '-button')
  8596. .removeClass(tm + '-state-active');
  8597. }
  8598. }
  8599. function disableButton(buttonName) {
  8600. if (el) {
  8601. el.find('.fc-' + buttonName + '-button')
  8602. .prop('disabled', true)
  8603. .addClass(tm + '-state-disabled');
  8604. }
  8605. }
  8606. function enableButton(buttonName) {
  8607. if (el) {
  8608. el.find('.fc-' + buttonName + '-button')
  8609. .prop('disabled', false)
  8610. .removeClass(tm + '-state-disabled');
  8611. }
  8612. }
  8613. function getViewsWithButtons() {
  8614. return viewsWithButtons;
  8615. }
  8616. }
  8617. ;;
  8618. var Calendar = FC.Calendar = Class.extend(EmitterMixin, {
  8619. view: null, // current View object
  8620. viewsByType: null, // holds all instantiated view instances, current or not
  8621. currentDate: null, // unzoned moment. private (public API should use getDate instead)
  8622. loadingLevel: 0, // number of simultaneous loading tasks
  8623. constructor: function(el, overrides) {
  8624. // declare the current calendar instance relies on GlobalEmitter. needed for garbage collection.
  8625. // unneeded() is called in destroy.
  8626. GlobalEmitter.needed();
  8627. this.el = el;
  8628. this.viewsByType = {};
  8629. this.viewSpecCache = {};
  8630. this.initOptionsInternals(overrides);
  8631. this.initMomentInternals(); // needs to happen after options hash initialized
  8632. this.initCurrentDate();
  8633. EventManager.call(this); // needs options immediately
  8634. this.initialize();
  8635. },
  8636. // Subclasses can override this for initialization logic after the constructor has been called
  8637. initialize: function() {
  8638. },
  8639. // Public API
  8640. // -----------------------------------------------------------------------------------------------------------------
  8641. getCalendar: function() {
  8642. return this;
  8643. },
  8644. getView: function() {
  8645. return this.view;
  8646. },
  8647. publiclyTrigger: function(name, thisObj) {
  8648. var args = Array.prototype.slice.call(arguments, 2);
  8649. var optHandler = this.opt(name);
  8650. thisObj = thisObj || this.el[0];
  8651. this.triggerWith(name, thisObj, args); // Emitter's method
  8652. if (optHandler) {
  8653. return optHandler.apply(thisObj, args);
  8654. }
  8655. },
  8656. // View
  8657. // -----------------------------------------------------------------------------------------------------------------
  8658. // Given a view name for a custom view or a standard view, creates a ready-to-go View object
  8659. instantiateView: function(viewType) {
  8660. var spec = this.getViewSpec(viewType);
  8661. return new spec['class'](this, spec);
  8662. },
  8663. // Returns a boolean about whether the view is okay to instantiate at some point
  8664. isValidViewType: function(viewType) {
  8665. return Boolean(this.getViewSpec(viewType));
  8666. },
  8667. changeView: function(viewName, dateOrRange) {
  8668. if (dateOrRange) {
  8669. if (dateOrRange.start && dateOrRange.end) { // a range
  8670. this.recordOptionOverrides({ // will not rerender
  8671. visibleRange: dateOrRange
  8672. });
  8673. }
  8674. else { // a date
  8675. this.currentDate = this.moment(dateOrRange).stripZone(); // just like gotoDate
  8676. }
  8677. }
  8678. this.renderView(viewName);
  8679. },
  8680. // Forces navigation to a view for the given date.
  8681. // `viewType` can be a specific view name or a generic one like "week" or "day".
  8682. zoomTo: function(newDate, viewType) {
  8683. var spec;
  8684. viewType = viewType || 'day'; // day is default zoom
  8685. spec = this.getViewSpec(viewType) || this.getUnitViewSpec(viewType);
  8686. this.currentDate = newDate.clone();
  8687. this.renderView(spec ? spec.type : null);
  8688. },
  8689. // Current Date
  8690. // -----------------------------------------------------------------------------------------------------------------
  8691. initCurrentDate: function() {
  8692. var defaultDateInput = this.opt('defaultDate');
  8693. // compute the initial ambig-timezone date
  8694. if (defaultDateInput != null) {
  8695. this.currentDate = this.moment(defaultDateInput).stripZone();
  8696. }
  8697. else {
  8698. this.currentDate = this.getNow(); // getNow already returns unzoned
  8699. }
  8700. },
  8701. prev: function() {
  8702. var prevInfo = this.view.buildPrevDateProfile(this.currentDate);
  8703. if (prevInfo.isValid) {
  8704. this.currentDate = prevInfo.date;
  8705. this.renderView();
  8706. }
  8707. },
  8708. next: function() {
  8709. var nextInfo = this.view.buildNextDateProfile(this.currentDate);
  8710. if (nextInfo.isValid) {
  8711. this.currentDate = nextInfo.date;
  8712. this.renderView();
  8713. }
  8714. },
  8715. prevYear: function() {
  8716. this.currentDate.add(-1, 'years');
  8717. this.renderView();
  8718. },
  8719. nextYear: function() {
  8720. this.currentDate.add(1, 'years');
  8721. this.renderView();
  8722. },
  8723. today: function() {
  8724. this.currentDate = this.getNow(); // should deny like prev/next?
  8725. this.renderView();
  8726. },
  8727. gotoDate: function(zonedDateInput) {
  8728. this.currentDate = this.moment(zonedDateInput).stripZone();
  8729. this.renderView();
  8730. },
  8731. incrementDate: function(delta) {
  8732. this.currentDate.add(moment.duration(delta));
  8733. this.renderView();
  8734. },
  8735. // for external API
  8736. getDate: function() {
  8737. return this.applyTimezone(this.currentDate); // infuse the calendar's timezone
  8738. },
  8739. // Loading Triggering
  8740. // -----------------------------------------------------------------------------------------------------------------
  8741. // Should be called when any type of async data fetching begins
  8742. pushLoading: function() {
  8743. if (!(this.loadingLevel++)) {
  8744. this.publiclyTrigger('loading', null, true, this.view);
  8745. }
  8746. },
  8747. // Should be called when any type of async data fetching completes
  8748. popLoading: function() {
  8749. if (!(--this.loadingLevel)) {
  8750. this.publiclyTrigger('loading', null, false, this.view);
  8751. }
  8752. },
  8753. // Selection
  8754. // -----------------------------------------------------------------------------------------------------------------
  8755. // this public method receives start/end dates in any format, with any timezone
  8756. select: function(zonedStartInput, zonedEndInput) {
  8757. this.view.select(
  8758. this.buildSelectSpan.apply(this, arguments)
  8759. );
  8760. },
  8761. unselect: function() { // safe to be called before renderView
  8762. if (this.view) {
  8763. this.view.unselect();
  8764. }
  8765. },
  8766. // Given arguments to the select method in the API, returns a span (unzoned start/end and other info)
  8767. buildSelectSpan: function(zonedStartInput, zonedEndInput) {
  8768. var start = this.moment(zonedStartInput).stripZone();
  8769. var end;
  8770. if (zonedEndInput) {
  8771. end = this.moment(zonedEndInput).stripZone();
  8772. }
  8773. else if (start.hasTime()) {
  8774. end = start.clone().add(this.defaultTimedEventDuration);
  8775. }
  8776. else {
  8777. end = start.clone().add(this.defaultAllDayEventDuration);
  8778. }
  8779. return { start: start, end: end };
  8780. },
  8781. // Misc
  8782. // -----------------------------------------------------------------------------------------------------------------
  8783. // will return `null` if invalid range
  8784. parseRange: function(rangeInput) {
  8785. var start = null;
  8786. var end = null;
  8787. if (rangeInput.start) {
  8788. start = this.moment(rangeInput.start).stripZone();
  8789. }
  8790. if (rangeInput.end) {
  8791. end = this.moment(rangeInput.end).stripZone();
  8792. }
  8793. if (!start && !end) {
  8794. return null;
  8795. }
  8796. if (start && end && end.isBefore(start)) {
  8797. return null;
  8798. }
  8799. return { start: start, end: end };
  8800. },
  8801. rerenderEvents: function() { // API method. destroys old events if previously rendered.
  8802. if (this.elementVisible()) {
  8803. this.reportEventChange(); // will re-trasmit events to the view, causing a rerender
  8804. }
  8805. }
  8806. });
  8807. ;;
  8808. /*
  8809. Options binding/triggering system.
  8810. */
  8811. Calendar.mixin({
  8812. dirDefaults: null, // option defaults related to LTR or RTL
  8813. localeDefaults: null, // option defaults related to current locale
  8814. overrides: null, // option overrides given to the fullCalendar constructor
  8815. dynamicOverrides: null, // options set with dynamic setter method. higher precedence than view overrides.
  8816. optionsModel: null, // all defaults combined with overrides
  8817. initOptionsInternals: function(overrides) {
  8818. this.overrides = $.extend({}, overrides); // make a copy
  8819. this.dynamicOverrides = {};
  8820. this.optionsModel = new Model();
  8821. this.populateOptionsHash();
  8822. },
  8823. // public getter/setter
  8824. option: function(name, value) {
  8825. var newOptionHash;
  8826. if (typeof name === 'string') {
  8827. if (value === undefined) { // getter
  8828. return this.optionsModel.get(name);
  8829. }
  8830. else { // setter for individual option
  8831. newOptionHash = {};
  8832. newOptionHash[name] = value;
  8833. this.setOptions(newOptionHash);
  8834. }
  8835. }
  8836. else if (typeof name === 'object') { // compound setter with object input
  8837. this.setOptions(name);
  8838. }
  8839. },
  8840. // private getter
  8841. opt: function(name) {
  8842. return this.optionsModel.get(name);
  8843. },
  8844. setOptions: function(newOptionHash) {
  8845. var optionCnt = 0;
  8846. var optionName;
  8847. this.recordOptionOverrides(newOptionHash);
  8848. for (optionName in newOptionHash) {
  8849. optionCnt++;
  8850. }
  8851. // special-case handling of single option change.
  8852. // if only one option change, `optionName` will be its name.
  8853. if (optionCnt === 1) {
  8854. if (optionName === 'height' || optionName === 'contentHeight' || optionName === 'aspectRatio') {
  8855. this.updateSize(true); // true = allow recalculation of height
  8856. return;
  8857. }
  8858. else if (optionName === 'defaultDate') {
  8859. return; // can't change date this way. use gotoDate instead
  8860. }
  8861. else if (optionName === 'businessHours') {
  8862. if (this.view) {
  8863. this.view.unrenderBusinessHours();
  8864. this.view.renderBusinessHours();
  8865. }
  8866. return;
  8867. }
  8868. else if (optionName === 'timezone') {
  8869. this.rezoneArrayEventSources();
  8870. this.refetchEvents();
  8871. return;
  8872. }
  8873. }
  8874. // catch-all. rerender the header and footer and rebuild/rerender the current view
  8875. this.renderHeader();
  8876. this.renderFooter();
  8877. // even non-current views will be affected by this option change. do before rerender
  8878. // TODO: detangle
  8879. this.viewsByType = {};
  8880. this.reinitView();
  8881. },
  8882. // Computes the flattened options hash for the calendar and assigns to `this.options`.
  8883. // Assumes this.overrides and this.dynamicOverrides have already been initialized.
  8884. populateOptionsHash: function() {
  8885. var locale, localeDefaults;
  8886. var isRTL, dirDefaults;
  8887. var rawOptions;
  8888. locale = firstDefined( // explicit locale option given?
  8889. this.dynamicOverrides.locale,
  8890. this.overrides.locale
  8891. );
  8892. localeDefaults = localeOptionHash[locale];
  8893. if (!localeDefaults) { // explicit locale option not given or invalid?
  8894. locale = Calendar.defaults.locale;
  8895. localeDefaults = localeOptionHash[locale] || {};
  8896. }
  8897. isRTL = firstDefined( // based on options computed so far, is direction RTL?
  8898. this.dynamicOverrides.isRTL,
  8899. this.overrides.isRTL,
  8900. localeDefaults.isRTL,
  8901. Calendar.defaults.isRTL
  8902. );
  8903. dirDefaults = isRTL ? Calendar.rtlDefaults : {};
  8904. this.dirDefaults = dirDefaults;
  8905. this.localeDefaults = localeDefaults;
  8906. rawOptions = mergeOptions([ // merge defaults and overrides. lowest to highest precedence
  8907. Calendar.defaults, // global defaults
  8908. dirDefaults,
  8909. localeDefaults,
  8910. this.overrides,
  8911. this.dynamicOverrides
  8912. ]);
  8913. populateInstanceComputableOptions(rawOptions); // fill in gaps with computed options
  8914. this.optionsModel.reset(rawOptions);
  8915. },
  8916. // stores the new options internally, but does not rerender anything.
  8917. recordOptionOverrides: function(newOptionHash) {
  8918. var optionName;
  8919. for (optionName in newOptionHash) {
  8920. this.dynamicOverrides[optionName] = newOptionHash[optionName];
  8921. }
  8922. this.viewSpecCache = {}; // the dynamic override invalidates the options in this cache, so just clear it
  8923. this.populateOptionsHash(); // this.options needs to be recomputed after the dynamic override
  8924. }
  8925. });
  8926. ;;
  8927. Calendar.mixin({
  8928. defaultAllDayEventDuration: null,
  8929. defaultTimedEventDuration: null,
  8930. localeData: null,
  8931. initMomentInternals: function() {
  8932. var _this = this;
  8933. this.defaultAllDayEventDuration = moment.duration(this.opt('defaultAllDayEventDuration'));
  8934. this.defaultTimedEventDuration = moment.duration(this.opt('defaultTimedEventDuration'));
  8935. // Called immediately, and when any of the options change.
  8936. // Happens before any internal objects rebuild or rerender, because this is very core.
  8937. this.optionsModel.watch('buildingMomentLocale', [
  8938. '?locale', '?monthNames', '?monthNamesShort', '?dayNames', '?dayNamesShort',
  8939. '?firstDay', '?weekNumberCalculation'
  8940. ], function(opts) {
  8941. var weekNumberCalculation = opts.weekNumberCalculation;
  8942. var firstDay = opts.firstDay;
  8943. var _week;
  8944. // normalize
  8945. if (weekNumberCalculation === 'iso') {
  8946. weekNumberCalculation = 'ISO'; // normalize
  8947. }
  8948. var localeData = createObject( // make a cheap copy
  8949. getMomentLocaleData(opts.locale) // will fall back to en
  8950. );
  8951. if (opts.monthNames) {
  8952. localeData._months = opts.monthNames;
  8953. }
  8954. if (opts.monthNamesShort) {
  8955. localeData._monthsShort = opts.monthNamesShort;
  8956. }
  8957. if (opts.dayNames) {
  8958. localeData._weekdays = opts.dayNames;
  8959. }
  8960. if (opts.dayNamesShort) {
  8961. localeData._weekdaysShort = opts.dayNamesShort;
  8962. }
  8963. if (firstDay == null && weekNumberCalculation === 'ISO') {
  8964. firstDay = 1;
  8965. }
  8966. if (firstDay != null) {
  8967. _week = createObject(localeData._week); // _week: { dow: # }
  8968. _week.dow = firstDay;
  8969. localeData._week = _week;
  8970. }
  8971. if ( // whitelist certain kinds of input
  8972. weekNumberCalculation === 'ISO' ||
  8973. weekNumberCalculation === 'local' ||
  8974. typeof weekNumberCalculation === 'function'
  8975. ) {
  8976. localeData._fullCalendar_weekCalc = weekNumberCalculation; // moment-ext will know what to do with it
  8977. }
  8978. _this.localeData = localeData;
  8979. // If the internal current date object already exists, move to new locale.
  8980. // We do NOT need to do this technique for event dates, because this happens when converting to "segments".
  8981. if (_this.currentDate) {
  8982. _this.localizeMoment(_this.currentDate); // sets to localeData
  8983. }
  8984. });
  8985. },
  8986. // Builds a moment using the settings of the current calendar: timezone and locale.
  8987. // Accepts anything the vanilla moment() constructor accepts.
  8988. moment: function() {
  8989. var mom;
  8990. if (this.opt('timezone') === 'local') {
  8991. mom = FC.moment.apply(null, arguments);
  8992. // Force the moment to be local, because FC.moment doesn't guarantee it.
  8993. if (mom.hasTime()) { // don't give ambiguously-timed moments a local zone
  8994. mom.local();
  8995. }
  8996. }
  8997. else if (this.opt('timezone') === 'UTC') {
  8998. mom = FC.moment.utc.apply(null, arguments); // process as UTC
  8999. }
  9000. else {
  9001. mom = FC.moment.parseZone.apply(null, arguments); // let the input decide the zone
  9002. }
  9003. this.localizeMoment(mom); // TODO
  9004. return mom;
  9005. },
  9006. // Updates the given moment's locale settings to the current calendar locale settings.
  9007. localizeMoment: function(mom) {
  9008. mom._locale = this.localeData;
  9009. },
  9010. // Returns a boolean about whether or not the calendar knows how to calculate
  9011. // the timezone offset of arbitrary dates in the current timezone.
  9012. getIsAmbigTimezone: function() {
  9013. return this.opt('timezone') !== 'local' && this.opt('timezone') !== 'UTC';
  9014. },
  9015. // Returns a copy of the given date in the current timezone. Has no effect on dates without times.
  9016. applyTimezone: function(date) {
  9017. if (!date.hasTime()) {
  9018. return date.clone();
  9019. }
  9020. var zonedDate = this.moment(date.toArray());
  9021. var timeAdjust = date.time() - zonedDate.time();
  9022. var adjustedZonedDate;
  9023. // Safari sometimes has problems with this coersion when near DST. Adjust if necessary. (bug #2396)
  9024. if (timeAdjust) { // is the time result different than expected?
  9025. adjustedZonedDate = zonedDate.clone().add(timeAdjust); // add milliseconds
  9026. if (date.time() - adjustedZonedDate.time() === 0) { // does it match perfectly now?
  9027. zonedDate = adjustedZonedDate;
  9028. }
  9029. }
  9030. return zonedDate;
  9031. },
  9032. // Returns a moment for the current date, as defined by the client's computer or from the `now` option.
  9033. // Will return an moment with an ambiguous timezone.
  9034. getNow: function() {
  9035. var now = this.opt('now');
  9036. if (typeof now === 'function') {
  9037. now = now();
  9038. }
  9039. return this.moment(now).stripZone();
  9040. },
  9041. // Produces a human-readable string for the given duration.
  9042. // Side-effect: changes the locale of the given duration.
  9043. humanizeDuration: function(duration) {
  9044. return duration.locale(this.opt('locale')).humanize();
  9045. },
  9046. // Event-Specific Date Utilities. TODO: move
  9047. // -----------------------------------------------------------------------------------------------------------------
  9048. // Get an event's normalized end date. If not present, calculate it from the defaults.
  9049. getEventEnd: function(event) {
  9050. if (event.end) {
  9051. return event.end.clone();
  9052. }
  9053. else {
  9054. return this.getDefaultEventEnd(event.allDay, event.start);
  9055. }
  9056. },
  9057. // Given an event's allDay status and start date, return what its fallback end date should be.
  9058. // TODO: rename to computeDefaultEventEnd
  9059. getDefaultEventEnd: function(allDay, zonedStart) {
  9060. var end = zonedStart.clone();
  9061. if (allDay) {
  9062. end.stripTime().add(this.defaultAllDayEventDuration);
  9063. }
  9064. else {
  9065. end.add(this.defaultTimedEventDuration);
  9066. }
  9067. if (this.getIsAmbigTimezone()) {
  9068. end.stripZone(); // we don't know what the tzo should be
  9069. }
  9070. return end;
  9071. }
  9072. });
  9073. ;;
  9074. Calendar.mixin({
  9075. viewSpecCache: null, // cache of view definitions (initialized in Calendar.js)
  9076. // Gets information about how to create a view. Will use a cache.
  9077. getViewSpec: function(viewType) {
  9078. var cache = this.viewSpecCache;
  9079. return cache[viewType] || (cache[viewType] = this.buildViewSpec(viewType));
  9080. },
  9081. // Given a duration singular unit, like "week" or "day", finds a matching view spec.
  9082. // Preference is given to views that have corresponding buttons.
  9083. getUnitViewSpec: function(unit) {
  9084. var viewTypes;
  9085. var i;
  9086. var spec;
  9087. if ($.inArray(unit, unitsDesc) != -1) {
  9088. // put views that have buttons first. there will be duplicates, but oh well
  9089. viewTypes = this.header.getViewsWithButtons(); // TODO: include footer as well?
  9090. $.each(FC.views, function(viewType) { // all views
  9091. viewTypes.push(viewType);
  9092. });
  9093. for (i = 0; i < viewTypes.length; i++) {
  9094. spec = this.getViewSpec(viewTypes[i]);
  9095. if (spec) {
  9096. if (spec.singleUnit == unit) {
  9097. return spec;
  9098. }
  9099. }
  9100. }
  9101. }
  9102. },
  9103. // Builds an object with information on how to create a given view
  9104. buildViewSpec: function(requestedViewType) {
  9105. var viewOverrides = this.overrides.views || {};
  9106. var specChain = []; // for the view. lowest to highest priority
  9107. var defaultsChain = []; // for the view. lowest to highest priority
  9108. var overridesChain = []; // for the view. lowest to highest priority
  9109. var viewType = requestedViewType;
  9110. var spec; // for the view
  9111. var overrides; // for the view
  9112. var durationInput;
  9113. var duration;
  9114. var unit;
  9115. // iterate from the specific view definition to a more general one until we hit an actual View class
  9116. while (viewType) {
  9117. spec = fcViews[viewType];
  9118. overrides = viewOverrides[viewType];
  9119. viewType = null; // clear. might repopulate for another iteration
  9120. if (typeof spec === 'function') { // TODO: deprecate
  9121. spec = { 'class': spec };
  9122. }
  9123. if (spec) {
  9124. specChain.unshift(spec);
  9125. defaultsChain.unshift(spec.defaults || {});
  9126. durationInput = durationInput || spec.duration;
  9127. viewType = viewType || spec.type;
  9128. }
  9129. if (overrides) {
  9130. overridesChain.unshift(overrides); // view-specific option hashes have options at zero-level
  9131. durationInput = durationInput || overrides.duration;
  9132. viewType = viewType || overrides.type;
  9133. }
  9134. }
  9135. spec = mergeProps(specChain);
  9136. spec.type = requestedViewType;
  9137. if (!spec['class']) {
  9138. return false;
  9139. }
  9140. // fall back to top-level `duration` option
  9141. durationInput = durationInput ||
  9142. this.dynamicOverrides.duration ||
  9143. this.overrides.duration;
  9144. if (durationInput) {
  9145. duration = moment.duration(durationInput);
  9146. if (duration.valueOf()) { // valid?
  9147. unit = computeDurationGreatestUnit(duration, durationInput);
  9148. spec.duration = duration;
  9149. spec.durationUnit = unit;
  9150. // view is a single-unit duration, like "week" or "day"
  9151. // incorporate options for this. lowest priority
  9152. if (duration.as(unit) === 1) {
  9153. spec.singleUnit = unit;
  9154. overridesChain.unshift(viewOverrides[unit] || {});
  9155. }
  9156. }
  9157. }
  9158. spec.defaults = mergeOptions(defaultsChain);
  9159. spec.overrides = mergeOptions(overridesChain);
  9160. this.buildViewSpecOptions(spec);
  9161. this.buildViewSpecButtonText(spec, requestedViewType);
  9162. return spec;
  9163. },
  9164. // Builds and assigns a view spec's options object from its already-assigned defaults and overrides
  9165. buildViewSpecOptions: function(spec) {
  9166. spec.options = mergeOptions([ // lowest to highest priority
  9167. Calendar.defaults, // global defaults
  9168. spec.defaults, // view's defaults (from ViewSubclass.defaults)
  9169. this.dirDefaults,
  9170. this.localeDefaults, // locale and dir take precedence over view's defaults!
  9171. this.overrides, // calendar's overrides (options given to constructor)
  9172. spec.overrides, // view's overrides (view-specific options)
  9173. this.dynamicOverrides // dynamically set via setter. highest precedence
  9174. ]);
  9175. populateInstanceComputableOptions(spec.options);
  9176. },
  9177. // Computes and assigns a view spec's buttonText-related options
  9178. buildViewSpecButtonText: function(spec, requestedViewType) {
  9179. // given an options object with a possible `buttonText` hash, lookup the buttonText for the
  9180. // requested view, falling back to a generic unit entry like "week" or "day"
  9181. function queryButtonText(options) {
  9182. var buttonText = options.buttonText || {};
  9183. return buttonText[requestedViewType] ||
  9184. // view can decide to look up a certain key
  9185. (spec.buttonTextKey ? buttonText[spec.buttonTextKey] : null) ||
  9186. // a key like "month"
  9187. (spec.singleUnit ? buttonText[spec.singleUnit] : null);
  9188. }
  9189. // highest to lowest priority
  9190. spec.buttonTextOverride =
  9191. queryButtonText(this.dynamicOverrides) ||
  9192. queryButtonText(this.overrides) || // constructor-specified buttonText lookup hash takes precedence
  9193. spec.overrides.buttonText; // `buttonText` for view-specific options is a string
  9194. // highest to lowest priority. mirrors buildViewSpecOptions
  9195. spec.buttonTextDefault =
  9196. queryButtonText(this.localeDefaults) ||
  9197. queryButtonText(this.dirDefaults) ||
  9198. spec.defaults.buttonText || // a single string. from ViewSubclass.defaults
  9199. queryButtonText(Calendar.defaults) ||
  9200. (spec.duration ? this.humanizeDuration(spec.duration) : null) || // like "3 days"
  9201. requestedViewType; // fall back to given view name
  9202. }
  9203. });
  9204. ;;
  9205. Calendar.mixin({
  9206. el: null,
  9207. contentEl: null,
  9208. suggestedViewHeight: null,
  9209. windowResizeProxy: null,
  9210. ignoreWindowResize: 0,
  9211. render: function() {
  9212. if (!this.contentEl) {
  9213. this.initialRender();
  9214. }
  9215. else if (this.elementVisible()) {
  9216. // mainly for the public API
  9217. this.calcSize();
  9218. this.renderView();
  9219. }
  9220. },
  9221. initialRender: function() {
  9222. var _this = this;
  9223. var el = this.el;
  9224. el.addClass('fc');
  9225. // event delegation for nav links
  9226. el.on('click.fc', 'a[data-goto]', function(ev) {
  9227. var anchorEl = $(this);
  9228. var gotoOptions = anchorEl.data('goto'); // will automatically parse JSON
  9229. var date = _this.moment(gotoOptions.date);
  9230. var viewType = gotoOptions.type;
  9231. // property like "navLinkDayClick". might be a string or a function
  9232. var customAction = _this.view.opt('navLink' + capitaliseFirstLetter(viewType) + 'Click');
  9233. if (typeof customAction === 'function') {
  9234. customAction(date, ev);
  9235. }
  9236. else {
  9237. if (typeof customAction === 'string') {
  9238. viewType = customAction;
  9239. }
  9240. _this.zoomTo(date, viewType);
  9241. }
  9242. });
  9243. // called immediately, and upon option change
  9244. this.optionsModel.watch('applyingThemeClasses', [ '?theme' ], function(opts) {
  9245. el.toggleClass('ui-widget', opts.theme);
  9246. el.toggleClass('fc-unthemed', !opts.theme);
  9247. });
  9248. // called immediately, and upon option change.
  9249. // HACK: locale often affects isRTL, so we explicitly listen to that too.
  9250. this.optionsModel.watch('applyingDirClasses', [ '?isRTL', '?locale' ], function(opts) {
  9251. el.toggleClass('fc-ltr', !opts.isRTL);
  9252. el.toggleClass('fc-rtl', opts.isRTL);
  9253. });
  9254. this.contentEl = $("<div class='fc-view-container'/>").prependTo(el);
  9255. this.initToolbars();
  9256. this.renderHeader();
  9257. this.renderFooter();
  9258. this.renderView(this.opt('defaultView'));
  9259. if (this.opt('handleWindowResize')) {
  9260. $(window).resize(
  9261. this.windowResizeProxy = debounce( // prevents rapid calls
  9262. this.windowResize.bind(this),
  9263. this.opt('windowResizeDelay')
  9264. )
  9265. );
  9266. }
  9267. },
  9268. destroy: function() {
  9269. if (this.view) {
  9270. this.view.removeElement();
  9271. // NOTE: don't null-out this.view in case API methods are called after destroy.
  9272. // It is still the "current" view, just not rendered.
  9273. }
  9274. this.toolbarsManager.proxyCall('removeElement');
  9275. this.contentEl.remove();
  9276. this.el.removeClass('fc fc-ltr fc-rtl fc-unthemed ui-widget');
  9277. this.el.off('.fc'); // unbind nav link handlers
  9278. if (this.windowResizeProxy) {
  9279. $(window).unbind('resize', this.windowResizeProxy);
  9280. this.windowResizeProxy = null;
  9281. }
  9282. GlobalEmitter.unneeded();
  9283. },
  9284. elementVisible: function() {
  9285. return this.el.is(':visible');
  9286. },
  9287. // View Rendering
  9288. // -----------------------------------------------------------------------------------
  9289. // Renders a view because of a date change, view-type change, or for the first time.
  9290. // If not given a viewType, keep the current view but render different dates.
  9291. // Accepts an optional scroll state to restore to.
  9292. renderView: function(viewType, forcedScroll) {
  9293. this.ignoreWindowResize++;
  9294. var needsClearView = this.view && viewType && this.view.type !== viewType;
  9295. // if viewType is changing, remove the old view's rendering
  9296. if (needsClearView) {
  9297. this.freezeContentHeight(); // prevent a scroll jump when view element is removed
  9298. this.clearView();
  9299. }
  9300. // if viewType changed, or the view was never created, create a fresh view
  9301. if (!this.view && viewType) {
  9302. this.view =
  9303. this.viewsByType[viewType] ||
  9304. (this.viewsByType[viewType] = this.instantiateView(viewType));
  9305. this.view.setElement(
  9306. $("<div class='fc-view fc-" + viewType + "-view' />").appendTo(this.contentEl)
  9307. );
  9308. this.toolbarsManager.proxyCall('activateButton', viewType);
  9309. }
  9310. if (this.view) {
  9311. if (forcedScroll) {
  9312. this.view.addForcedScroll(forcedScroll);
  9313. }
  9314. if (this.elementVisible()) {
  9315. this.currentDate = this.view.setDate(this.currentDate);
  9316. }
  9317. }
  9318. if (needsClearView) {
  9319. this.thawContentHeight();
  9320. }
  9321. this.ignoreWindowResize--;
  9322. },
  9323. // Unrenders the current view and reflects this change in the Header.
  9324. // Unregsiters the `view`, but does not remove from viewByType hash.
  9325. clearView: function() {
  9326. this.toolbarsManager.proxyCall('deactivateButton', this.view.type);
  9327. this.view.removeElement();
  9328. this.view = null;
  9329. },
  9330. // Destroys the view, including the view object. Then, re-instantiates it and renders it.
  9331. // Maintains the same scroll state.
  9332. // TODO: maintain any other user-manipulated state.
  9333. reinitView: function() {
  9334. this.ignoreWindowResize++;
  9335. this.freezeContentHeight();
  9336. var viewType = this.view.type;
  9337. var scrollState = this.view.queryScroll();
  9338. this.clearView();
  9339. this.calcSize();
  9340. this.renderView(viewType, scrollState);
  9341. this.thawContentHeight();
  9342. this.ignoreWindowResize--;
  9343. },
  9344. // Resizing
  9345. // -----------------------------------------------------------------------------------
  9346. getSuggestedViewHeight: function() {
  9347. if (this.suggestedViewHeight === null) {
  9348. this.calcSize();
  9349. }
  9350. return this.suggestedViewHeight;
  9351. },
  9352. isHeightAuto: function() {
  9353. return this.opt('contentHeight') === 'auto' || this.opt('height') === 'auto';
  9354. },
  9355. updateSize: function(shouldRecalc) {
  9356. if (this.elementVisible()) {
  9357. if (shouldRecalc) {
  9358. this._calcSize();
  9359. }
  9360. this.ignoreWindowResize++;
  9361. this.view.updateSize(true); // isResize=true. will poll getSuggestedViewHeight() and isHeightAuto()
  9362. this.ignoreWindowResize--;
  9363. return true; // signal success
  9364. }
  9365. },
  9366. calcSize: function() {
  9367. if (this.elementVisible()) {
  9368. this._calcSize();
  9369. }
  9370. },
  9371. _calcSize: function() { // assumes elementVisible
  9372. var contentHeightInput = this.opt('contentHeight');
  9373. var heightInput = this.opt('height');
  9374. if (typeof contentHeightInput === 'number') { // exists and not 'auto'
  9375. this.suggestedViewHeight = contentHeightInput;
  9376. }
  9377. else if (typeof contentHeightInput === 'function') { // exists and is a function
  9378. this.suggestedViewHeight = contentHeightInput();
  9379. }
  9380. else if (typeof heightInput === 'number') { // exists and not 'auto'
  9381. this.suggestedViewHeight = heightInput - this.queryToolbarsHeight();
  9382. }
  9383. else if (typeof heightInput === 'function') { // exists and is a function
  9384. this.suggestedViewHeight = heightInput() - this.queryToolbarsHeight();
  9385. }
  9386. else if (heightInput === 'parent') { // set to height of parent element
  9387. this.suggestedViewHeight = this.el.parent().height() - this.queryToolbarsHeight();
  9388. }
  9389. else {
  9390. this.suggestedViewHeight = Math.round(
  9391. this.contentEl.width() /
  9392. Math.max(this.opt('aspectRatio'), .5)
  9393. );
  9394. }
  9395. },
  9396. windowResize: function(ev) {
  9397. if (
  9398. !this.ignoreWindowResize &&
  9399. ev.target === window && // so we don't process jqui "resize" events that have bubbled up
  9400. this.view.renderRange // view has already been rendered
  9401. ) {
  9402. if (this.updateSize(true)) {
  9403. this.view.publiclyTrigger('windowResize', this.el[0]);
  9404. }
  9405. }
  9406. },
  9407. /* Height "Freezing"
  9408. -----------------------------------------------------------------------------*/
  9409. freezeContentHeight: function() {
  9410. this.contentEl.css({
  9411. width: '100%',
  9412. height: this.contentEl.height(),
  9413. overflow: 'hidden'
  9414. });
  9415. },
  9416. thawContentHeight: function() {
  9417. this.contentEl.css({
  9418. width: '',
  9419. height: '',
  9420. overflow: ''
  9421. });
  9422. }
  9423. });
  9424. ;;
  9425. Calendar.mixin({
  9426. header: null,
  9427. footer: null,
  9428. toolbarsManager: null,
  9429. initToolbars: function() {
  9430. this.header = new Toolbar(this, this.computeHeaderOptions());
  9431. this.footer = new Toolbar(this, this.computeFooterOptions());
  9432. this.toolbarsManager = new Iterator([ this.header, this.footer ]);
  9433. },
  9434. computeHeaderOptions: function() {
  9435. return {
  9436. extraClasses: 'fc-header-toolbar',
  9437. layout: this.opt('header')
  9438. };
  9439. },
  9440. computeFooterOptions: function() {
  9441. return {
  9442. extraClasses: 'fc-footer-toolbar',
  9443. layout: this.opt('footer')
  9444. };
  9445. },
  9446. // can be called repeatedly and Header will rerender
  9447. renderHeader: function() {
  9448. var header = this.header;
  9449. header.setToolbarOptions(this.computeHeaderOptions());
  9450. header.render();
  9451. if (header.el) {
  9452. this.el.prepend(header.el);
  9453. }
  9454. },
  9455. // can be called repeatedly and Footer will rerender
  9456. renderFooter: function() {
  9457. var footer = this.footer;
  9458. footer.setToolbarOptions(this.computeFooterOptions());
  9459. footer.render();
  9460. if (footer.el) {
  9461. this.el.append(footer.el);
  9462. }
  9463. },
  9464. setToolbarsTitle: function(title) {
  9465. this.toolbarsManager.proxyCall('updateTitle', title);
  9466. },
  9467. updateToolbarButtons: function() {
  9468. var now = this.getNow();
  9469. var view = this.view;
  9470. var todayInfo = view.buildDateProfile(now);
  9471. var prevInfo = view.buildPrevDateProfile(this.currentDate);
  9472. var nextInfo = view.buildNextDateProfile(this.currentDate);
  9473. this.toolbarsManager.proxyCall(
  9474. (todayInfo.isValid && !isDateWithinRange(now, view.currentRange)) ?
  9475. 'enableButton' :
  9476. 'disableButton',
  9477. 'today'
  9478. );
  9479. this.toolbarsManager.proxyCall(
  9480. prevInfo.isValid ?
  9481. 'enableButton' :
  9482. 'disableButton',
  9483. 'prev'
  9484. );
  9485. this.toolbarsManager.proxyCall(
  9486. nextInfo.isValid ?
  9487. 'enableButton' :
  9488. 'disableButton',
  9489. 'next'
  9490. );
  9491. },
  9492. queryToolbarsHeight: function() {
  9493. return this.toolbarsManager.items.reduce(function(accumulator, toolbar) {
  9494. var toolbarHeight = toolbar.el ? toolbar.el.outerHeight(true) : 0; // includes margin
  9495. return accumulator + toolbarHeight;
  9496. }, 0);
  9497. }
  9498. });
  9499. ;;
  9500. Calendar.defaults = {
  9501. titleRangeSeparator: ' \u2013 ', // en dash
  9502. monthYearFormat: 'MMMM YYYY', // required for en. other locales rely on datepicker computable option
  9503. defaultTimedEventDuration: '02:00:00',
  9504. defaultAllDayEventDuration: { days: 1 },
  9505. forceEventDuration: false,
  9506. nextDayThreshold: '09:00:00', // 9am
  9507. // display
  9508. defaultView: 'month',
  9509. aspectRatio: 1.35,
  9510. header: {
  9511. left: 'title',
  9512. center: '',
  9513. right: 'today prev,next'
  9514. },
  9515. weekends: true,
  9516. weekNumbers: false,
  9517. weekNumberTitle: 'W',
  9518. weekNumberCalculation: 'local',
  9519. //editable: false,
  9520. //nowIndicator: false,
  9521. scrollTime: '06:00:00',
  9522. minTime: '00:00:00',
  9523. maxTime: '24:00:00',
  9524. showNonCurrentDates: true,
  9525. // event ajax
  9526. lazyFetching: true,
  9527. startParam: 'start',
  9528. endParam: 'end',
  9529. timezoneParam: 'timezone',
  9530. timezone: false,
  9531. //allDayDefault: undefined,
  9532. // locale
  9533. isRTL: false,
  9534. buttonText: {
  9535. prev: "prev",
  9536. next: "next",
  9537. prevYear: "prev year",
  9538. nextYear: "next year",
  9539. year: 'year', // TODO: locale files need to specify this
  9540. today: 'today',
  9541. month: 'month',
  9542. week: 'week',
  9543. day: 'day'
  9544. },
  9545. buttonIcons: {
  9546. prev: 'left-single-arrow',
  9547. next: 'right-single-arrow',
  9548. prevYear: 'left-double-arrow',
  9549. nextYear: 'right-double-arrow'
  9550. },
  9551. allDayText: 'all-day',
  9552. // jquery-ui theming
  9553. theme: false,
  9554. themeButtonIcons: {
  9555. prev: 'circle-triangle-w',
  9556. next: 'circle-triangle-e',
  9557. prevYear: 'seek-prev',
  9558. nextYear: 'seek-next'
  9559. },
  9560. //eventResizableFromStart: false,
  9561. dragOpacity: .75,
  9562. dragRevertDuration: 500,
  9563. dragScroll: true,
  9564. //selectable: false,
  9565. unselectAuto: true,
  9566. //selectMinDistance: 0,
  9567. dropAccept: '*',
  9568. eventOrder: 'title',
  9569. //eventRenderWait: null,
  9570. eventLimit: false,
  9571. eventLimitText: 'more',
  9572. eventLimitClick: 'popover',
  9573. dayPopoverFormat: 'LL',
  9574. handleWindowResize: true,
  9575. windowResizeDelay: 100, // milliseconds before an updateSize happens
  9576. longPressDelay: 1000
  9577. };
  9578. Calendar.englishDefaults = { // used by locale.js
  9579. dayPopoverFormat: 'dddd, MMMM D'
  9580. };
  9581. Calendar.rtlDefaults = { // right-to-left defaults
  9582. header: { // TODO: smarter solution (first/center/last ?)
  9583. left: 'next,prev today',
  9584. center: '',
  9585. right: 'title'
  9586. },
  9587. buttonIcons: {
  9588. prev: 'right-single-arrow',
  9589. next: 'left-single-arrow',
  9590. prevYear: 'right-double-arrow',
  9591. nextYear: 'left-double-arrow'
  9592. },
  9593. themeButtonIcons: {
  9594. prev: 'circle-triangle-e',
  9595. next: 'circle-triangle-w',
  9596. nextYear: 'seek-prev',
  9597. prevYear: 'seek-next'
  9598. }
  9599. };
  9600. ;;
  9601. var localeOptionHash = FC.locales = {}; // initialize and expose
  9602. // TODO: document the structure and ordering of a FullCalendar locale file
  9603. // Initialize jQuery UI datepicker translations while using some of the translations
  9604. // Will set this as the default locales for datepicker.
  9605. FC.datepickerLocale = function(localeCode, dpLocaleCode, dpOptions) {
  9606. // get the FullCalendar internal option hash for this locale. create if necessary
  9607. var fcOptions = localeOptionHash[localeCode] || (localeOptionHash[localeCode] = {});
  9608. // transfer some simple options from datepicker to fc
  9609. fcOptions.isRTL = dpOptions.isRTL;
  9610. fcOptions.weekNumberTitle = dpOptions.weekHeader;
  9611. // compute some more complex options from datepicker
  9612. $.each(dpComputableOptions, function(name, func) {
  9613. fcOptions[name] = func(dpOptions);
  9614. });
  9615. // is jQuery UI Datepicker is on the page?
  9616. if ($.datepicker) {
  9617. // Register the locale data.
  9618. // FullCalendar and MomentJS use locale codes like "pt-br" but Datepicker
  9619. // does it like "pt-BR" or if it doesn't have the locale, maybe just "pt".
  9620. // Make an alias so the locale can be referenced either way.
  9621. $.datepicker.regional[dpLocaleCode] =
  9622. $.datepicker.regional[localeCode] = // alias
  9623. dpOptions;
  9624. // Alias 'en' to the default locale data. Do this every time.
  9625. $.datepicker.regional.en = $.datepicker.regional[''];
  9626. // Set as Datepicker's global defaults.
  9627. $.datepicker.setDefaults(dpOptions);
  9628. }
  9629. };
  9630. // Sets FullCalendar-specific translations. Will set the locales as the global default.
  9631. FC.locale = function(localeCode, newFcOptions) {
  9632. var fcOptions;
  9633. var momOptions;
  9634. // get the FullCalendar internal option hash for this locale. create if necessary
  9635. fcOptions = localeOptionHash[localeCode] || (localeOptionHash[localeCode] = {});
  9636. // provided new options for this locales? merge them in
  9637. if (newFcOptions) {
  9638. fcOptions = localeOptionHash[localeCode] = mergeOptions([ fcOptions, newFcOptions ]);
  9639. }
  9640. // compute locale options that weren't defined.
  9641. // always do this. newFcOptions can be undefined when initializing from i18n file,
  9642. // so no way to tell if this is an initialization or a default-setting.
  9643. momOptions = getMomentLocaleData(localeCode); // will fall back to en
  9644. $.each(momComputableOptions, function(name, func) {
  9645. if (fcOptions[name] == null) {
  9646. fcOptions[name] = func(momOptions, fcOptions);
  9647. }
  9648. });
  9649. // set it as the default locale for FullCalendar
  9650. Calendar.defaults.locale = localeCode;
  9651. };
  9652. // NOTE: can't guarantee any of these computations will run because not every locale has datepicker
  9653. // configs, so make sure there are English fallbacks for these in the defaults file.
  9654. var dpComputableOptions = {
  9655. buttonText: function(dpOptions) {
  9656. return {
  9657. // the translations sometimes wrongly contain HTML entities
  9658. prev: stripHtmlEntities(dpOptions.prevText),
  9659. next: stripHtmlEntities(dpOptions.nextText),
  9660. today: stripHtmlEntities(dpOptions.currentText)
  9661. };
  9662. },
  9663. // Produces format strings like "MMMM YYYY" -> "September 2014"
  9664. monthYearFormat: function(dpOptions) {
  9665. return dpOptions.showMonthAfterYear ?
  9666. 'YYYY[' + dpOptions.yearSuffix + '] MMMM' :
  9667. 'MMMM YYYY[' + dpOptions.yearSuffix + ']';
  9668. }
  9669. };
  9670. var momComputableOptions = {
  9671. // Produces format strings like "ddd M/D" -> "Fri 9/15"
  9672. dayOfMonthFormat: function(momOptions, fcOptions) {
  9673. var format = momOptions.longDateFormat('l'); // for the format like "M/D/YYYY"
  9674. // strip the year off the edge, as well as other misc non-whitespace chars
  9675. format = format.replace(/^Y+[^\w\s]*|[^\w\s]*Y+$/g, '');
  9676. if (fcOptions.isRTL) {
  9677. format += ' ddd'; // for RTL, add day-of-week to end
  9678. }
  9679. else {
  9680. format = 'ddd ' + format; // for LTR, add day-of-week to beginning
  9681. }
  9682. return format;
  9683. },
  9684. // Produces format strings like "h:mma" -> "6:00pm"
  9685. mediumTimeFormat: function(momOptions) { // can't be called `timeFormat` because collides with option
  9686. return momOptions.longDateFormat('LT')
  9687. .replace(/\s*a$/i, 'a'); // convert AM/PM/am/pm to lowercase. remove any spaces beforehand
  9688. },
  9689. // Produces format strings like "h(:mm)a" -> "6pm" / "6:30pm"
  9690. smallTimeFormat: function(momOptions) {
  9691. return momOptions.longDateFormat('LT')
  9692. .replace(':mm', '(:mm)')
  9693. .replace(/(\Wmm)$/, '($1)') // like above, but for foreign locales
  9694. .replace(/\s*a$/i, 'a'); // convert AM/PM/am/pm to lowercase. remove any spaces beforehand
  9695. },
  9696. // Produces format strings like "h(:mm)t" -> "6p" / "6:30p"
  9697. extraSmallTimeFormat: function(momOptions) {
  9698. return momOptions.longDateFormat('LT')
  9699. .replace(':mm', '(:mm)')
  9700. .replace(/(\Wmm)$/, '($1)') // like above, but for foreign locales
  9701. .replace(/\s*a$/i, 't'); // convert to AM/PM/am/pm to lowercase one-letter. remove any spaces beforehand
  9702. },
  9703. // Produces format strings like "ha" / "H" -> "6pm" / "18"
  9704. hourFormat: function(momOptions) {
  9705. return momOptions.longDateFormat('LT')
  9706. .replace(':mm', '')
  9707. .replace(/(\Wmm)$/, '') // like above, but for foreign locales
  9708. .replace(/\s*a$/i, 'a'); // convert AM/PM/am/pm to lowercase. remove any spaces beforehand
  9709. },
  9710. // Produces format strings like "h:mm" -> "6:30" (with no AM/PM)
  9711. noMeridiemTimeFormat: function(momOptions) {
  9712. return momOptions.longDateFormat('LT')
  9713. .replace(/\s*a$/i, ''); // remove trailing AM/PM
  9714. }
  9715. };
  9716. // options that should be computed off live calendar options (considers override options)
  9717. // TODO: best place for this? related to locale?
  9718. // TODO: flipping text based on isRTL is a bad idea because the CSS `direction` might want to handle it
  9719. var instanceComputableOptions = {
  9720. // Produces format strings for results like "Mo 16"
  9721. smallDayDateFormat: function(options) {
  9722. return options.isRTL ?
  9723. 'D dd' :
  9724. 'dd D';
  9725. },
  9726. // Produces format strings for results like "Wk 5"
  9727. weekFormat: function(options) {
  9728. return options.isRTL ?
  9729. 'w[ ' + options.weekNumberTitle + ']' :
  9730. '[' + options.weekNumberTitle + ' ]w';
  9731. },
  9732. // Produces format strings for results like "Wk5"
  9733. smallWeekFormat: function(options) {
  9734. return options.isRTL ?
  9735. 'w[' + options.weekNumberTitle + ']' :
  9736. '[' + options.weekNumberTitle + ']w';
  9737. }
  9738. };
  9739. // TODO: make these computable properties in optionsModel
  9740. function populateInstanceComputableOptions(options) {
  9741. $.each(instanceComputableOptions, function(name, func) {
  9742. if (options[name] == null) {
  9743. options[name] = func(options);
  9744. }
  9745. });
  9746. }
  9747. // Returns moment's internal locale data. If doesn't exist, returns English.
  9748. function getMomentLocaleData(localeCode) {
  9749. return moment.localeData(localeCode) || moment.localeData('en');
  9750. }
  9751. // Initialize English by forcing computation of moment-derived options.
  9752. // Also, sets it as the default.
  9753. FC.locale('en', Calendar.englishDefaults);
  9754. ;;
  9755. FC.sourceNormalizers = [];
  9756. FC.sourceFetchers = [];
  9757. var ajaxDefaults = {
  9758. dataType: 'json',
  9759. cache: false
  9760. };
  9761. var eventGUID = 1;
  9762. function EventManager() { // assumed to be a calendar
  9763. var t = this;
  9764. // exports
  9765. t.requestEvents = requestEvents;
  9766. t.reportEventChange = reportEventChange;
  9767. t.isFetchNeeded = isFetchNeeded;
  9768. t.fetchEvents = fetchEvents;
  9769. t.fetchEventSources = fetchEventSources;
  9770. t.refetchEvents = refetchEvents;
  9771. t.refetchEventSources = refetchEventSources;
  9772. t.getEventSources = getEventSources;
  9773. t.getEventSourceById = getEventSourceById;
  9774. t.addEventSource = addEventSource;
  9775. t.removeEventSource = removeEventSource;
  9776. t.removeEventSources = removeEventSources;
  9777. t.updateEvent = updateEvent;
  9778. t.updateEvents = updateEvents;
  9779. t.renderEvent = renderEvent;
  9780. t.renderEvents = renderEvents;
  9781. t.removeEvents = removeEvents;
  9782. t.clientEvents = clientEvents;
  9783. t.mutateEvent = mutateEvent;
  9784. t.normalizeEventDates = normalizeEventDates;
  9785. t.normalizeEventTimes = normalizeEventTimes;
  9786. // locals
  9787. var stickySource = { events: [] };
  9788. var sources = [ stickySource ];
  9789. var rangeStart, rangeEnd;
  9790. var pendingSourceCnt = 0; // outstanding fetch requests, max one per source
  9791. var cache = []; // holds events that have already been expanded
  9792. var prunedCache; // like cache, but only events that intersect with rangeStart/rangeEnd
  9793. $.each(
  9794. (t.opt('events') ? [ t.opt('events') ] : []).concat(t.opt('eventSources') || []),
  9795. function(i, sourceInput) {
  9796. var source = buildEventSource(sourceInput);
  9797. if (source) {
  9798. sources.push(source);
  9799. }
  9800. }
  9801. );
  9802. function requestEvents(start, end) {
  9803. if (!t.opt('lazyFetching') || isFetchNeeded(start, end)) {
  9804. return fetchEvents(start, end);
  9805. }
  9806. else {
  9807. return Promise.resolve(prunedCache);
  9808. }
  9809. }
  9810. function reportEventChange() {
  9811. prunedCache = filterEventsWithinRange(cache);
  9812. t.trigger('eventsReset', prunedCache);
  9813. }
  9814. function filterEventsWithinRange(events) {
  9815. var filteredEvents = [];
  9816. var i, event;
  9817. for (i = 0; i < events.length; i++) {
  9818. event = events[i];
  9819. if (
  9820. event.start.clone().stripZone() < rangeEnd &&
  9821. t.getEventEnd(event).stripZone() > rangeStart
  9822. ) {
  9823. filteredEvents.push(event);
  9824. }
  9825. }
  9826. return filteredEvents;
  9827. }
  9828. t.getEventCache = function() {
  9829. return cache;
  9830. };
  9831. /* Fetching
  9832. -----------------------------------------------------------------------------*/
  9833. // start and end are assumed to be unzoned
  9834. function isFetchNeeded(start, end) {
  9835. return !rangeStart || // nothing has been fetched yet?
  9836. start < rangeStart || end > rangeEnd; // is part of the new range outside of the old range?
  9837. }
  9838. function fetchEvents(start, end) {
  9839. rangeStart = start;
  9840. rangeEnd = end;
  9841. return refetchEvents();
  9842. }
  9843. // poorly named. fetches all sources with current `rangeStart` and `rangeEnd`.
  9844. function refetchEvents() {
  9845. return fetchEventSources(sources, 'reset');
  9846. }
  9847. // poorly named. fetches a subset of event sources.
  9848. function refetchEventSources(matchInputs) {
  9849. return fetchEventSources(getEventSourcesByMatchArray(matchInputs));
  9850. }
  9851. // expects an array of event source objects (the originals, not copies)
  9852. // `specialFetchType` is an optimization parameter that affects purging of the event cache.
  9853. function fetchEventSources(specificSources, specialFetchType) {
  9854. var i, source;
  9855. if (specialFetchType === 'reset') {
  9856. cache = [];
  9857. }
  9858. else if (specialFetchType !== 'add') {
  9859. cache = excludeEventsBySources(cache, specificSources);
  9860. }
  9861. for (i = 0; i < specificSources.length; i++) {
  9862. source = specificSources[i];
  9863. // already-pending sources have already been accounted for in pendingSourceCnt
  9864. if (source._status !== 'pending') {
  9865. pendingSourceCnt++;
  9866. }
  9867. source._fetchId = (source._fetchId || 0) + 1;
  9868. source._status = 'pending';
  9869. }
  9870. for (i = 0; i < specificSources.length; i++) {
  9871. source = specificSources[i];
  9872. tryFetchEventSource(source, source._fetchId);
  9873. }
  9874. if (pendingSourceCnt) {
  9875. return Promise.construct(function(resolve) {
  9876. t.one('eventsReceived', resolve); // will send prunedCache
  9877. });
  9878. }
  9879. else { // executed all synchronously, or no sources at all
  9880. return Promise.resolve(prunedCache);
  9881. }
  9882. }
  9883. // fetches an event source and processes its result ONLY if it is still the current fetch.
  9884. // caller is responsible for incrementing pendingSourceCnt first.
  9885. function tryFetchEventSource(source, fetchId) {
  9886. _fetchEventSource(source, function(eventInputs) {
  9887. var isArraySource = $.isArray(source.events);
  9888. var i, eventInput;
  9889. var abstractEvent;
  9890. if (
  9891. // is this the source's most recent fetch?
  9892. // if not, rely on an upcoming fetch of this source to decrement pendingSourceCnt
  9893. fetchId === source._fetchId &&
  9894. // event source no longer valid?
  9895. source._status !== 'rejected'
  9896. ) {
  9897. source._status = 'resolved';
  9898. if (eventInputs) {
  9899. for (i = 0; i < eventInputs.length; i++) {
  9900. eventInput = eventInputs[i];
  9901. if (isArraySource) { // array sources have already been convert to Event Objects
  9902. abstractEvent = eventInput;
  9903. }
  9904. else {
  9905. abstractEvent = buildEventFromInput(eventInput, source);
  9906. }
  9907. if (abstractEvent) { // not false (an invalid event)
  9908. cache.push.apply( // append
  9909. cache,
  9910. expandEvent(abstractEvent) // add individual expanded events to the cache
  9911. );
  9912. }
  9913. }
  9914. }
  9915. decrementPendingSourceCnt();
  9916. }
  9917. });
  9918. }
  9919. function rejectEventSource(source) {
  9920. var wasPending = source._status === 'pending';
  9921. source._status = 'rejected';
  9922. if (wasPending) {
  9923. decrementPendingSourceCnt();
  9924. }
  9925. }
  9926. function decrementPendingSourceCnt() {
  9927. pendingSourceCnt--;
  9928. if (!pendingSourceCnt) {
  9929. reportEventChange(cache); // updates prunedCache
  9930. t.trigger('eventsReceived', prunedCache);
  9931. }
  9932. }
  9933. function _fetchEventSource(source, callback) {
  9934. var i;
  9935. var fetchers = FC.sourceFetchers;
  9936. var res;
  9937. for (i=0; i<fetchers.length; i++) {
  9938. res = fetchers[i].call(
  9939. t, // this, the Calendar object
  9940. source,
  9941. rangeStart.clone(),
  9942. rangeEnd.clone(),
  9943. t.opt('timezone'),
  9944. callback
  9945. );
  9946. if (res === true) {
  9947. // the fetcher is in charge. made its own async request
  9948. return;
  9949. }
  9950. else if (typeof res == 'object') {
  9951. // the fetcher returned a new source. process it
  9952. _fetchEventSource(res, callback);
  9953. return;
  9954. }
  9955. }
  9956. var events = source.events;
  9957. if (events) {
  9958. if ($.isFunction(events)) {
  9959. t.pushLoading();
  9960. events.call(
  9961. t, // this, the Calendar object
  9962. rangeStart.clone(),
  9963. rangeEnd.clone(),
  9964. t.opt('timezone'),
  9965. function(events) {
  9966. callback(events);
  9967. t.popLoading();
  9968. }
  9969. );
  9970. }
  9971. else if ($.isArray(events)) {
  9972. callback(events);
  9973. }
  9974. else {
  9975. callback();
  9976. }
  9977. }else{
  9978. var url = source.url;
  9979. if (url) {
  9980. var success = source.success;
  9981. var error = source.error;
  9982. var complete = source.complete;
  9983. // retrieve any outbound GET/POST $.ajax data from the options
  9984. var customData;
  9985. if ($.isFunction(source.data)) {
  9986. // supplied as a function that returns a key/value object
  9987. customData = source.data();
  9988. }
  9989. else {
  9990. // supplied as a straight key/value object
  9991. customData = source.data;
  9992. }
  9993. // use a copy of the custom data so we can modify the parameters
  9994. // and not affect the passed-in object.
  9995. var data = $.extend({}, customData || {});
  9996. var startParam = firstDefined(source.startParam, t.opt('startParam'));
  9997. var endParam = firstDefined(source.endParam, t.opt('endParam'));
  9998. var timezoneParam = firstDefined(source.timezoneParam, t.opt('timezoneParam'));
  9999. if (startParam) {
  10000. data[startParam] = rangeStart.format();
  10001. }
  10002. if (endParam) {
  10003. data[endParam] = rangeEnd.format();
  10004. }
  10005. if (t.opt('timezone') && t.opt('timezone') != 'local') {
  10006. data[timezoneParam] = t.opt('timezone');
  10007. }
  10008. t.pushLoading();
  10009. $.ajax($.extend({}, ajaxDefaults, source, {
  10010. data: data,
  10011. success: function(events) {
  10012. events = events || [];
  10013. var res = applyAll(success, this, arguments);
  10014. if ($.isArray(res)) {
  10015. events = res;
  10016. }
  10017. callback(events);
  10018. },
  10019. error: function() {
  10020. applyAll(error, this, arguments);
  10021. callback();
  10022. },
  10023. complete: function() {
  10024. applyAll(complete, this, arguments);
  10025. t.popLoading();
  10026. }
  10027. }));
  10028. }else{
  10029. callback();
  10030. }
  10031. }
  10032. }
  10033. /* Sources
  10034. -----------------------------------------------------------------------------*/
  10035. function addEventSource(sourceInput) {
  10036. var source = buildEventSource(sourceInput);
  10037. if (source) {
  10038. sources.push(source);
  10039. fetchEventSources([ source ], 'add'); // will eventually call reportEventChange
  10040. }
  10041. }
  10042. function buildEventSource(sourceInput) { // will return undefined if invalid source
  10043. var normalizers = FC.sourceNormalizers;
  10044. var source;
  10045. var i;
  10046. if ($.isFunction(sourceInput) || $.isArray(sourceInput)) {
  10047. source = { events: sourceInput };
  10048. }
  10049. else if (typeof sourceInput === 'string') {
  10050. source = { url: sourceInput };
  10051. }
  10052. else if (typeof sourceInput === 'object') {
  10053. source = $.extend({}, sourceInput); // shallow copy
  10054. }
  10055. if (source) {
  10056. // TODO: repeat code, same code for event classNames
  10057. if (source.className) {
  10058. if (typeof source.className === 'string') {
  10059. source.className = source.className.split(/\s+/);
  10060. }
  10061. // otherwise, assumed to be an array
  10062. }
  10063. else {
  10064. source.className = [];
  10065. }
  10066. // for array sources, we convert to standard Event Objects up front
  10067. if ($.isArray(source.events)) {
  10068. source.origArray = source.events; // for removeEventSource
  10069. source.events = $.map(source.events, function(eventInput) {
  10070. return buildEventFromInput(eventInput, source);
  10071. });
  10072. }
  10073. for (i=0; i<normalizers.length; i++) {
  10074. normalizers[i].call(t, source);
  10075. }
  10076. return source;
  10077. }
  10078. }
  10079. function removeEventSource(matchInput) {
  10080. removeSpecificEventSources(
  10081. getEventSourcesByMatch(matchInput)
  10082. );
  10083. }
  10084. // if called with no arguments, removes all.
  10085. function removeEventSources(matchInputs) {
  10086. if (matchInputs == null) {
  10087. removeSpecificEventSources(sources, true); // isAll=true
  10088. }
  10089. else {
  10090. removeSpecificEventSources(
  10091. getEventSourcesByMatchArray(matchInputs)
  10092. );
  10093. }
  10094. }
  10095. function removeSpecificEventSources(targetSources, isAll) {
  10096. var i;
  10097. // cancel pending requests
  10098. for (i = 0; i < targetSources.length; i++) {
  10099. rejectEventSource(targetSources[i]);
  10100. }
  10101. if (isAll) { // an optimization
  10102. sources = [];
  10103. cache = [];
  10104. }
  10105. else {
  10106. // remove from persisted source list
  10107. sources = $.grep(sources, function(source) {
  10108. for (i = 0; i < targetSources.length; i++) {
  10109. if (source === targetSources[i]) {
  10110. return false; // exclude
  10111. }
  10112. }
  10113. return true; // include
  10114. });
  10115. cache = excludeEventsBySources(cache, targetSources);
  10116. }
  10117. reportEventChange();
  10118. }
  10119. function getEventSources() {
  10120. return sources.slice(1); // returns a shallow copy of sources with stickySource removed
  10121. }
  10122. function getEventSourceById(id) {
  10123. return $.grep(sources, function(source) {
  10124. return source.id && source.id === id;
  10125. })[0];
  10126. }
  10127. // like getEventSourcesByMatch, but accepts multple match criteria (like multiple IDs)
  10128. function getEventSourcesByMatchArray(matchInputs) {
  10129. // coerce into an array
  10130. if (!matchInputs) {
  10131. matchInputs = [];
  10132. }
  10133. else if (!$.isArray(matchInputs)) {
  10134. matchInputs = [ matchInputs ];
  10135. }
  10136. var matchingSources = [];
  10137. var i;
  10138. // resolve raw inputs to real event source objects
  10139. for (i = 0; i < matchInputs.length; i++) {
  10140. matchingSources.push.apply( // append
  10141. matchingSources,
  10142. getEventSourcesByMatch(matchInputs[i])
  10143. );
  10144. }
  10145. return matchingSources;
  10146. }
  10147. // matchInput can either by a real event source object, an ID, or the function/URL for the source.
  10148. // returns an array of matching source objects.
  10149. function getEventSourcesByMatch(matchInput) {
  10150. var i, source;
  10151. // given an proper event source object
  10152. for (i = 0; i < sources.length; i++) {
  10153. source = sources[i];
  10154. if (source === matchInput) {
  10155. return [ source ];
  10156. }
  10157. }
  10158. // an ID match
  10159. source = getEventSourceById(matchInput);
  10160. if (source) {
  10161. return [ source ];
  10162. }
  10163. return $.grep(sources, function(source) {
  10164. return isSourcesEquivalent(matchInput, source);
  10165. });
  10166. }
  10167. function isSourcesEquivalent(source1, source2) {
  10168. return source1 && source2 && getSourcePrimitive(source1) == getSourcePrimitive(source2);
  10169. }
  10170. function getSourcePrimitive(source) {
  10171. return (
  10172. (typeof source === 'object') ? // a normalized event source?
  10173. (source.origArray || source.googleCalendarId || source.url || source.events) : // get the primitive
  10174. null
  10175. ) ||
  10176. source; // the given argument *is* the primitive
  10177. }
  10178. // util
  10179. // returns a filtered array without events that are part of any of the given sources
  10180. function excludeEventsBySources(specificEvents, specificSources) {
  10181. return $.grep(specificEvents, function(event) {
  10182. for (var i = 0; i < specificSources.length; i++) {
  10183. if (event.source === specificSources[i]) {
  10184. return false; // exclude
  10185. }
  10186. }
  10187. return true; // keep
  10188. });
  10189. }
  10190. /* Manipulation
  10191. -----------------------------------------------------------------------------*/
  10192. // Only ever called from the externally-facing API
  10193. function updateEvent(event) {
  10194. updateEvents([ event ]);
  10195. }
  10196. // Only ever called from the externally-facing API
  10197. function updateEvents(events) {
  10198. var i, event;
  10199. for (i = 0; i < events.length; i++) {
  10200. event = events[i];
  10201. // massage start/end values, even if date string values
  10202. event.start = t.moment(event.start);
  10203. if (event.end) {
  10204. event.end = t.moment(event.end);
  10205. }
  10206. else {
  10207. event.end = null;
  10208. }
  10209. mutateEvent(event, getMiscEventProps(event)); // will handle start/end/allDay normalization
  10210. }
  10211. reportEventChange(); // reports event modifications (so we can redraw)
  10212. }
  10213. // Returns a hash of misc event properties that should be copied over to related events.
  10214. function getMiscEventProps(event) {
  10215. var props = {};
  10216. $.each(event, function(name, val) {
  10217. if (isMiscEventPropName(name)) {
  10218. if (val !== undefined && isAtomic(val)) { // a defined non-object
  10219. props[name] = val;
  10220. }
  10221. }
  10222. });
  10223. return props;
  10224. }
  10225. // non-date-related, non-id-related, non-secret
  10226. function isMiscEventPropName(name) {
  10227. return !/^_|^(id|allDay|start|end)$/.test(name);
  10228. }
  10229. // returns the expanded events that were created
  10230. function renderEvent(eventInput, stick) {
  10231. return renderEvents([ eventInput ], stick);
  10232. }
  10233. // returns the expanded events that were created
  10234. function renderEvents(eventInputs, stick) {
  10235. var renderedEvents = [];
  10236. var renderableEvents;
  10237. var abstractEvent;
  10238. var i, j, event;
  10239. for (i = 0; i < eventInputs.length; i++) {
  10240. abstractEvent = buildEventFromInput(eventInputs[i]);
  10241. if (abstractEvent) { // not false (a valid input)
  10242. renderableEvents = expandEvent(abstractEvent);
  10243. for (j = 0; j < renderableEvents.length; j++) {
  10244. event = renderableEvents[j];
  10245. if (!event.source) {
  10246. if (stick) {
  10247. stickySource.events.push(event);
  10248. event.source = stickySource;
  10249. }
  10250. cache.push(event);
  10251. }
  10252. }
  10253. renderedEvents = renderedEvents.concat(renderableEvents);
  10254. }
  10255. }
  10256. if (renderedEvents.length) { // any new events rendered?
  10257. reportEventChange();
  10258. }
  10259. return renderedEvents;
  10260. }
  10261. function removeEvents(filter) {
  10262. var eventID;
  10263. var i;
  10264. if (filter == null) { // null or undefined. remove all events
  10265. filter = function() { return true; }; // will always match
  10266. }
  10267. else if (!$.isFunction(filter)) { // an event ID
  10268. eventID = filter + '';
  10269. filter = function(event) {
  10270. return event._id == eventID;
  10271. };
  10272. }
  10273. // Purge event(s) from our local cache
  10274. cache = $.grep(cache, filter, true); // inverse=true
  10275. // Remove events from array sources.
  10276. // This works because they have been converted to official Event Objects up front.
  10277. // (and as a result, event._id has been calculated).
  10278. for (i=0; i<sources.length; i++) {
  10279. if ($.isArray(sources[i].events)) {
  10280. sources[i].events = $.grep(sources[i].events, filter, true);
  10281. }
  10282. }
  10283. reportEventChange();
  10284. }
  10285. function clientEvents(filter) {
  10286. if ($.isFunction(filter)) {
  10287. return $.grep(cache, filter);
  10288. }
  10289. else if (filter != null) { // not null, not undefined. an event ID
  10290. filter += '';
  10291. return $.grep(cache, function(e) {
  10292. return e._id == filter;
  10293. });
  10294. }
  10295. return cache; // else, return all
  10296. }
  10297. // Makes sure all array event sources have their internal event objects
  10298. // converted over to the Calendar's current timezone.
  10299. t.rezoneArrayEventSources = function() {
  10300. var i;
  10301. var events;
  10302. var j;
  10303. for (i = 0; i < sources.length; i++) {
  10304. events = sources[i].events;
  10305. if ($.isArray(events)) {
  10306. for (j = 0; j < events.length; j++) {
  10307. rezoneEventDates(events[j]);
  10308. }
  10309. }
  10310. }
  10311. };
  10312. function rezoneEventDates(event) {
  10313. event.start = t.moment(event.start);
  10314. if (event.end) {
  10315. event.end = t.moment(event.end);
  10316. }
  10317. backupEventDates(event);
  10318. }
  10319. /* Event Normalization
  10320. -----------------------------------------------------------------------------*/
  10321. // Given a raw object with key/value properties, returns an "abstract" Event object.
  10322. // An "abstract" event is an event that, if recurring, will not have been expanded yet.
  10323. // Will return `false` when input is invalid.
  10324. // `source` is optional
  10325. function buildEventFromInput(input, source) {
  10326. var calendarEventDataTransform = t.opt('eventDataTransform');
  10327. var out = {};
  10328. var start, end;
  10329. var allDay;
  10330. if (calendarEventDataTransform) {
  10331. input = calendarEventDataTransform(input);
  10332. }
  10333. if (source && source.eventDataTransform) {
  10334. input = source.eventDataTransform(input);
  10335. }
  10336. // Copy all properties over to the resulting object.
  10337. // The special-case properties will be copied over afterwards.
  10338. $.extend(out, input);
  10339. if (source) {
  10340. out.source = source;
  10341. }
  10342. out._id = input._id || (input.id === undefined ? '_fc' + eventGUID++ : input.id + '');
  10343. if (input.className) {
  10344. if (typeof input.className == 'string') {
  10345. out.className = input.className.split(/\s+/);
  10346. }
  10347. else { // assumed to be an array
  10348. out.className = input.className;
  10349. }
  10350. }
  10351. else {
  10352. out.className = [];
  10353. }
  10354. start = input.start || input.date; // "date" is an alias for "start"
  10355. end = input.end;
  10356. // parse as a time (Duration) if applicable
  10357. if (isTimeString(start)) {
  10358. start = moment.duration(start);
  10359. }
  10360. if (isTimeString(end)) {
  10361. end = moment.duration(end);
  10362. }
  10363. if (input.dow || moment.isDuration(start) || moment.isDuration(end)) {
  10364. // the event is "abstract" (recurring) so don't calculate exact start/end dates just yet
  10365. out.start = start ? moment.duration(start) : null; // will be a Duration or null
  10366. out.end = end ? moment.duration(end) : null; // will be a Duration or null
  10367. out._recurring = true; // our internal marker
  10368. }
  10369. else {
  10370. if (start) {
  10371. start = t.moment(start);
  10372. if (!start.isValid()) {
  10373. return false;
  10374. }
  10375. }
  10376. if (end) {
  10377. end = t.moment(end);
  10378. if (!end.isValid()) {
  10379. end = null; // let defaults take over
  10380. }
  10381. }
  10382. allDay = input.allDay;
  10383. if (allDay === undefined) { // still undefined? fallback to default
  10384. allDay = firstDefined(
  10385. source ? source.allDayDefault : undefined,
  10386. t.opt('allDayDefault')
  10387. );
  10388. // still undefined? normalizeEventDates will calculate it
  10389. }
  10390. assignDatesToEvent(start, end, allDay, out);
  10391. }
  10392. t.normalizeEvent(out); // hook for external use. a prototype method
  10393. return out;
  10394. }
  10395. t.buildEventFromInput = buildEventFromInput;
  10396. // Normalizes and assigns the given dates to the given partially-formed event object.
  10397. // NOTE: mutates the given start/end moments. does not make a copy.
  10398. function assignDatesToEvent(start, end, allDay, event) {
  10399. event.start = start;
  10400. event.end = end;
  10401. event.allDay = allDay;
  10402. normalizeEventDates(event);
  10403. backupEventDates(event);
  10404. }
  10405. // Ensures proper values for allDay/start/end. Accepts an Event object, or a plain object with event-ish properties.
  10406. // NOTE: Will modify the given object.
  10407. function normalizeEventDates(eventProps) {
  10408. normalizeEventTimes(eventProps);
  10409. if (eventProps.end && !eventProps.end.isAfter(eventProps.start)) {
  10410. eventProps.end = null;
  10411. }
  10412. if (!eventProps.end) {
  10413. if (t.opt('forceEventDuration')) {
  10414. eventProps.end = t.getDefaultEventEnd(eventProps.allDay, eventProps.start);
  10415. }
  10416. else {
  10417. eventProps.end = null;
  10418. }
  10419. }
  10420. }
  10421. // Ensures the allDay property exists and the timeliness of the start/end dates are consistent
  10422. function normalizeEventTimes(eventProps) {
  10423. if (eventProps.allDay == null) {
  10424. eventProps.allDay = !(eventProps.start.hasTime() || (eventProps.end && eventProps.end.hasTime()));
  10425. }
  10426. if (eventProps.allDay) {
  10427. eventProps.start.stripTime();
  10428. if (eventProps.end) {
  10429. // TODO: consider nextDayThreshold here? If so, will require a lot of testing and adjustment
  10430. eventProps.end.stripTime();
  10431. }
  10432. }
  10433. else {
  10434. if (!eventProps.start.hasTime()) {
  10435. eventProps.start = t.applyTimezone(eventProps.start.time(0)); // will assign a 00:00 time
  10436. }
  10437. if (eventProps.end && !eventProps.end.hasTime()) {
  10438. eventProps.end = t.applyTimezone(eventProps.end.time(0)); // will assign a 00:00 time
  10439. }
  10440. }
  10441. }
  10442. // If the given event is a recurring event, break it down into an array of individual instances.
  10443. // If not a recurring event, return an array with the single original event.
  10444. // If given a falsy input (probably because of a failed buildEventFromInput call), returns an empty array.
  10445. // HACK: can override the recurring window by providing custom rangeStart/rangeEnd (for businessHours).
  10446. function expandEvent(abstractEvent, _rangeStart, _rangeEnd) {
  10447. var events = [];
  10448. var dowHash;
  10449. var dow;
  10450. var i;
  10451. var date;
  10452. var startTime, endTime;
  10453. var start, end;
  10454. var event;
  10455. _rangeStart = _rangeStart || rangeStart;
  10456. _rangeEnd = _rangeEnd || rangeEnd;
  10457. if (abstractEvent) {
  10458. if (abstractEvent._recurring) {
  10459. // make a boolean hash as to whether the event occurs on each day-of-week
  10460. if ((dow = abstractEvent.dow)) {
  10461. dowHash = {};
  10462. for (i = 0; i < dow.length; i++) {
  10463. dowHash[dow[i]] = true;
  10464. }
  10465. }
  10466. // iterate through every day in the current range
  10467. date = _rangeStart.clone().stripTime(); // holds the date of the current day
  10468. while (date.isBefore(_rangeEnd)) {
  10469. if (!dowHash || dowHash[date.day()]) { // if everyday, or this particular day-of-week
  10470. startTime = abstractEvent.start; // the stored start and end properties are times (Durations)
  10471. endTime = abstractEvent.end; // "
  10472. start = date.clone();
  10473. end = null;
  10474. if (startTime) {
  10475. start = start.time(startTime);
  10476. }
  10477. if (endTime) {
  10478. end = date.clone().time(endTime);
  10479. }
  10480. event = $.extend({}, abstractEvent); // make a copy of the original
  10481. assignDatesToEvent(
  10482. start, end,
  10483. !startTime && !endTime, // allDay?
  10484. event
  10485. );
  10486. events.push(event);
  10487. }
  10488. date.add(1, 'days');
  10489. }
  10490. }
  10491. else {
  10492. events.push(abstractEvent); // return the original event. will be a one-item array
  10493. }
  10494. }
  10495. return events;
  10496. }
  10497. t.expandEvent = expandEvent;
  10498. /* Event Modification Math
  10499. -----------------------------------------------------------------------------------------*/
  10500. // Modifies an event and all related events by applying the given properties.
  10501. // Special date-diffing logic is used for manipulation of dates.
  10502. // If `props` does not contain start/end dates, the updated values are assumed to be the event's current start/end.
  10503. // All date comparisons are done against the event's pristine _start and _end dates.
  10504. // Returns an object with delta information and a function to undo all operations.
  10505. // For making computations in a granularity greater than day/time, specify largeUnit.
  10506. // NOTE: The given `newProps` might be mutated for normalization purposes.
  10507. function mutateEvent(event, newProps, largeUnit) {
  10508. var miscProps = {};
  10509. var oldProps;
  10510. var clearEnd;
  10511. var startDelta;
  10512. var endDelta;
  10513. var durationDelta;
  10514. var undoFunc;
  10515. // diffs the dates in the appropriate way, returning a duration
  10516. function diffDates(date1, date0) { // date1 - date0
  10517. if (largeUnit) {
  10518. return diffByUnit(date1, date0, largeUnit);
  10519. }
  10520. else if (newProps.allDay) {
  10521. return diffDay(date1, date0);
  10522. }
  10523. else {
  10524. return diffDayTime(date1, date0);
  10525. }
  10526. }
  10527. newProps = newProps || {};
  10528. // normalize new date-related properties
  10529. if (!newProps.start) {
  10530. newProps.start = event.start.clone();
  10531. }
  10532. if (newProps.end === undefined) {
  10533. newProps.end = event.end ? event.end.clone() : null;
  10534. }
  10535. if (newProps.allDay == null) { // is null or undefined?
  10536. newProps.allDay = event.allDay;
  10537. }
  10538. normalizeEventDates(newProps);
  10539. // create normalized versions of the original props to compare against
  10540. // need a real end value, for diffing
  10541. oldProps = {
  10542. start: event._start.clone(),
  10543. end: event._end ? event._end.clone() : t.getDefaultEventEnd(event._allDay, event._start),
  10544. allDay: newProps.allDay // normalize the dates in the same regard as the new properties
  10545. };
  10546. normalizeEventDates(oldProps);
  10547. // need to clear the end date if explicitly changed to null
  10548. clearEnd = event._end !== null && newProps.end === null;
  10549. // compute the delta for moving the start date
  10550. startDelta = diffDates(newProps.start, oldProps.start);
  10551. // compute the delta for moving the end date
  10552. if (newProps.end) {
  10553. endDelta = diffDates(newProps.end, oldProps.end);
  10554. durationDelta = endDelta.subtract(startDelta);
  10555. }
  10556. else {
  10557. durationDelta = null;
  10558. }
  10559. // gather all non-date-related properties
  10560. $.each(newProps, function(name, val) {
  10561. if (isMiscEventPropName(name)) {
  10562. if (val !== undefined) {
  10563. miscProps[name] = val;
  10564. }
  10565. }
  10566. });
  10567. // apply the operations to the event and all related events
  10568. undoFunc = mutateEvents(
  10569. clientEvents(event._id), // get events with this ID
  10570. clearEnd,
  10571. newProps.allDay,
  10572. startDelta,
  10573. durationDelta,
  10574. miscProps
  10575. );
  10576. return {
  10577. dateDelta: startDelta,
  10578. durationDelta: durationDelta,
  10579. undo: undoFunc
  10580. };
  10581. }
  10582. // Modifies an array of events in the following ways (operations are in order):
  10583. // - clear the event's `end`
  10584. // - convert the event to allDay
  10585. // - add `dateDelta` to the start and end
  10586. // - add `durationDelta` to the event's duration
  10587. // - assign `miscProps` to the event
  10588. //
  10589. // Returns a function that can be called to undo all the operations.
  10590. //
  10591. // TODO: don't use so many closures. possible memory issues when lots of events with same ID.
  10592. //
  10593. function mutateEvents(events, clearEnd, allDay, dateDelta, durationDelta, miscProps) {
  10594. var isAmbigTimezone = t.getIsAmbigTimezone();
  10595. var undoFunctions = [];
  10596. // normalize zero-length deltas to be null
  10597. if (dateDelta && !dateDelta.valueOf()) { dateDelta = null; }
  10598. if (durationDelta && !durationDelta.valueOf()) { durationDelta = null; }
  10599. $.each(events, function(i, event) {
  10600. var oldProps;
  10601. var newProps;
  10602. // build an object holding all the old values, both date-related and misc.
  10603. // for the undo function.
  10604. oldProps = {
  10605. start: event.start.clone(),
  10606. end: event.end ? event.end.clone() : null,
  10607. allDay: event.allDay
  10608. };
  10609. $.each(miscProps, function(name) {
  10610. oldProps[name] = event[name];
  10611. });
  10612. // new date-related properties. work off the original date snapshot.
  10613. // ok to use references because they will be thrown away when backupEventDates is called.
  10614. newProps = {
  10615. start: event._start,
  10616. end: event._end,
  10617. allDay: allDay // normalize the dates in the same regard as the new properties
  10618. };
  10619. normalizeEventDates(newProps); // massages start/end/allDay
  10620. // strip or ensure the end date
  10621. if (clearEnd) {
  10622. newProps.end = null;
  10623. }
  10624. else if (durationDelta && !newProps.end) { // the duration translation requires an end date
  10625. newProps.end = t.getDefaultEventEnd(newProps.allDay, newProps.start);
  10626. }
  10627. if (dateDelta) {
  10628. newProps.start.add(dateDelta);
  10629. if (newProps.end) {
  10630. newProps.end.add(dateDelta);
  10631. }
  10632. }
  10633. if (durationDelta) {
  10634. newProps.end.add(durationDelta); // end already ensured above
  10635. }
  10636. // if the dates have changed, and we know it is impossible to recompute the
  10637. // timezone offsets, strip the zone.
  10638. if (
  10639. isAmbigTimezone &&
  10640. !newProps.allDay &&
  10641. (dateDelta || durationDelta)
  10642. ) {
  10643. newProps.start.stripZone();
  10644. if (newProps.end) {
  10645. newProps.end.stripZone();
  10646. }
  10647. }
  10648. $.extend(event, miscProps, newProps); // copy over misc props, then date-related props
  10649. backupEventDates(event); // regenerate internal _start/_end/_allDay
  10650. undoFunctions.push(function() {
  10651. $.extend(event, oldProps);
  10652. backupEventDates(event); // regenerate internal _start/_end/_allDay
  10653. });
  10654. });
  10655. return function() {
  10656. for (var i = 0; i < undoFunctions.length; i++) {
  10657. undoFunctions[i]();
  10658. }
  10659. };
  10660. }
  10661. }
  10662. // returns an undo function
  10663. Calendar.prototype.mutateSeg = function(seg, newProps) {
  10664. return this.mutateEvent(seg.event, newProps);
  10665. };
  10666. // hook for external libs to manipulate event properties upon creation.
  10667. // should manipulate the event in-place.
  10668. Calendar.prototype.normalizeEvent = function(event) {
  10669. };
  10670. // Does the given span (start, end, and other location information)
  10671. // fully contain the other?
  10672. Calendar.prototype.spanContainsSpan = function(outerSpan, innerSpan) {
  10673. var eventStart = outerSpan.start.clone().stripZone();
  10674. var eventEnd = this.getEventEnd(outerSpan).stripZone();
  10675. return innerSpan.start >= eventStart && innerSpan.end <= eventEnd;
  10676. };
  10677. // Returns a list of events that the given event should be compared against when being considered for a move to
  10678. // the specified span. Attached to the Calendar's prototype because EventManager is a mixin for a Calendar.
  10679. Calendar.prototype.getPeerEvents = function(span, event) {
  10680. var cache = this.getEventCache();
  10681. var peerEvents = [];
  10682. var i, otherEvent;
  10683. for (i = 0; i < cache.length; i++) {
  10684. otherEvent = cache[i];
  10685. if (
  10686. !event ||
  10687. event._id !== otherEvent._id // don't compare the event to itself or other related [repeating] events
  10688. ) {
  10689. peerEvents.push(otherEvent);
  10690. }
  10691. }
  10692. return peerEvents;
  10693. };
  10694. // updates the "backup" properties, which are preserved in order to compute diffs later on.
  10695. function backupEventDates(event) {
  10696. event._allDay = event.allDay;
  10697. event._start = event.start.clone();
  10698. event._end = event.end ? event.end.clone() : null;
  10699. }
  10700. /* Overlapping / Constraining
  10701. -----------------------------------------------------------------------------------------*/
  10702. // Determines if the given event can be relocated to the given span (unzoned start/end with other misc data)
  10703. Calendar.prototype.isEventSpanAllowed = function(span, event) {
  10704. var source = event.source || {};
  10705. var eventAllowFunc = this.opt('eventAllow');
  10706. var constraint = firstDefined(
  10707. event.constraint,
  10708. source.constraint,
  10709. this.opt('eventConstraint')
  10710. );
  10711. var overlap = firstDefined(
  10712. event.overlap,
  10713. source.overlap,
  10714. this.opt('eventOverlap')
  10715. );
  10716. return this.isSpanAllowed(span, constraint, overlap, event) &&
  10717. (!eventAllowFunc || eventAllowFunc(span, event) !== false);
  10718. };
  10719. // Determines if an external event can be relocated to the given span (unzoned start/end with other misc data)
  10720. Calendar.prototype.isExternalSpanAllowed = function(eventSpan, eventLocation, eventProps) {
  10721. var eventInput;
  10722. var event;
  10723. // note: very similar logic is in View's reportExternalDrop
  10724. if (eventProps) {
  10725. eventInput = $.extend({}, eventProps, eventLocation);
  10726. event = this.expandEvent(
  10727. this.buildEventFromInput(eventInput)
  10728. )[0];
  10729. }
  10730. if (event) {
  10731. return this.isEventSpanAllowed(eventSpan, event);
  10732. }
  10733. else { // treat it as a selection
  10734. return this.isSelectionSpanAllowed(eventSpan);
  10735. }
  10736. };
  10737. // Determines the given span (unzoned start/end with other misc data) can be selected.
  10738. Calendar.prototype.isSelectionSpanAllowed = function(span) {
  10739. var selectAllowFunc = this.opt('selectAllow');
  10740. return this.isSpanAllowed(span, this.opt('selectConstraint'), this.opt('selectOverlap')) &&
  10741. (!selectAllowFunc || selectAllowFunc(span) !== false);
  10742. };
  10743. // Returns true if the given span (caused by an event drop/resize or a selection) is allowed to exist
  10744. // according to the constraint/overlap settings.
  10745. // `event` is not required if checking a selection.
  10746. Calendar.prototype.isSpanAllowed = function(span, constraint, overlap, event) {
  10747. var constraintEvents;
  10748. var anyContainment;
  10749. var peerEvents;
  10750. var i, peerEvent;
  10751. var peerOverlap;
  10752. // the range must be fully contained by at least one of produced constraint events
  10753. if (constraint != null) {
  10754. // not treated as an event! intermediate data structure
  10755. // TODO: use ranges in the future
  10756. constraintEvents = this.constraintToEvents(constraint);
  10757. if (constraintEvents) { // not invalid
  10758. anyContainment = false;
  10759. for (i = 0; i < constraintEvents.length; i++) {
  10760. if (this.spanContainsSpan(constraintEvents[i], span)) {
  10761. anyContainment = true;
  10762. break;
  10763. }
  10764. }
  10765. if (!anyContainment) {
  10766. return false;
  10767. }
  10768. }
  10769. }
  10770. peerEvents = this.getPeerEvents(span, event);
  10771. for (i = 0; i < peerEvents.length; i++) {
  10772. peerEvent = peerEvents[i];
  10773. // there needs to be an actual intersection before disallowing anything
  10774. if (this.eventIntersectsRange(peerEvent, span)) {
  10775. // evaluate overlap for the given range and short-circuit if necessary
  10776. if (overlap === false) {
  10777. return false;
  10778. }
  10779. // if the event's overlap is a test function, pass the peer event in question as the first param
  10780. else if (typeof overlap === 'function' && !overlap(peerEvent, event)) {
  10781. return false;
  10782. }
  10783. // if we are computing if the given range is allowable for an event, consider the other event's
  10784. // EventObject-specific or Source-specific `overlap` property
  10785. if (event) {
  10786. peerOverlap = firstDefined(
  10787. peerEvent.overlap,
  10788. (peerEvent.source || {}).overlap
  10789. // we already considered the global `eventOverlap`
  10790. );
  10791. if (peerOverlap === false) {
  10792. return false;
  10793. }
  10794. // if the peer event's overlap is a test function, pass the subject event as the first param
  10795. if (typeof peerOverlap === 'function' && !peerOverlap(event, peerEvent)) {
  10796. return false;
  10797. }
  10798. }
  10799. }
  10800. }
  10801. return true;
  10802. };
  10803. // Given an event input from the API, produces an array of event objects. Possible event inputs:
  10804. // 'businessHours'
  10805. // An event ID (number or string)
  10806. // An object with specific start/end dates or a recurring event (like what businessHours accepts)
  10807. Calendar.prototype.constraintToEvents = function(constraintInput) {
  10808. if (constraintInput === 'businessHours') {
  10809. return this.getCurrentBusinessHourEvents();
  10810. }
  10811. if (typeof constraintInput === 'object') {
  10812. if (constraintInput.start != null) { // needs to be event-like input
  10813. return this.expandEvent(this.buildEventFromInput(constraintInput));
  10814. }
  10815. else {
  10816. return null; // invalid
  10817. }
  10818. }
  10819. return this.clientEvents(constraintInput); // probably an ID
  10820. };
  10821. // Does the event's date range intersect with the given range?
  10822. // start/end already assumed to have stripped zones :(
  10823. Calendar.prototype.eventIntersectsRange = function(event, range) {
  10824. var eventStart = event.start.clone().stripZone();
  10825. var eventEnd = this.getEventEnd(event).stripZone();
  10826. return range.start < eventEnd && range.end > eventStart;
  10827. };
  10828. /* Business Hours
  10829. -----------------------------------------------------------------------------------------*/
  10830. var BUSINESS_HOUR_EVENT_DEFAULTS = {
  10831. id: '_fcBusinessHours', // will relate events from different calls to expandEvent
  10832. start: '09:00',
  10833. end: '17:00',
  10834. dow: [ 1, 2, 3, 4, 5 ], // monday - friday
  10835. rendering: 'inverse-background'
  10836. // classNames are defined in businessHoursSegClasses
  10837. };
  10838. // Return events objects for business hours within the current view.
  10839. // Abuse of our event system :(
  10840. Calendar.prototype.getCurrentBusinessHourEvents = function(wholeDay) {
  10841. return this.computeBusinessHourEvents(wholeDay, this.opt('businessHours'));
  10842. };
  10843. // Given a raw input value from options, return events objects for business hours within the current view.
  10844. Calendar.prototype.computeBusinessHourEvents = function(wholeDay, input) {
  10845. if (input === true) {
  10846. return this.expandBusinessHourEvents(wholeDay, [ {} ]);
  10847. }
  10848. else if ($.isPlainObject(input)) {
  10849. return this.expandBusinessHourEvents(wholeDay, [ input ]);
  10850. }
  10851. else if ($.isArray(input)) {
  10852. return this.expandBusinessHourEvents(wholeDay, input, true);
  10853. }
  10854. else {
  10855. return [];
  10856. }
  10857. };
  10858. // inputs expected to be an array of objects.
  10859. // if ignoreNoDow is true, will ignore entries that don't specify a day-of-week (dow) key.
  10860. Calendar.prototype.expandBusinessHourEvents = function(wholeDay, inputs, ignoreNoDow) {
  10861. var view = this.getView();
  10862. var events = [];
  10863. var i, input;
  10864. for (i = 0; i < inputs.length; i++) {
  10865. input = inputs[i];
  10866. if (ignoreNoDow && !input.dow) {
  10867. continue;
  10868. }
  10869. // give defaults. will make a copy
  10870. input = $.extend({}, BUSINESS_HOUR_EVENT_DEFAULTS, input);
  10871. // if a whole-day series is requested, clear the start/end times
  10872. if (wholeDay) {
  10873. input.start = null;
  10874. input.end = null;
  10875. }
  10876. events.push.apply(events, // append
  10877. this.expandEvent(
  10878. this.buildEventFromInput(input),
  10879. view.activeRange.start,
  10880. view.activeRange.end
  10881. )
  10882. );
  10883. }
  10884. return events;
  10885. };
  10886. ;;
  10887. /* An abstract class for the "basic" views, as well as month view. Renders one or more rows of day cells.
  10888. ----------------------------------------------------------------------------------------------------------------------*/
  10889. // It is a manager for a DayGrid subcomponent, which does most of the heavy lifting.
  10890. // It is responsible for managing width/height.
  10891. var BasicView = FC.BasicView = View.extend({
  10892. scroller: null,
  10893. dayGridClass: DayGrid, // class the dayGrid will be instantiated from (overridable by subclasses)
  10894. dayGrid: null, // the main subcomponent that does most of the heavy lifting
  10895. dayNumbersVisible: false, // display day numbers on each day cell?
  10896. colWeekNumbersVisible: false, // display week numbers along the side?
  10897. cellWeekNumbersVisible: false, // display week numbers in day cell?
  10898. weekNumberWidth: null, // width of all the week-number cells running down the side
  10899. headContainerEl: null, // div that hold's the dayGrid's rendered date header
  10900. headRowEl: null, // the fake row element of the day-of-week header
  10901. initialize: function() {
  10902. this.dayGrid = this.instantiateDayGrid();
  10903. this.scroller = new Scroller({
  10904. overflowX: 'hidden',
  10905. overflowY: 'auto'
  10906. });
  10907. },
  10908. // Generates the DayGrid object this view needs. Draws from this.dayGridClass
  10909. instantiateDayGrid: function() {
  10910. // generate a subclass on the fly with BasicView-specific behavior
  10911. // TODO: cache this subclass
  10912. var subclass = this.dayGridClass.extend(basicDayGridMethods);
  10913. return new subclass(this);
  10914. },
  10915. // Computes the date range that will be rendered.
  10916. buildRenderRange: function(currentRange, currentRangeUnit) {
  10917. var renderRange = View.prototype.buildRenderRange.apply(this, arguments);
  10918. // year and month views should be aligned with weeks. this is already done for week
  10919. if (/^(year|month)$/.test(currentRangeUnit)) {
  10920. renderRange.start.startOf('week');
  10921. // make end-of-week if not already
  10922. if (renderRange.end.weekday()) {
  10923. renderRange.end.add(1, 'week').startOf('week'); // exclusively move backwards
  10924. }
  10925. }
  10926. return this.trimHiddenDays(renderRange);
  10927. },
  10928. // Renders the view into `this.el`, which should already be assigned
  10929. renderDates: function() {
  10930. this.dayGrid.breakOnWeeks = /year|month|week/.test(this.currentRangeUnit); // do before Grid::setRange
  10931. this.dayGrid.setRange(this.renderRange);
  10932. this.dayNumbersVisible = this.dayGrid.rowCnt > 1; // TODO: make grid responsible
  10933. if (this.opt('weekNumbers')) {
  10934. if (this.opt('weekNumbersWithinDays')) {
  10935. this.cellWeekNumbersVisible = true;
  10936. this.colWeekNumbersVisible = false;
  10937. }
  10938. else {
  10939. this.cellWeekNumbersVisible = false;
  10940. this.colWeekNumbersVisible = true;
  10941. };
  10942. }
  10943. this.dayGrid.numbersVisible = this.dayNumbersVisible ||
  10944. this.cellWeekNumbersVisible || this.colWeekNumbersVisible;
  10945. this.el.addClass('fc-basic-view').html(this.renderSkeletonHtml());
  10946. this.renderHead();
  10947. this.scroller.render();
  10948. var dayGridContainerEl = this.scroller.el.addClass('fc-day-grid-container');
  10949. var dayGridEl = $('<div class="fc-day-grid" />').appendTo(dayGridContainerEl);
  10950. this.el.find('.fc-body > tr > td').append(dayGridContainerEl);
  10951. this.dayGrid.setElement(dayGridEl);
  10952. this.dayGrid.renderDates(this.hasRigidRows());
  10953. },
  10954. // render the day-of-week headers
  10955. renderHead: function() {
  10956. this.headContainerEl =
  10957. this.el.find('.fc-head-container')
  10958. .html(this.dayGrid.renderHeadHtml());
  10959. this.headRowEl = this.headContainerEl.find('.fc-row');
  10960. },
  10961. // Unrenders the content of the view. Since we haven't separated skeleton rendering from date rendering,
  10962. // always completely kill the dayGrid's rendering.
  10963. unrenderDates: function() {
  10964. this.dayGrid.unrenderDates();
  10965. this.dayGrid.removeElement();
  10966. this.scroller.destroy();
  10967. },
  10968. renderBusinessHours: function() {
  10969. this.dayGrid.renderBusinessHours();
  10970. },
  10971. unrenderBusinessHours: function() {
  10972. this.dayGrid.unrenderBusinessHours();
  10973. },
  10974. // Builds the HTML skeleton for the view.
  10975. // The day-grid component will render inside of a container defined by this HTML.
  10976. renderSkeletonHtml: function() {
  10977. return '' +
  10978. '<table>' +
  10979. '<thead class="fc-head">' +
  10980. '<tr>' +
  10981. '<td class="fc-head-container ' + this.widgetHeaderClass + '"></td>' +
  10982. '</tr>' +
  10983. '</thead>' +
  10984. '<tbody class="fc-body">' +
  10985. '<tr>' +
  10986. '<td class="' + this.widgetContentClass + '"></td>' +
  10987. '</tr>' +
  10988. '</tbody>' +
  10989. '</table>';
  10990. },
  10991. // Generates an HTML attribute string for setting the width of the week number column, if it is known
  10992. weekNumberStyleAttr: function() {
  10993. if (this.weekNumberWidth !== null) {
  10994. return 'style="width:' + this.weekNumberWidth + 'px"';
  10995. }
  10996. return '';
  10997. },
  10998. // Determines whether each row should have a constant height
  10999. hasRigidRows: function() {
  11000. var eventLimit = this.opt('eventLimit');
  11001. return eventLimit && typeof eventLimit !== 'number';
  11002. },
  11003. /* Dimensions
  11004. ------------------------------------------------------------------------------------------------------------------*/
  11005. // Refreshes the horizontal dimensions of the view
  11006. updateWidth: function() {
  11007. if (this.colWeekNumbersVisible) {
  11008. // Make sure all week number cells running down the side have the same width.
  11009. // Record the width for cells created later.
  11010. this.weekNumberWidth = matchCellWidths(
  11011. this.el.find('.fc-week-number')
  11012. );
  11013. }
  11014. },
  11015. // Adjusts the vertical dimensions of the view to the specified values
  11016. setHeight: function(totalHeight, isAuto) {
  11017. var eventLimit = this.opt('eventLimit');
  11018. var scrollerHeight;
  11019. var scrollbarWidths;
  11020. // reset all heights to be natural
  11021. this.scroller.clear();
  11022. uncompensateScroll(this.headRowEl);
  11023. this.dayGrid.removeSegPopover(); // kill the "more" popover if displayed
  11024. // is the event limit a constant level number?
  11025. if (eventLimit && typeof eventLimit === 'number') {
  11026. this.dayGrid.limitRows(eventLimit); // limit the levels first so the height can redistribute after
  11027. }
  11028. // distribute the height to the rows
  11029. // (totalHeight is a "recommended" value if isAuto)
  11030. scrollerHeight = this.computeScrollerHeight(totalHeight);
  11031. this.setGridHeight(scrollerHeight, isAuto);
  11032. // is the event limit dynamically calculated?
  11033. if (eventLimit && typeof eventLimit !== 'number') {
  11034. this.dayGrid.limitRows(eventLimit); // limit the levels after the grid's row heights have been set
  11035. }
  11036. if (!isAuto) { // should we force dimensions of the scroll container?
  11037. this.scroller.setHeight(scrollerHeight);
  11038. scrollbarWidths = this.scroller.getScrollbarWidths();
  11039. if (scrollbarWidths.left || scrollbarWidths.right) { // using scrollbars?
  11040. compensateScroll(this.headRowEl, scrollbarWidths);
  11041. // doing the scrollbar compensation might have created text overflow which created more height. redo
  11042. scrollerHeight = this.computeScrollerHeight(totalHeight);
  11043. this.scroller.setHeight(scrollerHeight);
  11044. }
  11045. // guarantees the same scrollbar widths
  11046. this.scroller.lockOverflow(scrollbarWidths);
  11047. }
  11048. },
  11049. // given a desired total height of the view, returns what the height of the scroller should be
  11050. computeScrollerHeight: function(totalHeight) {
  11051. return totalHeight -
  11052. subtractInnerElHeight(this.el, this.scroller.el); // everything that's NOT the scroller
  11053. },
  11054. // Sets the height of just the DayGrid component in this view
  11055. setGridHeight: function(height, isAuto) {
  11056. if (isAuto) {
  11057. undistributeHeight(this.dayGrid.rowEls); // let the rows be their natural height with no expanding
  11058. }
  11059. else {
  11060. distributeHeight(this.dayGrid.rowEls, height, true); // true = compensate for height-hogging rows
  11061. }
  11062. },
  11063. /* Scroll
  11064. ------------------------------------------------------------------------------------------------------------------*/
  11065. computeInitialDateScroll: function() {
  11066. return { top: 0 };
  11067. },
  11068. queryDateScroll: function() {
  11069. return { top: this.scroller.getScrollTop() };
  11070. },
  11071. applyDateScroll: function(scroll) {
  11072. if (scroll.top !== undefined) {
  11073. this.scroller.setScrollTop(scroll.top);
  11074. }
  11075. },
  11076. /* Hit Areas
  11077. ------------------------------------------------------------------------------------------------------------------*/
  11078. // forward all hit-related method calls to dayGrid
  11079. hitsNeeded: function() {
  11080. this.dayGrid.hitsNeeded();
  11081. },
  11082. hitsNotNeeded: function() {
  11083. this.dayGrid.hitsNotNeeded();
  11084. },
  11085. prepareHits: function() {
  11086. this.dayGrid.prepareHits();
  11087. },
  11088. releaseHits: function() {
  11089. this.dayGrid.releaseHits();
  11090. },
  11091. queryHit: function(left, top) {
  11092. return this.dayGrid.queryHit(left, top);
  11093. },
  11094. getHitSpan: function(hit) {
  11095. return this.dayGrid.getHitSpan(hit);
  11096. },
  11097. getHitEl: function(hit) {
  11098. return this.dayGrid.getHitEl(hit);
  11099. },
  11100. /* Events
  11101. ------------------------------------------------------------------------------------------------------------------*/
  11102. // Renders the given events onto the view and populates the segments array
  11103. renderEvents: function(events) {
  11104. this.dayGrid.renderEvents(events);
  11105. this.updateHeight(); // must compensate for events that overflow the row
  11106. },
  11107. // Retrieves all segment objects that are rendered in the view
  11108. getEventSegs: function() {
  11109. return this.dayGrid.getEventSegs();
  11110. },
  11111. // Unrenders all event elements and clears internal segment data
  11112. unrenderEvents: function() {
  11113. this.dayGrid.unrenderEvents();
  11114. // we DON'T need to call updateHeight() because
  11115. // a renderEvents() call always happens after this, which will eventually call updateHeight()
  11116. },
  11117. /* Dragging (for both events and external elements)
  11118. ------------------------------------------------------------------------------------------------------------------*/
  11119. // A returned value of `true` signals that a mock "helper" event has been rendered.
  11120. renderDrag: function(dropLocation, seg) {
  11121. return this.dayGrid.renderDrag(dropLocation, seg);
  11122. },
  11123. unrenderDrag: function() {
  11124. this.dayGrid.unrenderDrag();
  11125. },
  11126. /* Selection
  11127. ------------------------------------------------------------------------------------------------------------------*/
  11128. // Renders a visual indication of a selection
  11129. renderSelection: function(span) {
  11130. this.dayGrid.renderSelection(span);
  11131. },
  11132. // Unrenders a visual indications of a selection
  11133. unrenderSelection: function() {
  11134. this.dayGrid.unrenderSelection();
  11135. }
  11136. });
  11137. // Methods that will customize the rendering behavior of the BasicView's dayGrid
  11138. var basicDayGridMethods = {
  11139. // Generates the HTML that will go before the day-of week header cells
  11140. renderHeadIntroHtml: function() {
  11141. var view = this.view;
  11142. if (view.colWeekNumbersVisible) {
  11143. return '' +
  11144. '<th class="fc-week-number ' + view.widgetHeaderClass + '" ' + view.weekNumberStyleAttr() + '>' +
  11145. '<span>' + // needed for matchCellWidths
  11146. htmlEscape(view.opt('weekNumberTitle')) +
  11147. '</span>' +
  11148. '</th>';
  11149. }
  11150. return '';
  11151. },
  11152. // Generates the HTML that will go before content-skeleton cells that display the day/week numbers
  11153. renderNumberIntroHtml: function(row) {
  11154. var view = this.view;
  11155. var weekStart = this.getCellDate(row, 0);
  11156. if (view.colWeekNumbersVisible) {
  11157. return '' +
  11158. '<td class="fc-week-number" ' + view.weekNumberStyleAttr() + '>' +
  11159. view.buildGotoAnchorHtml( // aside from link, important for matchCellWidths
  11160. { date: weekStart, type: 'week', forceOff: this.colCnt === 1 },
  11161. weekStart.format('w') // inner HTML
  11162. ) +
  11163. '</td>';
  11164. }
  11165. return '';
  11166. },
  11167. // Generates the HTML that goes before the day bg cells for each day-row
  11168. renderBgIntroHtml: function() {
  11169. var view = this.view;
  11170. if (view.colWeekNumbersVisible) {
  11171. return '<td class="fc-week-number ' + view.widgetContentClass + '" ' +
  11172. view.weekNumberStyleAttr() + '></td>';
  11173. }
  11174. return '';
  11175. },
  11176. // Generates the HTML that goes before every other type of row generated by DayGrid.
  11177. // Affects helper-skeleton and highlight-skeleton rows.
  11178. renderIntroHtml: function() {
  11179. var view = this.view;
  11180. if (view.colWeekNumbersVisible) {
  11181. return '<td class="fc-week-number" ' + view.weekNumberStyleAttr() + '></td>';
  11182. }
  11183. return '';
  11184. }
  11185. };
  11186. ;;
  11187. /* A month view with day cells running in rows (one-per-week) and columns
  11188. ----------------------------------------------------------------------------------------------------------------------*/
  11189. var MonthView = FC.MonthView = BasicView.extend({
  11190. // Computes the date range that will be rendered.
  11191. buildRenderRange: function() {
  11192. var renderRange = BasicView.prototype.buildRenderRange.apply(this, arguments);
  11193. var rowCnt;
  11194. // ensure 6 weeks
  11195. if (this.isFixedWeeks()) {
  11196. rowCnt = Math.ceil( // could be partial weeks due to hiddenDays
  11197. renderRange.end.diff(renderRange.start, 'weeks', true) // dontRound=true
  11198. );
  11199. renderRange.end.add(6 - rowCnt, 'weeks');
  11200. }
  11201. return renderRange;
  11202. },
  11203. // Overrides the default BasicView behavior to have special multi-week auto-height logic
  11204. setGridHeight: function(height, isAuto) {
  11205. // if auto, make the height of each row the height that it would be if there were 6 weeks
  11206. if (isAuto) {
  11207. height *= this.rowCnt / 6;
  11208. }
  11209. distributeHeight(this.dayGrid.rowEls, height, !isAuto); // if auto, don't compensate for height-hogging rows
  11210. },
  11211. isFixedWeeks: function() {
  11212. return this.opt('fixedWeekCount');
  11213. }
  11214. });
  11215. ;;
  11216. fcViews.basic = {
  11217. 'class': BasicView
  11218. };
  11219. fcViews.basicDay = {
  11220. type: 'basic',
  11221. duration: { days: 1 }
  11222. };
  11223. fcViews.basicWeek = {
  11224. type: 'basic',
  11225. duration: { weeks: 1 }
  11226. };
  11227. fcViews.month = {
  11228. 'class': MonthView,
  11229. duration: { months: 1 }, // important for prev/next
  11230. defaults: {
  11231. fixedWeekCount: true
  11232. }
  11233. };
  11234. ;;
  11235. /* An abstract class for all agenda-related views. Displays one more columns with time slots running vertically.
  11236. ----------------------------------------------------------------------------------------------------------------------*/
  11237. // Is a manager for the TimeGrid subcomponent and possibly the DayGrid subcomponent (if allDaySlot is on).
  11238. // Responsible for managing width/height.
  11239. var AgendaView = FC.AgendaView = View.extend({
  11240. scroller: null,
  11241. timeGridClass: TimeGrid, // class used to instantiate the timeGrid. subclasses can override
  11242. timeGrid: null, // the main time-grid subcomponent of this view
  11243. dayGridClass: DayGrid, // class used to instantiate the dayGrid. subclasses can override
  11244. dayGrid: null, // the "all-day" subcomponent. if all-day is turned off, this will be null
  11245. axisWidth: null, // the width of the time axis running down the side
  11246. headContainerEl: null, // div that hold's the timeGrid's rendered date header
  11247. noScrollRowEls: null, // set of fake row elements that must compensate when scroller has scrollbars
  11248. // when the time-grid isn't tall enough to occupy the given height, we render an <hr> underneath
  11249. bottomRuleEl: null,
  11250. // indicates that minTime/maxTime affects rendering
  11251. usesMinMaxTime: true,
  11252. initialize: function() {
  11253. this.timeGrid = this.instantiateTimeGrid();
  11254. if (this.opt('allDaySlot')) { // should we display the "all-day" area?
  11255. this.dayGrid = this.instantiateDayGrid(); // the all-day subcomponent of this view
  11256. }
  11257. this.scroller = new Scroller({
  11258. overflowX: 'hidden',
  11259. overflowY: 'auto'
  11260. });
  11261. },
  11262. // Instantiates the TimeGrid object this view needs. Draws from this.timeGridClass
  11263. instantiateTimeGrid: function() {
  11264. var subclass = this.timeGridClass.extend(agendaTimeGridMethods);
  11265. return new subclass(this);
  11266. },
  11267. // Instantiates the DayGrid object this view might need. Draws from this.dayGridClass
  11268. instantiateDayGrid: function() {
  11269. var subclass = this.dayGridClass.extend(agendaDayGridMethods);
  11270. return new subclass(this);
  11271. },
  11272. /* Rendering
  11273. ------------------------------------------------------------------------------------------------------------------*/
  11274. // Renders the view into `this.el`, which has already been assigned
  11275. renderDates: function() {
  11276. this.timeGrid.setRange(this.renderRange);
  11277. if (this.dayGrid) {
  11278. this.dayGrid.setRange(this.renderRange);
  11279. }
  11280. this.el.addClass('fc-agenda-view').html(this.renderSkeletonHtml());
  11281. this.renderHead();
  11282. this.scroller.render();
  11283. var timeGridWrapEl = this.scroller.el.addClass('fc-time-grid-container');
  11284. var timeGridEl = $('<div class="fc-time-grid" />').appendTo(timeGridWrapEl);
  11285. this.el.find('.fc-body > tr > td').append(timeGridWrapEl);
  11286. this.timeGrid.setElement(timeGridEl);
  11287. this.timeGrid.renderDates();
  11288. // the <hr> that sometimes displays under the time-grid
  11289. this.bottomRuleEl = $('<hr class="fc-divider ' + this.widgetHeaderClass + '"/>')
  11290. .appendTo(this.timeGrid.el); // inject it into the time-grid
  11291. if (this.dayGrid) {
  11292. this.dayGrid.setElement(this.el.find('.fc-day-grid'));
  11293. this.dayGrid.renderDates();
  11294. // have the day-grid extend it's coordinate area over the <hr> dividing the two grids
  11295. this.dayGrid.bottomCoordPadding = this.dayGrid.el.next('hr').outerHeight();
  11296. }
  11297. this.noScrollRowEls = this.el.find('.fc-row:not(.fc-scroller *)'); // fake rows not within the scroller
  11298. },
  11299. // render the day-of-week headers
  11300. renderHead: function() {
  11301. this.headContainerEl =
  11302. this.el.find('.fc-head-container')
  11303. .html(this.timeGrid.renderHeadHtml());
  11304. },
  11305. // Unrenders the content of the view. Since we haven't separated skeleton rendering from date rendering,
  11306. // always completely kill each grid's rendering.
  11307. unrenderDates: function() {
  11308. this.timeGrid.unrenderDates();
  11309. this.timeGrid.removeElement();
  11310. if (this.dayGrid) {
  11311. this.dayGrid.unrenderDates();
  11312. this.dayGrid.removeElement();
  11313. }
  11314. this.scroller.destroy();
  11315. },
  11316. // Builds the HTML skeleton for the view.
  11317. // The day-grid and time-grid components will render inside containers defined by this HTML.
  11318. renderSkeletonHtml: function() {
  11319. return '' +
  11320. '<table>' +
  11321. '<thead class="fc-head">' +
  11322. '<tr>' +
  11323. '<td class="fc-head-container ' + this.widgetHeaderClass + '"></td>' +
  11324. '</tr>' +
  11325. '</thead>' +
  11326. '<tbody class="fc-body">' +
  11327. '<tr>' +
  11328. '<td class="' + this.widgetContentClass + '">' +
  11329. (this.dayGrid ?
  11330. '<div class="fc-day-grid"/>' +
  11331. '<hr class="fc-divider ' + this.widgetHeaderClass + '"/>' :
  11332. ''
  11333. ) +
  11334. '</td>' +
  11335. '</tr>' +
  11336. '</tbody>' +
  11337. '</table>';
  11338. },
  11339. // Generates an HTML attribute string for setting the width of the axis, if it is known
  11340. axisStyleAttr: function() {
  11341. if (this.axisWidth !== null) {
  11342. return 'style="width:' + this.axisWidth + 'px"';
  11343. }
  11344. return '';
  11345. },
  11346. /* Business Hours
  11347. ------------------------------------------------------------------------------------------------------------------*/
  11348. renderBusinessHours: function() {
  11349. this.timeGrid.renderBusinessHours();
  11350. if (this.dayGrid) {
  11351. this.dayGrid.renderBusinessHours();
  11352. }
  11353. },
  11354. unrenderBusinessHours: function() {
  11355. this.timeGrid.unrenderBusinessHours();
  11356. if (this.dayGrid) {
  11357. this.dayGrid.unrenderBusinessHours();
  11358. }
  11359. },
  11360. /* Now Indicator
  11361. ------------------------------------------------------------------------------------------------------------------*/
  11362. getNowIndicatorUnit: function() {
  11363. return this.timeGrid.getNowIndicatorUnit();
  11364. },
  11365. renderNowIndicator: function(date) {
  11366. this.timeGrid.renderNowIndicator(date);
  11367. },
  11368. unrenderNowIndicator: function() {
  11369. this.timeGrid.unrenderNowIndicator();
  11370. },
  11371. /* Dimensions
  11372. ------------------------------------------------------------------------------------------------------------------*/
  11373. updateSize: function(isResize) {
  11374. this.timeGrid.updateSize(isResize);
  11375. View.prototype.updateSize.call(this, isResize); // call the super-method
  11376. },
  11377. // Refreshes the horizontal dimensions of the view
  11378. updateWidth: function() {
  11379. // make all axis cells line up, and record the width so newly created axis cells will have it
  11380. this.axisWidth = matchCellWidths(this.el.find('.fc-axis'));
  11381. },
  11382. // Adjusts the vertical dimensions of the view to the specified values
  11383. setHeight: function(totalHeight, isAuto) {
  11384. var eventLimit;
  11385. var scrollerHeight;
  11386. var scrollbarWidths;
  11387. // reset all dimensions back to the original state
  11388. this.bottomRuleEl.hide(); // .show() will be called later if this <hr> is necessary
  11389. this.scroller.clear(); // sets height to 'auto' and clears overflow
  11390. uncompensateScroll(this.noScrollRowEls);
  11391. // limit number of events in the all-day area
  11392. if (this.dayGrid) {
  11393. this.dayGrid.removeSegPopover(); // kill the "more" popover if displayed
  11394. eventLimit = this.opt('eventLimit');
  11395. if (eventLimit && typeof eventLimit !== 'number') {
  11396. eventLimit = AGENDA_ALL_DAY_EVENT_LIMIT; // make sure "auto" goes to a real number
  11397. }
  11398. if (eventLimit) {
  11399. this.dayGrid.limitRows(eventLimit);
  11400. }
  11401. }
  11402. if (!isAuto) { // should we force dimensions of the scroll container?
  11403. scrollerHeight = this.computeScrollerHeight(totalHeight);
  11404. this.scroller.setHeight(scrollerHeight);
  11405. scrollbarWidths = this.scroller.getScrollbarWidths();
  11406. if (scrollbarWidths.left || scrollbarWidths.right) { // using scrollbars?
  11407. // make the all-day and header rows lines up
  11408. compensateScroll(this.noScrollRowEls, scrollbarWidths);
  11409. // the scrollbar compensation might have changed text flow, which might affect height, so recalculate
  11410. // and reapply the desired height to the scroller.
  11411. scrollerHeight = this.computeScrollerHeight(totalHeight);
  11412. this.scroller.setHeight(scrollerHeight);
  11413. }
  11414. // guarantees the same scrollbar widths
  11415. this.scroller.lockOverflow(scrollbarWidths);
  11416. // if there's any space below the slats, show the horizontal rule.
  11417. // this won't cause any new overflow, because lockOverflow already called.
  11418. if (this.timeGrid.getTotalSlatHeight() < scrollerHeight) {
  11419. this.bottomRuleEl.show();
  11420. }
  11421. }
  11422. },
  11423. // given a desired total height of the view, returns what the height of the scroller should be
  11424. computeScrollerHeight: function(totalHeight) {
  11425. return totalHeight -
  11426. subtractInnerElHeight(this.el, this.scroller.el); // everything that's NOT the scroller
  11427. },
  11428. /* Scroll
  11429. ------------------------------------------------------------------------------------------------------------------*/
  11430. // Computes the initial pre-configured scroll state prior to allowing the user to change it
  11431. computeInitialDateScroll: function() {
  11432. var scrollTime = moment.duration(this.opt('scrollTime'));
  11433. var top = this.timeGrid.computeTimeTop(scrollTime);
  11434. // zoom can give weird floating-point values. rather scroll a little bit further
  11435. top = Math.ceil(top);
  11436. if (top) {
  11437. top++; // to overcome top border that slots beyond the first have. looks better
  11438. }
  11439. return { top: top };
  11440. },
  11441. queryDateScroll: function() {
  11442. return { top: this.scroller.getScrollTop() };
  11443. },
  11444. applyDateScroll: function(scroll) {
  11445. if (scroll.top !== undefined) {
  11446. this.scroller.setScrollTop(scroll.top);
  11447. }
  11448. },
  11449. /* Hit Areas
  11450. ------------------------------------------------------------------------------------------------------------------*/
  11451. // forward all hit-related method calls to the grids (dayGrid might not be defined)
  11452. hitsNeeded: function() {
  11453. this.timeGrid.hitsNeeded();
  11454. if (this.dayGrid) {
  11455. this.dayGrid.hitsNeeded();
  11456. }
  11457. },
  11458. hitsNotNeeded: function() {
  11459. this.timeGrid.hitsNotNeeded();
  11460. if (this.dayGrid) {
  11461. this.dayGrid.hitsNotNeeded();
  11462. }
  11463. },
  11464. prepareHits: function() {
  11465. this.timeGrid.prepareHits();
  11466. if (this.dayGrid) {
  11467. this.dayGrid.prepareHits();
  11468. }
  11469. },
  11470. releaseHits: function() {
  11471. this.timeGrid.releaseHits();
  11472. if (this.dayGrid) {
  11473. this.dayGrid.releaseHits();
  11474. }
  11475. },
  11476. queryHit: function(left, top) {
  11477. var hit = this.timeGrid.queryHit(left, top);
  11478. if (!hit && this.dayGrid) {
  11479. hit = this.dayGrid.queryHit(left, top);
  11480. }
  11481. return hit;
  11482. },
  11483. getHitSpan: function(hit) {
  11484. // TODO: hit.component is set as a hack to identify where the hit came from
  11485. return hit.component.getHitSpan(hit);
  11486. },
  11487. getHitEl: function(hit) {
  11488. // TODO: hit.component is set as a hack to identify where the hit came from
  11489. return hit.component.getHitEl(hit);
  11490. },
  11491. /* Events
  11492. ------------------------------------------------------------------------------------------------------------------*/
  11493. // Renders events onto the view and populates the View's segment array
  11494. renderEvents: function(events) {
  11495. var dayEvents = [];
  11496. var timedEvents = [];
  11497. var daySegs = [];
  11498. var timedSegs;
  11499. var i;
  11500. // separate the events into all-day and timed
  11501. for (i = 0; i < events.length; i++) {
  11502. if (events[i].allDay) {
  11503. dayEvents.push(events[i]);
  11504. }
  11505. else {
  11506. timedEvents.push(events[i]);
  11507. }
  11508. }
  11509. // render the events in the subcomponents
  11510. timedSegs = this.timeGrid.renderEvents(timedEvents);
  11511. if (this.dayGrid) {
  11512. daySegs = this.dayGrid.renderEvents(dayEvents);
  11513. }
  11514. // the all-day area is flexible and might have a lot of events, so shift the height
  11515. this.updateHeight();
  11516. },
  11517. // Retrieves all segment objects that are rendered in the view
  11518. getEventSegs: function() {
  11519. return this.timeGrid.getEventSegs().concat(
  11520. this.dayGrid ? this.dayGrid.getEventSegs() : []
  11521. );
  11522. },
  11523. // Unrenders all event elements and clears internal segment data
  11524. unrenderEvents: function() {
  11525. // unrender the events in the subcomponents
  11526. this.timeGrid.unrenderEvents();
  11527. if (this.dayGrid) {
  11528. this.dayGrid.unrenderEvents();
  11529. }
  11530. // we DON'T need to call updateHeight() because
  11531. // a renderEvents() call always happens after this, which will eventually call updateHeight()
  11532. },
  11533. /* Dragging (for events and external elements)
  11534. ------------------------------------------------------------------------------------------------------------------*/
  11535. // A returned value of `true` signals that a mock "helper" event has been rendered.
  11536. renderDrag: function(dropLocation, seg) {
  11537. if (dropLocation.start.hasTime()) {
  11538. return this.timeGrid.renderDrag(dropLocation, seg);
  11539. }
  11540. else if (this.dayGrid) {
  11541. return this.dayGrid.renderDrag(dropLocation, seg);
  11542. }
  11543. },
  11544. unrenderDrag: function() {
  11545. this.timeGrid.unrenderDrag();
  11546. if (this.dayGrid) {
  11547. this.dayGrid.unrenderDrag();
  11548. }
  11549. },
  11550. /* Selection
  11551. ------------------------------------------------------------------------------------------------------------------*/
  11552. // Renders a visual indication of a selection
  11553. renderSelection: function(span) {
  11554. if (span.start.hasTime() || span.end.hasTime()) {
  11555. this.timeGrid.renderSelection(span);
  11556. }
  11557. else if (this.dayGrid) {
  11558. this.dayGrid.renderSelection(span);
  11559. }
  11560. },
  11561. // Unrenders a visual indications of a selection
  11562. unrenderSelection: function() {
  11563. this.timeGrid.unrenderSelection();
  11564. if (this.dayGrid) {
  11565. this.dayGrid.unrenderSelection();
  11566. }
  11567. }
  11568. });
  11569. // Methods that will customize the rendering behavior of the AgendaView's timeGrid
  11570. // TODO: move into TimeGrid
  11571. var agendaTimeGridMethods = {
  11572. // Generates the HTML that will go before the day-of week header cells
  11573. renderHeadIntroHtml: function() {
  11574. var view = this.view;
  11575. var weekText;
  11576. if (view.opt('weekNumbers')) {
  11577. weekText = this.start.format(view.opt('smallWeekFormat'));
  11578. return '' +
  11579. '<th class="fc-axis fc-week-number ' + view.widgetHeaderClass + '" ' + view.axisStyleAttr() + '>' +
  11580. view.buildGotoAnchorHtml( // aside from link, important for matchCellWidths
  11581. { date: this.start, type: 'week', forceOff: this.colCnt > 1 },
  11582. htmlEscape(weekText) // inner HTML
  11583. ) +
  11584. '</th>';
  11585. }
  11586. else {
  11587. return '<th class="fc-axis ' + view.widgetHeaderClass + '" ' + view.axisStyleAttr() + '></th>';
  11588. }
  11589. },
  11590. // Generates the HTML that goes before the bg of the TimeGrid slot area. Long vertical column.
  11591. renderBgIntroHtml: function() {
  11592. var view = this.view;
  11593. return '<td class="fc-axis ' + view.widgetContentClass + '" ' + view.axisStyleAttr() + '></td>';
  11594. },
  11595. // Generates the HTML that goes before all other types of cells.
  11596. // Affects content-skeleton, helper-skeleton, highlight-skeleton for both the time-grid and day-grid.
  11597. renderIntroHtml: function() {
  11598. var view = this.view;
  11599. return '<td class="fc-axis" ' + view.axisStyleAttr() + '></td>';
  11600. }
  11601. };
  11602. // Methods that will customize the rendering behavior of the AgendaView's dayGrid
  11603. var agendaDayGridMethods = {
  11604. // Generates the HTML that goes before the all-day cells
  11605. renderBgIntroHtml: function() {
  11606. var view = this.view;
  11607. return '' +
  11608. '<td class="fc-axis ' + view.widgetContentClass + '" ' + view.axisStyleAttr() + '>' +
  11609. '<span>' + // needed for matchCellWidths
  11610. view.getAllDayHtml() +
  11611. '</span>' +
  11612. '</td>';
  11613. },
  11614. // Generates the HTML that goes before all other types of cells.
  11615. // Affects content-skeleton, helper-skeleton, highlight-skeleton for both the time-grid and day-grid.
  11616. renderIntroHtml: function() {
  11617. var view = this.view;
  11618. return '<td class="fc-axis" ' + view.axisStyleAttr() + '></td>';
  11619. }
  11620. };
  11621. ;;
  11622. var AGENDA_ALL_DAY_EVENT_LIMIT = 5;
  11623. // potential nice values for the slot-duration and interval-duration
  11624. // from largest to smallest
  11625. var AGENDA_STOCK_SUB_DURATIONS = [
  11626. { hours: 1 },
  11627. { minutes: 30 },
  11628. { minutes: 15 },
  11629. { seconds: 30 },
  11630. { seconds: 15 }
  11631. ];
  11632. fcViews.agenda = {
  11633. 'class': AgendaView,
  11634. defaults: {
  11635. allDaySlot: true,
  11636. slotDuration: '00:30:00',
  11637. slotEventOverlap: true // a bad name. confused with overlap/constraint system
  11638. }
  11639. };
  11640. fcViews.agendaDay = {
  11641. type: 'agenda',
  11642. duration: { days: 1 }
  11643. };
  11644. fcViews.agendaWeek = {
  11645. type: 'agenda',
  11646. duration: { weeks: 1 }
  11647. };
  11648. ;;
  11649. /*
  11650. Responsible for the scroller, and forwarding event-related actions into the "grid"
  11651. */
  11652. var ListView = View.extend({
  11653. grid: null,
  11654. scroller: null,
  11655. initialize: function() {
  11656. this.grid = new ListViewGrid(this);
  11657. this.scroller = new Scroller({
  11658. overflowX: 'hidden',
  11659. overflowY: 'auto'
  11660. });
  11661. },
  11662. renderSkeleton: function() {
  11663. this.el.addClass(
  11664. 'fc-list-view ' +
  11665. this.widgetContentClass
  11666. );
  11667. this.scroller.render();
  11668. this.scroller.el.appendTo(this.el);
  11669. this.grid.setElement(this.scroller.scrollEl);
  11670. },
  11671. unrenderSkeleton: function() {
  11672. this.scroller.destroy(); // will remove the Grid too
  11673. },
  11674. setHeight: function(totalHeight, isAuto) {
  11675. this.scroller.setHeight(this.computeScrollerHeight(totalHeight));
  11676. },
  11677. computeScrollerHeight: function(totalHeight) {
  11678. return totalHeight -
  11679. subtractInnerElHeight(this.el, this.scroller.el); // everything that's NOT the scroller
  11680. },
  11681. renderDates: function() {
  11682. this.grid.setRange(this.renderRange); // needs to process range-related options
  11683. },
  11684. renderEvents: function(events) {
  11685. this.grid.renderEvents(events);
  11686. },
  11687. unrenderEvents: function() {
  11688. this.grid.unrenderEvents();
  11689. },
  11690. isEventResizable: function(event) {
  11691. return false;
  11692. },
  11693. isEventDraggable: function(event) {
  11694. return false;
  11695. }
  11696. });
  11697. /*
  11698. Responsible for event rendering and user-interaction.
  11699. Its "el" is the inner-content of the above view's scroller.
  11700. */
  11701. var ListViewGrid = Grid.extend({
  11702. segSelector: '.fc-list-item', // which elements accept event actions
  11703. hasDayInteractions: false, // no day selection or day clicking
  11704. // slices by day
  11705. spanToSegs: function(span) {
  11706. var view = this.view;
  11707. var dayStart = view.renderRange.start.clone().time(0); // timed, so segs get times!
  11708. var dayIndex = 0;
  11709. var seg;
  11710. var segs = [];
  11711. while (dayStart < view.renderRange.end) {
  11712. seg = intersectRanges(span, {
  11713. start: dayStart,
  11714. end: dayStart.clone().add(1, 'day')
  11715. });
  11716. if (seg) {
  11717. seg.dayIndex = dayIndex;
  11718. segs.push(seg);
  11719. }
  11720. dayStart.add(1, 'day');
  11721. dayIndex++;
  11722. // detect when span won't go fully into the next day,
  11723. // and mutate the latest seg to the be the end.
  11724. if (
  11725. seg && !seg.isEnd && span.end.hasTime() &&
  11726. span.end < dayStart.clone().add(this.view.nextDayThreshold)
  11727. ) {
  11728. seg.end = span.end.clone();
  11729. seg.isEnd = true;
  11730. break;
  11731. }
  11732. }
  11733. return segs;
  11734. },
  11735. // like "4:00am"
  11736. computeEventTimeFormat: function() {
  11737. return this.view.opt('mediumTimeFormat');
  11738. },
  11739. // for events with a url, the whole <tr> should be clickable,
  11740. // but it's impossible to wrap with an <a> tag. simulate this.
  11741. handleSegClick: function(seg, ev) {
  11742. var url;
  11743. Grid.prototype.handleSegClick.apply(this, arguments); // super. might prevent the default action
  11744. // not clicking on or within an <a> with an href
  11745. if (!$(ev.target).closest('a[href]').length) {
  11746. url = seg.event.url;
  11747. if (url && !ev.isDefaultPrevented()) { // jsEvent not cancelled in handler
  11748. window.location.href = url; // simulate link click
  11749. }
  11750. }
  11751. },
  11752. // returns list of foreground segs that were actually rendered
  11753. renderFgSegs: function(segs) {
  11754. segs = this.renderFgSegEls(segs); // might filter away hidden events
  11755. if (!segs.length) {
  11756. this.renderEmptyMessage();
  11757. }
  11758. else {
  11759. this.renderSegList(segs);
  11760. }
  11761. return segs;
  11762. },
  11763. renderEmptyMessage: function() {
  11764. this.el.html(
  11765. '<div class="fc-list-empty-wrap2">' + // TODO: try less wraps
  11766. '<div class="fc-list-empty-wrap1">' +
  11767. '<div class="fc-list-empty">' +
  11768. htmlEscape(this.view.opt('noEventsMessage')) +
  11769. '</div>' +
  11770. '</div>' +
  11771. '</div>'
  11772. );
  11773. },
  11774. // render the event segments in the view
  11775. renderSegList: function(allSegs) {
  11776. var segsByDay = this.groupSegsByDay(allSegs); // sparse array
  11777. var dayIndex;
  11778. var daySegs;
  11779. var i;
  11780. var tableEl = $('<table class="fc-list-table"><tbody/></table>');
  11781. var tbodyEl = tableEl.find('tbody');
  11782. for (dayIndex = 0; dayIndex < segsByDay.length; dayIndex++) {
  11783. daySegs = segsByDay[dayIndex];
  11784. if (daySegs) { // sparse array, so might be undefined
  11785. // append a day header
  11786. tbodyEl.append(this.dayHeaderHtml(
  11787. this.view.renderRange.start.clone().add(dayIndex, 'days')
  11788. ));
  11789. this.sortEventSegs(daySegs);
  11790. for (i = 0; i < daySegs.length; i++) {
  11791. tbodyEl.append(daySegs[i].el); // append event row
  11792. }
  11793. }
  11794. }
  11795. this.el.empty().append(tableEl);
  11796. },
  11797. // Returns a sparse array of arrays, segs grouped by their dayIndex
  11798. groupSegsByDay: function(segs) {
  11799. var segsByDay = []; // sparse array
  11800. var i, seg;
  11801. for (i = 0; i < segs.length; i++) {
  11802. seg = segs[i];
  11803. (segsByDay[seg.dayIndex] || (segsByDay[seg.dayIndex] = []))
  11804. .push(seg);
  11805. }
  11806. return segsByDay;
  11807. },
  11808. // generates the HTML for the day headers that live amongst the event rows
  11809. dayHeaderHtml: function(dayDate) {
  11810. var view = this.view;
  11811. var mainFormat = view.opt('listDayFormat');
  11812. var altFormat = view.opt('listDayAltFormat');
  11813. return '<tr class="fc-list-heading" data-date="' + dayDate.format('YYYY-MM-DD') + '">' +
  11814. '<td class="' + view.widgetHeaderClass + '" colspan="3">' +
  11815. (mainFormat ?
  11816. view.buildGotoAnchorHtml(
  11817. dayDate,
  11818. { 'class': 'fc-list-heading-main' },
  11819. htmlEscape(dayDate.format(mainFormat)) // inner HTML
  11820. ) :
  11821. '') +
  11822. (altFormat ?
  11823. view.buildGotoAnchorHtml(
  11824. dayDate,
  11825. { 'class': 'fc-list-heading-alt' },
  11826. htmlEscape(dayDate.format(altFormat)) // inner HTML
  11827. ) :
  11828. '') +
  11829. '</td>' +
  11830. '</tr>';
  11831. },
  11832. // generates the HTML for a single event row
  11833. fgSegHtml: function(seg) {
  11834. var view = this.view;
  11835. var classes = [ 'fc-list-item' ].concat(this.getSegCustomClasses(seg));
  11836. var bgColor = this.getSegBackgroundColor(seg);
  11837. var event = seg.event;
  11838. var url = event.url;
  11839. var timeHtml;
  11840. if (event.allDay) {
  11841. timeHtml = view.getAllDayHtml();
  11842. }
  11843. else if (view.isMultiDayEvent(event)) { // if the event appears to span more than one day
  11844. if (seg.isStart || seg.isEnd) { // outer segment that probably lasts part of the day
  11845. timeHtml = htmlEscape(this.getEventTimeText(seg));
  11846. }
  11847. else { // inner segment that lasts the whole day
  11848. timeHtml = view.getAllDayHtml();
  11849. }
  11850. }
  11851. else {
  11852. // Display the normal time text for the *event's* times
  11853. timeHtml = htmlEscape(this.getEventTimeText(event));
  11854. }
  11855. if (url) {
  11856. classes.push('fc-has-url');
  11857. }
  11858. return '<tr class="' + classes.join(' ') + '">' +
  11859. (this.displayEventTime ?
  11860. '<td class="fc-list-item-time ' + view.widgetContentClass + '">' +
  11861. (timeHtml || '') +
  11862. '</td>' :
  11863. '') +
  11864. '<td class="fc-list-item-marker ' + view.widgetContentClass + '">' +
  11865. '<span class="fc-event-dot"' +
  11866. (bgColor ?
  11867. ' style="background-color:' + bgColor + '"' :
  11868. '') +
  11869. '></span>' +
  11870. '</td>' +
  11871. '<td class="fc-list-item-title ' + view.widgetContentClass + '">' +
  11872. '<a' + (url ? ' href="' + htmlEscape(url) + '"' : '') + '>' +
  11873. htmlEscape(seg.event.title || '') +
  11874. '</a>' +
  11875. '</td>' +
  11876. '</tr>';
  11877. }
  11878. });
  11879. ;;
  11880. fcViews.list = {
  11881. 'class': ListView,
  11882. buttonTextKey: 'list', // what to lookup in locale files
  11883. defaults: {
  11884. buttonText: 'list', // text to display for English
  11885. listDayFormat: 'LL', // like "January 1, 2016"
  11886. noEventsMessage: 'No events to display'
  11887. }
  11888. };
  11889. fcViews.listDay = {
  11890. type: 'list',
  11891. duration: { days: 1 },
  11892. defaults: {
  11893. listDayFormat: 'dddd' // day-of-week is all we need. full date is probably in header
  11894. }
  11895. };
  11896. fcViews.listWeek = {
  11897. type: 'list',
  11898. duration: { weeks: 1 },
  11899. defaults: {
  11900. listDayFormat: 'dddd', // day-of-week is more important
  11901. listDayAltFormat: 'LL'
  11902. }
  11903. };
  11904. fcViews.listMonth = {
  11905. type: 'list',
  11906. duration: { month: 1 },
  11907. defaults: {
  11908. listDayAltFormat: 'dddd' // day-of-week is nice-to-have
  11909. }
  11910. };
  11911. fcViews.listYear = {
  11912. type: 'list',
  11913. duration: { year: 1 },
  11914. defaults: {
  11915. listDayAltFormat: 'dddd' // day-of-week is nice-to-have
  11916. }
  11917. };
  11918. ;;
  11919. return FC; // export for Node/CommonJS
  11920. });