fullcalendar.js 331 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906
  1. /*!
  2. * FullCalendar v2.6.1
  3. * Docs & License: http://fullcalendar.io/
  4. * (c) 2015 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(jQuery, moment) {
  17. ;;
  18. var FC = jQuery.fullCalendar = {
  19. version: "2.6.1",
  20. internalApiVersion: 3
  21. };
  22. var fcViews = FC.views = {};
  23. jQuery.fn.fullCalendar = function(options) {
  24. var args = Array.prototype.slice.call(arguments, 1); // for a possible method call
  25. var res = this; // what this function will return (this jQuery object by default)
  26. this.each(function(i, _element) { // loop each DOM element involved
  27. var element = jQuery(_element);
  28. var calendar = element.data('fullCalendar'); // get the existing calendar object (if any)
  29. var singleRes; // the returned value of this single method call
  30. // a method call
  31. if (typeof options === 'string') {
  32. if (calendar && jQuery.isFunction(calendar[options])) {
  33. singleRes = calendar[options].apply(calendar, args);
  34. if (!i) {
  35. res = singleRes; // record the first method call result
  36. }
  37. if (options === 'destroy') { // for the destroy method, must remove Calendar object data
  38. element.removeData('fullCalendar');
  39. }
  40. }
  41. }
  42. // a new calendar initialization
  43. else if (!calendar) { // don't initialize twice
  44. calendar = new Calendar(element, options);
  45. element.data('fullCalendar', calendar);
  46. calendar.render();
  47. }
  48. });
  49. return res;
  50. };
  51. var complexOptions = [ // names of options that are objects whose properties should be combined
  52. 'header',
  53. 'buttonText',
  54. 'buttonIcons',
  55. 'themeButtonIcons'
  56. ];
  57. // Merges an array of option objects into a single object
  58. function mergeOptions(optionObjs) {
  59. return mergeProps(optionObjs, complexOptions);
  60. }
  61. // Given options specified for the calendar's constructor, massages any legacy options into a non-legacy form.
  62. // Converts View-Option-Hashes into the View-Specific-Options format.
  63. function massageOverrides(input) {
  64. var overrides = { views: input.views || {} }; // the output. ensure a `views` hash
  65. var subObj;
  66. // iterate through all option override properties (except `views`)
  67. jQuery.each(input, function(name, val) {
  68. if (name != 'views') {
  69. // could the value be a legacy View-Option-Hash?
  70. if (
  71. jQuery.isPlainObject(val) &&
  72. !/(time|duration|interval)$/i.test(name) && // exclude duration options. might be given as objects
  73. jQuery.inArray(name, complexOptions) == -1 // complex options aren't allowed to be View-Option-Hashes
  74. ) {
  75. subObj = null;
  76. // iterate through the properties of this possible View-Option-Hash value
  77. jQuery.each(val, function(subName, subVal) {
  78. // is the property targeting a view?
  79. if (/^(month|week|day|default|basic(Week|Day)?|agenda(Week|Day)?)$/.test(subName)) {
  80. if (!overrides.views[subName]) { // ensure the view-target entry exists
  81. overrides.views[subName] = {};
  82. }
  83. overrides.views[subName][name] = subVal; // record the value in the `views` object
  84. }
  85. else { // a non-View-Option-Hash property
  86. if (!subObj) {
  87. subObj = {};
  88. }
  89. subObj[subName] = subVal; // accumulate these unrelated values for later
  90. }
  91. });
  92. if (subObj) { // non-View-Option-Hash properties? transfer them as-is
  93. overrides[name] = subObj;
  94. }
  95. }
  96. else {
  97. overrides[name] = val; // transfer normal options as-is
  98. }
  99. }
  100. });
  101. return overrides;
  102. }
  103. ;;
  104. // exports
  105. FC.intersectRanges = intersectRanges;
  106. FC.applyAll = applyAll;
  107. FC.debounce = debounce;
  108. FC.isInt = isInt;
  109. FC.htmlEscape = htmlEscape;
  110. FC.cssToStr = cssToStr;
  111. FC.proxy = proxy;
  112. FC.capitaliseFirstLetter = capitaliseFirstLetter;
  113. /* FullCalendar-specific DOM Utilities
  114. ----------------------------------------------------------------------------------------------------------------------*/
  115. // Given the scrollbar widths of some other container, create borders/margins on rowEls in order to match the left
  116. // and right space that was offset by the scrollbars. A 1-pixel border first, then margin beyond that.
  117. function compensateScroll(rowEls, scrollbarWidths) {
  118. if (scrollbarWidths.left) {
  119. rowEls.css({
  120. 'border-left-width': 1,
  121. 'margin-left': scrollbarWidths.left - 1
  122. });
  123. }
  124. if (scrollbarWidths.right) {
  125. rowEls.css({
  126. 'border-right-width': 1,
  127. 'margin-right': scrollbarWidths.right - 1
  128. });
  129. }
  130. }
  131. // Undoes compensateScroll and restores all borders/margins
  132. function uncompensateScroll(rowEls) {
  133. rowEls.css({
  134. 'margin-left': '',
  135. 'margin-right': '',
  136. 'border-left-width': '',
  137. 'border-right-width': ''
  138. });
  139. }
  140. // Make the mouse cursor express that an event is not allowed in the current area
  141. function disableCursor() {
  142. jQuery('body').addClass('fc-not-allowed');
  143. }
  144. // Returns the mouse cursor to its original look
  145. function enableCursor() {
  146. jQuery('body').removeClass('fc-not-allowed');
  147. }
  148. // Given a total available height to fill, have `els` (essentially child rows) expand to accomodate.
  149. // By default, all elements that are shorter than the recommended height are expanded uniformly, not considering
  150. // any other els that are already too tall. if `shouldRedistribute` is on, it considers these tall rows and
  151. // reduces the available height.
  152. function distributeHeight(els, availableHeight, shouldRedistribute) {
  153. // *FLOORING NOTE*: we floor in certain places because zoom can give inaccurate floating-point dimensions,
  154. // and it is better to be shorter than taller, to avoid creating unnecessary scrollbars.
  155. var minOffset1 = Math.floor(availableHeight / els.length); // for non-last element
  156. var minOffset2 = Math.floor(availableHeight - minOffset1 * (els.length - 1)); // for last element *FLOORING NOTE*
  157. var flexEls = []; // elements that are allowed to expand. array of DOM nodes
  158. var flexOffsets = []; // amount of vertical space it takes up
  159. var flexHeights = []; // actual css height
  160. var usedHeight = 0;
  161. undistributeHeight(els); // give all elements their natural height
  162. // find elements that are below the recommended height (expandable).
  163. // important to query for heights in a single first pass (to avoid reflow oscillation).
  164. els.each(function(i, el) {
  165. var minOffset = i === els.length - 1 ? minOffset2 : minOffset1;
  166. var naturalOffset = jQuery(el).outerHeight(true);
  167. if (naturalOffset < minOffset) {
  168. flexEls.push(el);
  169. flexOffsets.push(naturalOffset);
  170. flexHeights.push(jQuery(el).height());
  171. }
  172. else {
  173. // this element stretches past recommended height (non-expandable). mark the space as occupied.
  174. usedHeight += naturalOffset;
  175. }
  176. });
  177. // readjust the recommended height to only consider the height available to non-maxed-out rows.
  178. if (shouldRedistribute) {
  179. availableHeight -= usedHeight;
  180. minOffset1 = Math.floor(availableHeight / flexEls.length);
  181. minOffset2 = Math.floor(availableHeight - minOffset1 * (flexEls.length - 1)); // *FLOORING NOTE*
  182. }
  183. // assign heights to all expandable elements
  184. jQuery(flexEls).each(function(i, el) {
  185. var minOffset = i === flexEls.length - 1 ? minOffset2 : minOffset1;
  186. var naturalOffset = flexOffsets[i];
  187. var naturalHeight = flexHeights[i];
  188. var newHeight = minOffset - (naturalOffset - naturalHeight); // subtract the margin/padding
  189. if (naturalOffset < minOffset) { // we check this again because redistribution might have changed things
  190. jQuery(el).height(newHeight);
  191. }
  192. });
  193. }
  194. // Undoes distrubuteHeight, restoring all els to their natural height
  195. function undistributeHeight(els) {
  196. els.height('');
  197. }
  198. // Given `els`, a jQuery set of <td> cells, find the cell with the largest natural width and set the widths of all the
  199. // cells to be that width.
  200. // PREREQUISITE: if you want a cell to take up width, it needs to have a single inner element w/ display:inline
  201. function matchCellWidths(els) {
  202. var maxInnerWidth = 0;
  203. els.find('> span').each(function(i, innerEl) {
  204. var innerWidth = jQuery(innerEl).outerWidth();
  205. if (innerWidth > maxInnerWidth) {
  206. maxInnerWidth = innerWidth;
  207. }
  208. });
  209. maxInnerWidth++; // sometimes not accurate of width the text needs to stay on one line. insurance
  210. els.width(maxInnerWidth);
  211. return maxInnerWidth;
  212. }
  213. // Turns a container element into a scroller if its contents is taller than the allotted height.
  214. // Returns true if the element is now a scroller, false otherwise.
  215. // NOTE: this method is best because it takes weird zooming dimensions into account
  216. function setPotentialScroller(containerEl, height) {
  217. containerEl.height(height).addClass('fc-scroller');
  218. // are scrollbars needed?
  219. if (containerEl[0].scrollHeight - 1 > containerEl[0].clientHeight) { // !!! -1 because IE is often off-by-one :(
  220. return true;
  221. }
  222. unsetScroller(containerEl); // undo
  223. return false;
  224. }
  225. // Takes an element that might have been a scroller, and turns it back into a normal element.
  226. function unsetScroller(containerEl) {
  227. containerEl.height('').removeClass('fc-scroller');
  228. }
  229. /* General DOM Utilities
  230. ----------------------------------------------------------------------------------------------------------------------*/
  231. FC.getOuterRect = getOuterRect;
  232. FC.getClientRect = getClientRect;
  233. FC.getContentRect = getContentRect;
  234. FC.getScrollbarWidths = getScrollbarWidths;
  235. // borrowed from https://github.com/jquery/jquery-ui/blob/1.11.0/ui/core.js#L51
  236. function getScrollParent(el) {
  237. var position = el.css('position'),
  238. scrollParent = el.parents().filter(function() {
  239. var parent = jQuery(this);
  240. return (/(auto|scroll)/).test(
  241. parent.css('overflow') + parent.css('overflow-y') + parent.css('overflow-x')
  242. );
  243. }).eq(0);
  244. return position === 'fixed' || !scrollParent.length ? jQuery(el[0].ownerDocument || document) : scrollParent;
  245. }
  246. // Queries the outer bounding area of a jQuery element.
  247. // Returns a rectangle with absolute coordinates: left, right (exclusive), top, bottom (exclusive).
  248. function getOuterRect(el) {
  249. var offset = el.offset();
  250. return {
  251. left: offset.left,
  252. right: offset.left + el.outerWidth(),
  253. top: offset.top,
  254. bottom: offset.top + el.outerHeight()
  255. };
  256. }
  257. // Queries the area within the margin/border/scrollbars of a jQuery element. Does not go within the padding.
  258. // Returns a rectangle with absolute coordinates: left, right (exclusive), top, bottom (exclusive).
  259. // NOTE: should use clientLeft/clientTop, but very unreliable cross-browser.
  260. function getClientRect(el) {
  261. var offset = el.offset();
  262. var scrollbarWidths = getScrollbarWidths(el);
  263. var left = offset.left + getCssFloat(el, 'border-left-width') + scrollbarWidths.left;
  264. var top = offset.top + getCssFloat(el, 'border-top-width') + scrollbarWidths.top;
  265. return {
  266. left: left,
  267. right: left + el[0].clientWidth, // clientWidth includes padding but NOT scrollbars
  268. top: top,
  269. bottom: top + el[0].clientHeight // clientHeight includes padding but NOT scrollbars
  270. };
  271. }
  272. // Queries the area within the margin/border/padding of a jQuery element. Assumed not to have scrollbars.
  273. // Returns a rectangle with absolute coordinates: left, right (exclusive), top, bottom (exclusive).
  274. function getContentRect(el) {
  275. var offset = el.offset(); // just outside of border, margin not included
  276. var left = offset.left + getCssFloat(el, 'border-left-width') + getCssFloat(el, 'padding-left');
  277. var top = offset.top + getCssFloat(el, 'border-top-width') + getCssFloat(el, 'padding-top');
  278. return {
  279. left: left,
  280. right: left + el.width(),
  281. top: top,
  282. bottom: top + el.height()
  283. };
  284. }
  285. // Returns the computed left/right/top/bottom scrollbar widths for the given jQuery element.
  286. // NOTE: should use clientLeft/clientTop, but very unreliable cross-browser.
  287. function getScrollbarWidths(el) {
  288. var leftRightWidth = el.innerWidth() - el[0].clientWidth; // the paddings cancel out, leaving the scrollbars
  289. var widths = {
  290. left: 0,
  291. right: 0,
  292. top: 0,
  293. bottom: el.innerHeight() - el[0].clientHeight // the paddings cancel out, leaving the bottom scrollbar
  294. };
  295. if (getIsLeftRtlScrollbars() && el.css('direction') == 'rtl') { // is the scrollbar on the left side?
  296. widths.left = leftRightWidth;
  297. }
  298. else {
  299. widths.right = leftRightWidth;
  300. }
  301. return widths;
  302. }
  303. // Logic for determining if, when the element is right-to-left, the scrollbar appears on the left side
  304. var _isLeftRtlScrollbars = null;
  305. function getIsLeftRtlScrollbars() { // responsible for caching the computation
  306. if (_isLeftRtlScrollbars === null) {
  307. _isLeftRtlScrollbars = computeIsLeftRtlScrollbars();
  308. }
  309. return _isLeftRtlScrollbars;
  310. }
  311. function computeIsLeftRtlScrollbars() { // creates an offscreen test element, then removes it
  312. var el = jQuery('<div><div/></div>')
  313. .css({
  314. position: 'absolute',
  315. top: -1000,
  316. left: 0,
  317. border: 0,
  318. padding: 0,
  319. overflow: 'scroll',
  320. direction: 'rtl'
  321. })
  322. .appendTo('body');
  323. var innerEl = el.children();
  324. var res = innerEl.offset().left > el.offset().left; // is the inner div shifted to accommodate a left scrollbar?
  325. el.remove();
  326. return res;
  327. }
  328. // Retrieves a jQuery element's computed CSS value as a floating-point number.
  329. // If the queried value is non-numeric (ex: IE can return "medium" for border width), will just return zero.
  330. function getCssFloat(el, prop) {
  331. return parseFloat(el.css(prop)) || 0;
  332. }
  333. // Returns a boolean whether this was a left mouse click and no ctrl key (which means right click on Mac)
  334. function isPrimaryMouseButton(ev) {
  335. return ev.which == 1 && !ev.ctrlKey;
  336. }
  337. /* Geometry
  338. ----------------------------------------------------------------------------------------------------------------------*/
  339. FC.intersectRects = intersectRects;
  340. // Returns a new rectangle that is the intersection of the two rectangles. If they don't intersect, returns false
  341. function intersectRects(rect1, rect2) {
  342. var res = {
  343. left: Math.max(rect1.left, rect2.left),
  344. right: Math.min(rect1.right, rect2.right),
  345. top: Math.max(rect1.top, rect2.top),
  346. bottom: Math.min(rect1.bottom, rect2.bottom)
  347. };
  348. if (res.left < res.right && res.top < res.bottom) {
  349. return res;
  350. }
  351. return false;
  352. }
  353. // Returns a new point that will have been moved to reside within the given rectangle
  354. function constrainPoint(point, rect) {
  355. return {
  356. left: Math.min(Math.max(point.left, rect.left), rect.right),
  357. top: Math.min(Math.max(point.top, rect.top), rect.bottom)
  358. };
  359. }
  360. // Returns a point that is the center of the given rectangle
  361. function getRectCenter(rect) {
  362. return {
  363. left: (rect.left + rect.right) / 2,
  364. top: (rect.top + rect.bottom) / 2
  365. };
  366. }
  367. // Subtracts point2's coordinates from point1's coordinates, returning a delta
  368. function diffPoints(point1, point2) {
  369. return {
  370. left: point1.left - point2.left,
  371. top: point1.top - point2.top
  372. };
  373. }
  374. /* Object Ordering by Field
  375. ----------------------------------------------------------------------------------------------------------------------*/
  376. FC.parseFieldSpecs = parseFieldSpecs;
  377. FC.compareByFieldSpecs = compareByFieldSpecs;
  378. FC.compareByFieldSpec = compareByFieldSpec;
  379. FC.flexibleCompare = flexibleCompare;
  380. function parseFieldSpecs(input) {
  381. var specs = [];
  382. var tokens = [];
  383. var i, token;
  384. if (typeof input === 'string') {
  385. tokens = input.split(/\s*,\s*/);
  386. }
  387. else if (typeof input === 'function') {
  388. tokens = [ input ];
  389. }
  390. else if (jQuery.isArray(input)) {
  391. tokens = input;
  392. }
  393. for (i = 0; i < tokens.length; i++) {
  394. token = tokens[i];
  395. if (typeof token === 'string') {
  396. specs.push(
  397. token.charAt(0) == '-' ?
  398. { field: token.substring(1), order: -1 } :
  399. { field: token, order: 1 }
  400. );
  401. }
  402. else if (typeof token === 'function') {
  403. specs.push({ func: token });
  404. }
  405. }
  406. return specs;
  407. }
  408. function compareByFieldSpecs(obj1, obj2, fieldSpecs) {
  409. var i;
  410. var cmp;
  411. for (i = 0; i < fieldSpecs.length; i++) {
  412. cmp = compareByFieldSpec(obj1, obj2, fieldSpecs[i]);
  413. if (cmp) {
  414. return cmp;
  415. }
  416. }
  417. return 0;
  418. }
  419. function compareByFieldSpec(obj1, obj2, fieldSpec) {
  420. if (fieldSpec.func) {
  421. return fieldSpec.func(obj1, obj2);
  422. }
  423. return flexibleCompare(obj1[fieldSpec.field], obj2[fieldSpec.field]) *
  424. (fieldSpec.order || 1);
  425. }
  426. function flexibleCompare(a, b) {
  427. if (!a && !b) {
  428. return 0;
  429. }
  430. if (b == null) {
  431. return -1;
  432. }
  433. if (a == null) {
  434. return 1;
  435. }
  436. if (jQuery.type(a) === 'string' || jQuery.type(b) === 'string') {
  437. return String(a).localeCompare(String(b));
  438. }
  439. return a - b;
  440. }
  441. /* FullCalendar-specific Misc Utilities
  442. ----------------------------------------------------------------------------------------------------------------------*/
  443. // Computes the intersection of the two ranges. Returns undefined if no intersection.
  444. // Expects all dates to be normalized to the same timezone beforehand.
  445. // TODO: move to date section?
  446. function intersectRanges(subjectRange, constraintRange) {
  447. var subjectStart = subjectRange.start;
  448. var subjectEnd = subjectRange.end;
  449. var constraintStart = constraintRange.start;
  450. var constraintEnd = constraintRange.end;
  451. var segStart, segEnd;
  452. var isStart, isEnd;
  453. if (subjectEnd > constraintStart && subjectStart < constraintEnd) { // in bounds at all?
  454. if (subjectStart >= constraintStart) {
  455. segStart = subjectStart.clone();
  456. isStart = true;
  457. }
  458. else {
  459. segStart = constraintStart.clone();
  460. isStart = false;
  461. }
  462. if (subjectEnd <= constraintEnd) {
  463. segEnd = subjectEnd.clone();
  464. isEnd = true;
  465. }
  466. else {
  467. segEnd = constraintEnd.clone();
  468. isEnd = false;
  469. }
  470. return {
  471. start: segStart,
  472. end: segEnd,
  473. isStart: isStart,
  474. isEnd: isEnd
  475. };
  476. }
  477. }
  478. /* Date Utilities
  479. ----------------------------------------------------------------------------------------------------------------------*/
  480. FC.computeIntervalUnit = computeIntervalUnit;
  481. FC.divideRangeByDuration = divideRangeByDuration;
  482. FC.divideDurationByDuration = divideDurationByDuration;
  483. FC.multiplyDuration = multiplyDuration;
  484. FC.durationHasTime = durationHasTime;
  485. var dayIDs = [ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ];
  486. var intervalUnits = [ 'year', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond' ];
  487. // Diffs the two moments into a Duration where full-days are recorded first, then the remaining time.
  488. // Moments will have their timezones normalized.
  489. function diffDayTime(a, b) {
  490. return moment.duration({
  491. days: a.clone().stripTime().diff(b.clone().stripTime(), 'days'),
  492. ms: a.time() - b.time() // time-of-day from day start. disregards timezone
  493. });
  494. }
  495. // Diffs the two moments via their start-of-day (regardless of timezone). Produces whole-day durations.
  496. function diffDay(a, b) {
  497. return moment.duration({
  498. days: a.clone().stripTime().diff(b.clone().stripTime(), 'days')
  499. });
  500. }
  501. // Diffs two moments, producing a duration, made of a whole-unit-increment of the given unit. Uses rounding.
  502. function diffByUnit(a, b, unit) {
  503. return moment.duration(
  504. Math.round(a.diff(b, unit, true)), // returnFloat=true
  505. unit
  506. );
  507. }
  508. // Computes the unit name of the largest whole-unit period of time.
  509. // For example, 48 hours will be "days" whereas 49 hours will be "hours".
  510. // Accepts start/end, a range object, or an original duration object.
  511. function computeIntervalUnit(start, end) {
  512. var i, unit;
  513. var val;
  514. for (i = 0; i < intervalUnits.length; i++) {
  515. unit = intervalUnits[i];
  516. val = computeRangeAs(unit, start, end);
  517. if (val >= 1 && isInt(val)) {
  518. break;
  519. }
  520. }
  521. return unit; // will be "milliseconds" if nothing else matches
  522. }
  523. // Computes the number of units (like "hours") in the given range.
  524. // Range can be a {start,end} object, separate start/end args, or a Duration.
  525. // Results are based on Moment's .as() and .diff() methods, so results can depend on internal handling
  526. // of month-diffing logic (which tends to vary from version to version).
  527. function computeRangeAs(unit, start, end) {
  528. if (end != null) { // given start, end
  529. return end.diff(start, unit, true);
  530. }
  531. else if (moment.isDuration(start)) { // given duration
  532. return start.as(unit);
  533. }
  534. else { // given { start, end } range object
  535. return start.end.diff(start.start, unit, true);
  536. }
  537. }
  538. // Intelligently divides a range (specified by a start/end params) by a duration
  539. function divideRangeByDuration(start, end, dur) {
  540. var months;
  541. if (durationHasTime(dur)) {
  542. return (end - start) / dur;
  543. }
  544. months = dur.asMonths();
  545. if (Math.abs(months) >= 1 && isInt(months)) {
  546. return end.diff(start, 'months', true) / months;
  547. }
  548. return end.diff(start, 'days', true) / dur.asDays();
  549. }
  550. // Intelligently divides one duration by another
  551. function divideDurationByDuration(dur1, dur2) {
  552. var months1, months2;
  553. if (durationHasTime(dur1) || durationHasTime(dur2)) {
  554. return dur1 / dur2;
  555. }
  556. months1 = dur1.asMonths();
  557. months2 = dur2.asMonths();
  558. if (
  559. Math.abs(months1) >= 1 && isInt(months1) &&
  560. Math.abs(months2) >= 1 && isInt(months2)
  561. ) {
  562. return months1 / months2;
  563. }
  564. return dur1.asDays() / dur2.asDays();
  565. }
  566. // Intelligently multiplies a duration by a number
  567. function multiplyDuration(dur, n) {
  568. var months;
  569. if (durationHasTime(dur)) {
  570. return moment.duration(dur * n);
  571. }
  572. months = dur.asMonths();
  573. if (Math.abs(months) >= 1 && isInt(months)) {
  574. return moment.duration({ months: months * n });
  575. }
  576. return moment.duration({ days: dur.asDays() * n });
  577. }
  578. // Returns a boolean about whether the given duration has any time parts (hours/minutes/seconds/ms)
  579. function durationHasTime(dur) {
  580. return Boolean(dur.hours() || dur.minutes() || dur.seconds() || dur.milliseconds());
  581. }
  582. function isNativeDate(input) {
  583. return Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date;
  584. }
  585. // Returns a boolean about whether the given input is a time string, like "06:40:00" or "06:00"
  586. function isTimeString(str) {
  587. return /^\d+\:\d+(?:\:\d+\.?(?:\d{3})?)?$/.test(str);
  588. }
  589. /* Logging and Debug
  590. ----------------------------------------------------------------------------------------------------------------------*/
  591. FC.log = function() {
  592. var console = window.console;
  593. if (console && console.log) {
  594. return console.log.apply(console, arguments);
  595. }
  596. };
  597. FC.warn = function() {
  598. var console = window.console;
  599. if (console && console.warn) {
  600. return console.warn.apply(console, arguments);
  601. }
  602. else {
  603. return FC.log.apply(FC, arguments);
  604. }
  605. };
  606. /* General Utilities
  607. ----------------------------------------------------------------------------------------------------------------------*/
  608. var hasOwnPropMethod = {}.hasOwnProperty;
  609. // Merges an array of objects into a single object.
  610. // The second argument allows for an array of property names who's object values will be merged together.
  611. function mergeProps(propObjs, complexProps) {
  612. var dest = {};
  613. var i, name;
  614. var complexObjs;
  615. var j, val;
  616. var props;
  617. if (complexProps) {
  618. for (i = 0; i < complexProps.length; i++) {
  619. name = complexProps[i];
  620. complexObjs = [];
  621. // collect the trailing object values, stopping when a non-object is discovered
  622. for (j = propObjs.length - 1; j >= 0; j--) {
  623. val = propObjs[j][name];
  624. if (typeof val === 'object') {
  625. complexObjs.unshift(val);
  626. }
  627. else if (val !== undefined) {
  628. dest[name] = val; // if there were no objects, this value will be used
  629. break;
  630. }
  631. }
  632. // if the trailing values were objects, use the merged value
  633. if (complexObjs.length) {
  634. dest[name] = mergeProps(complexObjs);
  635. }
  636. }
  637. }
  638. // copy values into the destination, going from last to first
  639. for (i = propObjs.length - 1; i >= 0; i--) {
  640. props = propObjs[i];
  641. for (name in props) {
  642. if (!(name in dest)) { // if already assigned by previous props or complex props, don't reassign
  643. dest[name] = props[name];
  644. }
  645. }
  646. }
  647. return dest;
  648. }
  649. // Create an object that has the given prototype. Just like Object.create
  650. function createObject(proto) {
  651. var f = function() {};
  652. f.prototype = proto;
  653. return new f();
  654. }
  655. function copyOwnProps(src, dest) {
  656. for (var name in src) {
  657. if (hasOwnProp(src, name)) {
  658. dest[name] = src[name];
  659. }
  660. }
  661. }
  662. // Copies over certain methods with the same names as Object.prototype methods. Overcomes an IE<=8 bug:
  663. // https://developer.mozilla.org/en-US/docs/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug
  664. function copyNativeMethods(src, dest) {
  665. var names = [ 'constructor', 'toString', 'valueOf' ];
  666. var i, name;
  667. for (i = 0; i < names.length; i++) {
  668. name = names[i];
  669. if (src[name] !== Object.prototype[name]) {
  670. dest[name] = src[name];
  671. }
  672. }
  673. }
  674. function hasOwnProp(obj, name) {
  675. return hasOwnPropMethod.call(obj, name);
  676. }
  677. // Is the given value a non-object non-function value?
  678. function isAtomic(val) {
  679. return /undefined|null|boolean|number|string/.test(jQuery.type(val));
  680. }
  681. function applyAll(functions, thisObj, args) {
  682. if (jQuery.isFunction(functions)) {
  683. functions = [ functions ];
  684. }
  685. if (functions) {
  686. var i;
  687. var ret;
  688. for (i=0; i<functions.length; i++) {
  689. ret = functions[i].apply(thisObj, args) || ret;
  690. }
  691. return ret;
  692. }
  693. }
  694. function firstDefined() {
  695. for (var i=0; i<arguments.length; i++) {
  696. if (arguments[i] !== undefined) {
  697. return arguments[i];
  698. }
  699. }
  700. }
  701. function htmlEscape(s) {
  702. return (s + '').replace(/&/g, '&amp;')
  703. .replace(/</g, '&lt;')
  704. .replace(/>/g, '&gt;')
  705. .replace(/'/g, '&#039;')
  706. .replace(/"/g, '&quot;')
  707. .replace(/\n/g, '<br />');
  708. }
  709. function stripHtmlEntities(text) {
  710. return text.replace(/&.*?;/g, '');
  711. }
  712. // Given a hash of CSS properties, returns a string of CSS.
  713. // Uses property names as-is (no camel-case conversion). Will not make statements for null/undefined values.
  714. function cssToStr(cssProps) {
  715. var statements = [];
  716. jQuery.each(cssProps, function(name, val) {
  717. if (val != null) {
  718. statements.push(name + ':' + val);
  719. }
  720. });
  721. return statements.join(';');
  722. }
  723. function capitaliseFirstLetter(str) {
  724. return str.charAt(0).toUpperCase() + str.slice(1);
  725. }
  726. function compareNumbers(a, b) { // for .sort()
  727. return a - b;
  728. }
  729. function isInt(n) {
  730. return n % 1 === 0;
  731. }
  732. // Returns a method bound to the given object context.
  733. // Just like one of the jQuery.proxy signatures, but without the undesired behavior of treating the same method with
  734. // different contexts as identical when binding/unbinding events.
  735. function proxy(obj, methodName) {
  736. var method = obj[methodName];
  737. return function() {
  738. return method.apply(obj, arguments);
  739. };
  740. }
  741. // Returns a function, that, as long as it continues to be invoked, will not
  742. // be triggered. The function will be called after it stops being called for
  743. // N milliseconds.
  744. // https://github.com/jashkenas/underscore/blob/1.6.0/underscore.js#L714
  745. function debounce(func, wait) {
  746. var timeoutId;
  747. var args;
  748. var context;
  749. var timestamp; // of most recent call
  750. var later = function() {
  751. var last = +new Date() - timestamp;
  752. if (last < wait && last > 0) {
  753. timeoutId = setTimeout(later, wait - last);
  754. }
  755. else {
  756. timeoutId = null;
  757. func.apply(context, args);
  758. if (!timeoutId) {
  759. context = args = null;
  760. }
  761. }
  762. };
  763. return function() {
  764. context = this;
  765. args = arguments;
  766. timestamp = +new Date();
  767. if (!timeoutId) {
  768. timeoutId = setTimeout(later, wait);
  769. }
  770. };
  771. }
  772. ;;
  773. var ambigDateOfMonthRegex = /^\s*\d{4}-\d\d$/;
  774. var ambigTimeOrZoneRegex =
  775. /^\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+)?)?)?)?)?$/;
  776. var newMomentProto = moment.fn; // where we will attach our new methods
  777. var oldMomentProto = jQuery.extend({}, newMomentProto); // copy of original moment methods
  778. var allowValueOptimization;
  779. var setUTCValues; // function defined below
  780. var setLocalValues; // function defined below
  781. // Creating
  782. // -------------------------------------------------------------------------------------------------
  783. // Creates a new moment, similar to the vanilla moment(...) constructor, but with
  784. // extra features (ambiguous time, enhanced formatting). When given an existing moment,
  785. // it will function as a clone (and retain the zone of the moment). Anything else will
  786. // result in a moment in the local zone.
  787. FC.moment = function() {
  788. return makeMoment(arguments);
  789. };
  790. // Sames as FC.moment, but forces the resulting moment to be in the UTC timezone.
  791. FC.moment.utc = function() {
  792. var mom = makeMoment(arguments, true);
  793. // Force it into UTC because makeMoment doesn't guarantee it
  794. // (if given a pre-existing moment for example)
  795. if (mom.hasTime()) { // don't give ambiguously-timed moments a UTC zone
  796. mom.utc();
  797. }
  798. return mom;
  799. };
  800. // Same as FC.moment, but when given an ISO8601 string, the timezone offset is preserved.
  801. // ISO8601 strings with no timezone offset will become ambiguously zoned.
  802. FC.moment.parseZone = function() {
  803. return makeMoment(arguments, true, true);
  804. };
  805. // Builds an enhanced moment from args. When given an existing moment, it clones. When given a
  806. // native Date, or called with no arguments (the current time), the resulting moment will be local.
  807. // Anything else needs to be "parsed" (a string or an array), and will be affected by:
  808. // parseAsUTC - if there is no zone information, should we parse the input in UTC?
  809. // parseZone - if there is zone information, should we force the zone of the moment?
  810. function makeMoment(args, parseAsUTC, parseZone) {
  811. var input = args[0];
  812. var isSingleString = args.length == 1 && typeof input === 'string';
  813. var isAmbigTime;
  814. var isAmbigZone;
  815. var ambigMatch;
  816. var mom;
  817. if (moment.isMoment(input)) {
  818. mom = moment.apply(null, args); // clone it
  819. transferAmbigs(input, mom); // the ambig flags weren't transfered with the clone
  820. }
  821. else if (isNativeDate(input) || input === undefined) {
  822. mom = moment.apply(null, args); // will be local
  823. }
  824. else { // "parsing" is required
  825. isAmbigTime = false;
  826. isAmbigZone = false;
  827. if (isSingleString) {
  828. if (ambigDateOfMonthRegex.test(input)) {
  829. // accept strings like '2014-05', but convert to the first of the month
  830. input += '-01';
  831. args = [ input ]; // for when we pass it on to moment's constructor
  832. isAmbigTime = true;
  833. isAmbigZone = true;
  834. }
  835. else if ((ambigMatch = ambigTimeOrZoneRegex.exec(input))) {
  836. isAmbigTime = !ambigMatch[5]; // no time part?
  837. isAmbigZone = true;
  838. }
  839. }
  840. else if (jQuery.isArray(input)) {
  841. // arrays have no timezone information, so assume ambiguous zone
  842. isAmbigZone = true;
  843. }
  844. // otherwise, probably a string with a format
  845. if (parseAsUTC || isAmbigTime) {
  846. mom = moment.utc.apply(moment, args);
  847. }
  848. else {
  849. mom = moment.apply(null, args);
  850. }
  851. if (isAmbigTime) {
  852. mom._ambigTime = true;
  853. mom._ambigZone = true; // ambiguous time always means ambiguous zone
  854. }
  855. else if (parseZone) { // let's record the inputted zone somehow
  856. if (isAmbigZone) {
  857. mom._ambigZone = true;
  858. }
  859. else if (isSingleString) {
  860. if (mom.utcOffset) {
  861. mom.utcOffset(input); // if not a valid zone, will assign UTC
  862. }
  863. else {
  864. mom.zone(input); // for moment-pre-2.9
  865. }
  866. }
  867. }
  868. }
  869. mom._fullCalendar = true; // flag for extended functionality
  870. return mom;
  871. }
  872. // A clone method that works with the flags related to our enhanced functionality.
  873. // In the future, use moment.momentProperties
  874. newMomentProto.clone = function() {
  875. var mom = oldMomentProto.clone.apply(this, arguments);
  876. // these flags weren't transfered with the clone
  877. transferAmbigs(this, mom);
  878. if (this._fullCalendar) {
  879. mom._fullCalendar = true;
  880. }
  881. return mom;
  882. };
  883. // Week Number
  884. // -------------------------------------------------------------------------------------------------
  885. // Returns the week number, considering the locale's custom week number calcuation
  886. // `weeks` is an alias for `week`
  887. newMomentProto.week = newMomentProto.weeks = function(input) {
  888. var weekCalc = (this._locale || this._lang) // works pre-moment-2.8
  889. ._fullCalendar_weekCalc;
  890. if (input == null && typeof weekCalc === 'function') { // custom function only works for getter
  891. return weekCalc(this);
  892. }
  893. else if (weekCalc === 'ISO') {
  894. return oldMomentProto.isoWeek.apply(this, arguments); // ISO getter/setter
  895. }
  896. return oldMomentProto.week.apply(this, arguments); // local getter/setter
  897. };
  898. // Time-of-day
  899. // -------------------------------------------------------------------------------------------------
  900. // GETTER
  901. // Returns a Duration with the hours/minutes/seconds/ms values of the moment.
  902. // If the moment has an ambiguous time, a duration of 00:00 will be returned.
  903. //
  904. // SETTER
  905. // You can supply a Duration, a Moment, or a Duration-like argument.
  906. // When setting the time, and the moment has an ambiguous time, it then becomes unambiguous.
  907. newMomentProto.time = function(time) {
  908. // Fallback to the original method (if there is one) if this moment wasn't created via FullCalendar.
  909. // `time` is a generic enough method name where this precaution is necessary to avoid collisions w/ other plugins.
  910. if (!this._fullCalendar) {
  911. return oldMomentProto.time.apply(this, arguments);
  912. }
  913. if (time == null) { // getter
  914. return moment.duration({
  915. hours: this.hours(),
  916. minutes: this.minutes(),
  917. seconds: this.seconds(),
  918. milliseconds: this.milliseconds()
  919. });
  920. }
  921. else { // setter
  922. this._ambigTime = false; // mark that the moment now has a time
  923. if (!moment.isDuration(time) && !moment.isMoment(time)) {
  924. time = moment.duration(time);
  925. }
  926. // The day value should cause overflow (so 24 hours becomes 00:00:00 of next day).
  927. // Only for Duration times, not Moment times.
  928. var dayHours = 0;
  929. if (moment.isDuration(time)) {
  930. dayHours = Math.floor(time.asDays()) * 24;
  931. }
  932. // We need to set the individual fields.
  933. // Can't use startOf('day') then add duration. In case of DST at start of day.
  934. return this.hours(dayHours + time.hours())
  935. .minutes(time.minutes())
  936. .seconds(time.seconds())
  937. .milliseconds(time.milliseconds());
  938. }
  939. };
  940. // Converts the moment to UTC, stripping out its time-of-day and timezone offset,
  941. // but preserving its YMD. A moment with a stripped time will display no time
  942. // nor timezone offset when .format() is called.
  943. newMomentProto.stripTime = function() {
  944. var a;
  945. if (!this._ambigTime) {
  946. // get the values before any conversion happens
  947. a = this.toArray(); // array of y/m/d/h/m/s/ms
  948. // TODO: use keepLocalTime in the future
  949. this.utc(); // set the internal UTC flag (will clear the ambig flags)
  950. setUTCValues(this, a.slice(0, 3)); // set the year/month/date. time will be zero
  951. // Mark the time as ambiguous. This needs to happen after the .utc() call, which might call .utcOffset(),
  952. // which clears all ambig flags. Same with setUTCValues with moment-timezone.
  953. this._ambigTime = true;
  954. this._ambigZone = true; // if ambiguous time, also ambiguous timezone offset
  955. }
  956. return this; // for chaining
  957. };
  958. // Returns if the moment has a non-ambiguous time (boolean)
  959. newMomentProto.hasTime = function() {
  960. return !this._ambigTime;
  961. };
  962. // Timezone
  963. // -------------------------------------------------------------------------------------------------
  964. // Converts the moment to UTC, stripping out its timezone offset, but preserving its
  965. // YMD and time-of-day. A moment with a stripped timezone offset will display no
  966. // timezone offset when .format() is called.
  967. // TODO: look into Moment's keepLocalTime functionality
  968. newMomentProto.stripZone = function() {
  969. var a, wasAmbigTime;
  970. if (!this._ambigZone) {
  971. // get the values before any conversion happens
  972. a = this.toArray(); // array of y/m/d/h/m/s/ms
  973. wasAmbigTime = this._ambigTime;
  974. this.utc(); // set the internal UTC flag (might clear the ambig flags, depending on Moment internals)
  975. setUTCValues(this, a); // will set the year/month/date/hours/minutes/seconds/ms
  976. // the above call to .utc()/.utcOffset() unfortunately might clear the ambig flags, so restore
  977. this._ambigTime = wasAmbigTime || false;
  978. // Mark the zone as ambiguous. This needs to happen after the .utc() call, which might call .utcOffset(),
  979. // which clears the ambig flags. Same with setUTCValues with moment-timezone.
  980. this._ambigZone = true;
  981. }
  982. return this; // for chaining
  983. };
  984. // Returns of the moment has a non-ambiguous timezone offset (boolean)
  985. newMomentProto.hasZone = function() {
  986. return !this._ambigZone;
  987. };
  988. // this method implicitly marks a zone
  989. newMomentProto.local = function() {
  990. var a = this.toArray(); // year,month,date,hours,minutes,seconds,ms as an array
  991. var wasAmbigZone = this._ambigZone;
  992. oldMomentProto.local.apply(this, arguments);
  993. // ensure non-ambiguous
  994. // this probably already happened via local() -> utcOffset(), but don't rely on Moment's internals
  995. this._ambigTime = false;
  996. this._ambigZone = false;
  997. if (wasAmbigZone) {
  998. // If the moment was ambiguously zoned, the date fields were stored as UTC.
  999. // We want to preserve these, but in local time.
  1000. // TODO: look into Moment's keepLocalTime functionality
  1001. setLocalValues(this, a);
  1002. }
  1003. return this; // for chaining
  1004. };
  1005. // implicitly marks a zone
  1006. newMomentProto.utc = function() {
  1007. oldMomentProto.utc.apply(this, arguments);
  1008. // ensure non-ambiguous
  1009. // this probably already happened via utc() -> utcOffset(), but don't rely on Moment's internals
  1010. this._ambigTime = false;
  1011. this._ambigZone = false;
  1012. return this;
  1013. };
  1014. // methods for arbitrarily manipulating timezone offset.
  1015. // should clear time/zone ambiguity when called.
  1016. jQuery.each([
  1017. 'zone', // only in moment-pre-2.9. deprecated afterwards
  1018. 'utcOffset'
  1019. ], function(i, name) {
  1020. if (oldMomentProto[name]) { // original method exists?
  1021. // this method implicitly marks a zone (will probably get called upon .utc() and .local())
  1022. newMomentProto[name] = function(tzo) {
  1023. if (tzo != null) { // setter
  1024. // these assignments needs to happen before the original zone method is called.
  1025. // I forget why, something to do with a browser crash.
  1026. this._ambigTime = false;
  1027. this._ambigZone = false;
  1028. }
  1029. return oldMomentProto[name].apply(this, arguments);
  1030. };
  1031. }
  1032. });
  1033. // Formatting
  1034. // -------------------------------------------------------------------------------------------------
  1035. newMomentProto.format = function() {
  1036. if (this._fullCalendar && arguments[0]) { // an enhanced moment? and a format string provided?
  1037. return formatDate(this, arguments[0]); // our extended formatting
  1038. }
  1039. if (this._ambigTime) {
  1040. return oldMomentFormat(this, 'YYYY-MM-DD');
  1041. }
  1042. if (this._ambigZone) {
  1043. return oldMomentFormat(this, 'YYYY-MM-DD[T]HH:mm:ss');
  1044. }
  1045. return oldMomentProto.format.apply(this, arguments);
  1046. };
  1047. newMomentProto.toISOString = function() {
  1048. if (this._ambigTime) {
  1049. return oldMomentFormat(this, 'YYYY-MM-DD');
  1050. }
  1051. if (this._ambigZone) {
  1052. return oldMomentFormat(this, 'YYYY-MM-DD[T]HH:mm:ss');
  1053. }
  1054. return oldMomentProto.toISOString.apply(this, arguments);
  1055. };
  1056. // Querying
  1057. // -------------------------------------------------------------------------------------------------
  1058. // Is the moment within the specified range? `end` is exclusive.
  1059. // FYI, this method is not a standard Moment method, so always do our enhanced logic.
  1060. newMomentProto.isWithin = function(start, end) {
  1061. var a = commonlyAmbiguate([ this, start, end ]);
  1062. return a[0] >= a[1] && a[0] < a[2];
  1063. };
  1064. // When isSame is called with units, timezone ambiguity is normalized before the comparison happens.
  1065. // If no units specified, the two moments must be identically the same, with matching ambig flags.
  1066. newMomentProto.isSame = function(input, units) {
  1067. var a;
  1068. // only do custom logic if this is an enhanced moment
  1069. if (!this._fullCalendar) {
  1070. return oldMomentProto.isSame.apply(this, arguments);
  1071. }
  1072. if (units) {
  1073. a = commonlyAmbiguate([ this, input ], true); // normalize timezones but don't erase times
  1074. return oldMomentProto.isSame.call(a[0], a[1], units);
  1075. }
  1076. else {
  1077. input = FC.moment.parseZone(input); // normalize input
  1078. return oldMomentProto.isSame.call(this, input) &&
  1079. Boolean(this._ambigTime) === Boolean(input._ambigTime) &&
  1080. Boolean(this._ambigZone) === Boolean(input._ambigZone);
  1081. }
  1082. };
  1083. // Make these query methods work with ambiguous moments
  1084. jQuery.each([
  1085. 'isBefore',
  1086. 'isAfter'
  1087. ], function(i, methodName) {
  1088. newMomentProto[methodName] = function(input, units) {
  1089. var a;
  1090. // only do custom logic if this is an enhanced moment
  1091. if (!this._fullCalendar) {
  1092. return oldMomentProto[methodName].apply(this, arguments);
  1093. }
  1094. a = commonlyAmbiguate([ this, input ]);
  1095. return oldMomentProto[methodName].call(a[0], a[1], units);
  1096. };
  1097. });
  1098. // Misc Internals
  1099. // -------------------------------------------------------------------------------------------------
  1100. // given an array of moment-like inputs, return a parallel array w/ moments similarly ambiguated.
  1101. // for example, of one moment has ambig time, but not others, all moments will have their time stripped.
  1102. // set `preserveTime` to `true` to keep times, but only normalize zone ambiguity.
  1103. // returns the original moments if no modifications are necessary.
  1104. function commonlyAmbiguate(inputs, preserveTime) {
  1105. var anyAmbigTime = false;
  1106. var anyAmbigZone = false;
  1107. var len = inputs.length;
  1108. var moms = [];
  1109. var i, mom;
  1110. // parse inputs into real moments and query their ambig flags
  1111. for (i = 0; i < len; i++) {
  1112. mom = inputs[i];
  1113. if (!moment.isMoment(mom)) {
  1114. mom = FC.moment.parseZone(mom);
  1115. }
  1116. anyAmbigTime = anyAmbigTime || mom._ambigTime;
  1117. anyAmbigZone = anyAmbigZone || mom._ambigZone;
  1118. moms.push(mom);
  1119. }
  1120. // strip each moment down to lowest common ambiguity
  1121. // use clones to avoid modifying the original moments
  1122. for (i = 0; i < len; i++) {
  1123. mom = moms[i];
  1124. if (!preserveTime && anyAmbigTime && !mom._ambigTime) {
  1125. moms[i] = mom.clone().stripTime();
  1126. }
  1127. else if (anyAmbigZone && !mom._ambigZone) {
  1128. moms[i] = mom.clone().stripZone();
  1129. }
  1130. }
  1131. return moms;
  1132. }
  1133. // Transfers all the flags related to ambiguous time/zone from the `src` moment to the `dest` moment
  1134. // TODO: look into moment.momentProperties for this.
  1135. function transferAmbigs(src, dest) {
  1136. if (src._ambigTime) {
  1137. dest._ambigTime = true;
  1138. }
  1139. else if (dest._ambigTime) {
  1140. dest._ambigTime = false;
  1141. }
  1142. if (src._ambigZone) {
  1143. dest._ambigZone = true;
  1144. }
  1145. else if (dest._ambigZone) {
  1146. dest._ambigZone = false;
  1147. }
  1148. }
  1149. // Sets the year/month/date/etc values of the moment from the given array.
  1150. // Inefficient because it calls each individual setter.
  1151. function setMomentValues(mom, a) {
  1152. mom.year(a[0] || 0)
  1153. .month(a[1] || 0)
  1154. .date(a[2] || 0)
  1155. .hours(a[3] || 0)
  1156. .minutes(a[4] || 0)
  1157. .seconds(a[5] || 0)
  1158. .milliseconds(a[6] || 0);
  1159. }
  1160. // Can we set the moment's internal date directly?
  1161. allowValueOptimization = '_d' in moment() && 'updateOffset' in moment;
  1162. // Utility function. Accepts a moment and an array of the UTC year/month/date/etc values to set.
  1163. // Assumes the given moment is already in UTC mode.
  1164. setUTCValues = allowValueOptimization ? function(mom, a) {
  1165. // simlate what moment's accessors do
  1166. mom._d.setTime(Date.UTC.apply(Date, a));
  1167. moment.updateOffset(mom, false); // keepTime=false
  1168. } : setMomentValues;
  1169. // Utility function. Accepts a moment and an array of the local year/month/date/etc values to set.
  1170. // Assumes the given moment is already in local mode.
  1171. setLocalValues = allowValueOptimization ? function(mom, a) {
  1172. // simlate what moment's accessors do
  1173. mom._d.setTime(+new Date( // FYI, there is now way to apply an array of args to a constructor
  1174. a[0] || 0,
  1175. a[1] || 0,
  1176. a[2] || 0,
  1177. a[3] || 0,
  1178. a[4] || 0,
  1179. a[5] || 0,
  1180. a[6] || 0
  1181. ));
  1182. moment.updateOffset(mom, false); // keepTime=false
  1183. } : setMomentValues;
  1184. ;;
  1185. // Single Date Formatting
  1186. // -------------------------------------------------------------------------------------------------
  1187. // call this if you want Moment's original format method to be used
  1188. function oldMomentFormat(mom, formatStr) {
  1189. return oldMomentProto.format.call(mom, formatStr); // oldMomentProto defined in moment-ext.js
  1190. }
  1191. // Formats `date` with a Moment formatting string, but allow our non-zero areas and
  1192. // additional token.
  1193. function formatDate(date, formatStr) {
  1194. return formatDateWithChunks(date, getFormatStringChunks(formatStr));
  1195. }
  1196. function formatDateWithChunks(date, chunks) {
  1197. var s = '';
  1198. var i;
  1199. for (i=0; i<chunks.length; i++) {
  1200. s += formatDateWithChunk(date, chunks[i]);
  1201. }
  1202. return s;
  1203. }
  1204. // addition formatting tokens we want recognized
  1205. var tokenOverrides = {
  1206. t: function(date) { // "a" or "p"
  1207. return oldMomentFormat(date, 'a').charAt(0);
  1208. },
  1209. T: function(date) { // "A" or "P"
  1210. return oldMomentFormat(date, 'A').charAt(0);
  1211. }
  1212. };
  1213. function formatDateWithChunk(date, chunk) {
  1214. var token;
  1215. var maybeStr;
  1216. if (typeof chunk === 'string') { // a literal string
  1217. return chunk;
  1218. }
  1219. else if ((token = chunk.token)) { // a token, like "YYYY"
  1220. if (tokenOverrides[token]) {
  1221. return tokenOverrides[token](date); // use our custom token
  1222. }
  1223. return oldMomentFormat(date, token);
  1224. }
  1225. else if (chunk.maybe) { // a grouping of other chunks that must be non-zero
  1226. maybeStr = formatDateWithChunks(date, chunk.maybe);
  1227. if (maybeStr.match(/[1-9]/)) {
  1228. return maybeStr;
  1229. }
  1230. }
  1231. return '';
  1232. }
  1233. // Date Range Formatting
  1234. // -------------------------------------------------------------------------------------------------
  1235. // TODO: make it work with timezone offset
  1236. // Using a formatting string meant for a single date, generate a range string, like
  1237. // "Sep 2 - 9 2013", that intelligently inserts a separator where the dates differ.
  1238. // If the dates are the same as far as the format string is concerned, just return a single
  1239. // rendering of one date, without any separator.
  1240. function formatRange(date1, date2, formatStr, separator, isRTL) {
  1241. var localeData;
  1242. date1 = FC.moment.parseZone(date1);
  1243. date2 = FC.moment.parseZone(date2);
  1244. localeData = (date1.localeData || date1.lang).call(date1); // works with moment-pre-2.8
  1245. // Expand localized format strings, like "LL" -> "MMMM D YYYY"
  1246. formatStr = localeData.longDateFormat(formatStr) || formatStr;
  1247. // BTW, this is not important for `formatDate` because it is impossible to put custom tokens
  1248. // or non-zero areas in Moment's localized format strings.
  1249. separator = separator || ' - ';
  1250. return formatRangeWithChunks(
  1251. date1,
  1252. date2,
  1253. getFormatStringChunks(formatStr),
  1254. separator,
  1255. isRTL
  1256. );
  1257. }
  1258. FC.formatRange = formatRange; // expose
  1259. function formatRangeWithChunks(date1, date2, chunks, separator, isRTL) {
  1260. var unzonedDate1 = date1.clone().stripZone(); // for formatSimilarChunk
  1261. var unzonedDate2 = date2.clone().stripZone(); // "
  1262. var chunkStr; // the rendering of the chunk
  1263. var leftI;
  1264. var leftStr = '';
  1265. var rightI;
  1266. var rightStr = '';
  1267. var middleI;
  1268. var middleStr1 = '';
  1269. var middleStr2 = '';
  1270. var middleStr = '';
  1271. // Start at the leftmost side of the formatting string and continue until you hit a token
  1272. // that is not the same between dates.
  1273. for (leftI=0; leftI<chunks.length; leftI++) {
  1274. chunkStr = formatSimilarChunk(date1, date2, unzonedDate1, unzonedDate2, chunks[leftI]);
  1275. if (chunkStr === false) {
  1276. break;
  1277. }
  1278. leftStr += chunkStr;
  1279. }
  1280. // Similarly, start at the rightmost side of the formatting string and move left
  1281. for (rightI=chunks.length-1; rightI>leftI; rightI--) {
  1282. chunkStr = formatSimilarChunk(date1, date2, unzonedDate1, unzonedDate2, chunks[rightI]);
  1283. if (chunkStr === false) {
  1284. break;
  1285. }
  1286. rightStr = chunkStr + rightStr;
  1287. }
  1288. // The area in the middle is different for both of the dates.
  1289. // Collect them distinctly so we can jam them together later.
  1290. for (middleI=leftI; middleI<=rightI; middleI++) {
  1291. middleStr1 += formatDateWithChunk(date1, chunks[middleI]);
  1292. middleStr2 += formatDateWithChunk(date2, chunks[middleI]);
  1293. }
  1294. if (middleStr1 || middleStr2) {
  1295. if (isRTL) {
  1296. middleStr = middleStr2 + separator + middleStr1;
  1297. }
  1298. else {
  1299. middleStr = middleStr1 + separator + middleStr2;
  1300. }
  1301. }
  1302. return leftStr + middleStr + rightStr;
  1303. }
  1304. var similarUnitMap = {
  1305. Y: 'year',
  1306. M: 'month',
  1307. D: 'day', // day of month
  1308. d: 'day', // day of week
  1309. // prevents a separator between anything time-related...
  1310. A: 'second', // AM/PM
  1311. a: 'second', // am/pm
  1312. T: 'second', // A/P
  1313. t: 'second', // a/p
  1314. H: 'second', // hour (24)
  1315. h: 'second', // hour (12)
  1316. m: 'second', // minute
  1317. s: 'second' // second
  1318. };
  1319. // TODO: week maybe?
  1320. // Given a formatting chunk, and given that both dates are similar in the regard the
  1321. // formatting chunk is concerned, format date1 against `chunk`. Otherwise, return `false`.
  1322. function formatSimilarChunk(date1, date2, unzonedDate1, unzonedDate2, chunk) {
  1323. var token;
  1324. var unit;
  1325. if (typeof chunk === 'string') { // a literal string
  1326. return chunk;
  1327. }
  1328. else if ((token = chunk.token)) {
  1329. unit = similarUnitMap[token.charAt(0)];
  1330. // are the dates the same for this unit of measurement?
  1331. // use the unzoned dates for this calculation because unreliable when near DST (bug #2396)
  1332. if (unit && unzonedDate1.isSame(unzonedDate2, unit)) {
  1333. return oldMomentFormat(date1, token); // would be the same if we used `date2`
  1334. // BTW, don't support custom tokens
  1335. }
  1336. }
  1337. return false; // the chunk is NOT the same for the two dates
  1338. // BTW, don't support splitting on non-zero areas
  1339. }
  1340. // Chunking Utils
  1341. // -------------------------------------------------------------------------------------------------
  1342. var formatStringChunkCache = {};
  1343. function getFormatStringChunks(formatStr) {
  1344. if (formatStr in formatStringChunkCache) {
  1345. return formatStringChunkCache[formatStr];
  1346. }
  1347. return (formatStringChunkCache[formatStr] = chunkFormatString(formatStr));
  1348. }
  1349. // Break the formatting string into an array of chunks
  1350. function chunkFormatString(formatStr) {
  1351. var chunks = [];
  1352. var chunker = /\[([^\]]*)\]|\(([^\)]*)\)|(LTS|LT|(\w)\4*o?)|([^\w\[\(]+)/g; // TODO: more descrimination
  1353. var match;
  1354. while ((match = chunker.exec(formatStr))) {
  1355. if (match[1]) { // a literal string inside [ ... ]
  1356. chunks.push(match[1]);
  1357. }
  1358. else if (match[2]) { // non-zero formatting inside ( ... )
  1359. chunks.push({ maybe: chunkFormatString(match[2]) });
  1360. }
  1361. else if (match[3]) { // a formatting token
  1362. chunks.push({ token: match[3] });
  1363. }
  1364. else if (match[5]) { // an unenclosed literal string
  1365. chunks.push(match[5]);
  1366. }
  1367. }
  1368. return chunks;
  1369. }
  1370. ;;
  1371. FC.Class = Class; // export
  1372. // Class that all other classes will inherit from
  1373. function Class() { }
  1374. // Called on a class to create a subclass.
  1375. // Last argument contains instance methods. Any argument before the last are considered mixins.
  1376. Class.extend = function() {
  1377. var len = arguments.length;
  1378. var i;
  1379. var members;
  1380. for (i = 0; i < len; i++) {
  1381. members = arguments[i];
  1382. if (i < len - 1) { // not the last argument?
  1383. mixIntoClass(this, members);
  1384. }
  1385. }
  1386. return extendClass(this, members || {}); // members will be undefined if no arguments
  1387. };
  1388. // Adds new member variables/methods to the class's prototype.
  1389. // Can be called with another class, or a plain object hash containing new members.
  1390. Class.mixin = function(members) {
  1391. mixIntoClass(this, members);
  1392. };
  1393. function extendClass(superClass, members) {
  1394. var subClass;
  1395. // ensure a constructor for the subclass, forwarding all arguments to the super-constructor if it doesn't exist
  1396. if (hasOwnProp(members, 'constructor')) {
  1397. subClass = members.constructor;
  1398. }
  1399. if (typeof subClass !== 'function') {
  1400. subClass = members.constructor = function() {
  1401. superClass.apply(this, arguments);
  1402. };
  1403. }
  1404. // build the base prototype for the subclass, which is an new object chained to the superclass's prototype
  1405. subClass.prototype = createObject(superClass.prototype);
  1406. // copy each member variable/method onto the the subclass's prototype
  1407. copyOwnProps(members, subClass.prototype);
  1408. copyNativeMethods(members, subClass.prototype); // hack for IE8
  1409. // copy over all class variables/methods to the subclass, such as `extend` and `mixin`
  1410. copyOwnProps(superClass, subClass);
  1411. return subClass;
  1412. }
  1413. function mixIntoClass(theClass, members) {
  1414. copyOwnProps(members.prototype || members, theClass.prototype); // TODO: copyNativeMethods?
  1415. }
  1416. ;;
  1417. var Emitter = FC.Emitter = Class.extend({
  1418. callbackHash: null,
  1419. on: function(name, callback) {
  1420. this.getCallbacks(name).add(callback);
  1421. return this; // for chaining
  1422. },
  1423. off: function(name, callback) {
  1424. this.getCallbacks(name).remove(callback);
  1425. return this; // for chaining
  1426. },
  1427. trigger: function(name) { // args...
  1428. var args = Array.prototype.slice.call(arguments, 1);
  1429. this.triggerWith(name, this, args);
  1430. return this; // for chaining
  1431. },
  1432. triggerWith: function(name, context, args) {
  1433. var callbacks = this.getCallbacks(name);
  1434. callbacks.fireWith(context, args);
  1435. return this; // for chaining
  1436. },
  1437. getCallbacks: function(name) {
  1438. var callbacks;
  1439. if (!this.callbackHash) {
  1440. this.callbackHash = {};
  1441. }
  1442. callbacks = this.callbackHash[name];
  1443. if (!callbacks) {
  1444. callbacks = this.callbackHash[name] = jQuery.Callbacks();
  1445. }
  1446. return callbacks;
  1447. }
  1448. });
  1449. ;;
  1450. /* A rectangular panel that is absolutely positioned over other content
  1451. ------------------------------------------------------------------------------------------------------------------------
  1452. Options:
  1453. - className (string)
  1454. - content (HTML string or jQuery element set)
  1455. - parentEl
  1456. - top
  1457. - left
  1458. - right (the x coord of where the right edge should be. not a "CSS" right)
  1459. - autoHide (boolean)
  1460. - show (callback)
  1461. - hide (callback)
  1462. */
  1463. var Popover = Class.extend({
  1464. isHidden: true,
  1465. options: null,
  1466. el: null, // the container element for the popover. generated by this object
  1467. documentMousedownProxy: null, // document mousedown handler bound to `this`
  1468. margin: 10, // the space required between the popover and the edges of the scroll container
  1469. constructor: function(options) {
  1470. this.options = options || {};
  1471. },
  1472. // Shows the popover on the specified position. Renders it if not already
  1473. show: function() {
  1474. if (this.isHidden) {
  1475. if (!this.el) {
  1476. this.render();
  1477. }
  1478. this.el.show();
  1479. this.position();
  1480. this.isHidden = false;
  1481. this.trigger('show');
  1482. }
  1483. },
  1484. // Hides the popover, through CSS, but does not remove it from the DOM
  1485. hide: function() {
  1486. if (!this.isHidden) {
  1487. this.el.hide();
  1488. this.isHidden = true;
  1489. this.trigger('hide');
  1490. }
  1491. },
  1492. // Creates `this.el` and renders content inside of it
  1493. render: function() {
  1494. var _this = this;
  1495. var options = this.options;
  1496. this.el = jQuery('<div class="fc-popover"/>')
  1497. .addClass(options.className || '')
  1498. .css({
  1499. // position initially to the top left to avoid creating scrollbars
  1500. top: 0,
  1501. left: 0
  1502. })
  1503. .append(options.content)
  1504. .appendTo(options.parentEl);
  1505. // when a click happens on anything inside with a 'fc-close' className, hide the popover
  1506. this.el.on('click', '.fc-close', function() {
  1507. _this.hide();
  1508. });
  1509. if (options.autoHide) {
  1510. jQuery(document).on('mousedown', this.documentMousedownProxy = proxy(this, 'documentMousedown'));
  1511. }
  1512. },
  1513. // Triggered when the user clicks *anywhere* in the document, for the autoHide feature
  1514. documentMousedown: function(ev) {
  1515. // only hide the popover if the click happened outside the popover
  1516. if (this.el && !jQuery(ev.target).closest(this.el).length) {
  1517. this.hide();
  1518. }
  1519. },
  1520. // Hides and unregisters any handlers
  1521. removeElement: function() {
  1522. this.hide();
  1523. if (this.el) {
  1524. this.el.remove();
  1525. this.el = null;
  1526. }
  1527. jQuery(document).off('mousedown', this.documentMousedownProxy);
  1528. },
  1529. // Positions the popover optimally, using the top/left/right options
  1530. position: function() {
  1531. var options = this.options;
  1532. var origin = this.el.offsetParent().offset();
  1533. var width = this.el.outerWidth();
  1534. var height = this.el.outerHeight();
  1535. var windowEl = jQuery(window);
  1536. var viewportEl = getScrollParent(this.el);
  1537. var viewportTop;
  1538. var viewportLeft;
  1539. var viewportOffset;
  1540. var top; // the "position" (not "offset") values for the popover
  1541. var left; //
  1542. // compute top and left
  1543. top = options.top || 0;
  1544. if (options.left !== undefined) {
  1545. left = options.left;
  1546. }
  1547. else if (options.right !== undefined) {
  1548. left = options.right - width; // derive the left value from the right value
  1549. }
  1550. else {
  1551. left = 0;
  1552. }
  1553. if (viewportEl.is(window) || viewportEl.is(document)) { // normalize getScrollParent's result
  1554. viewportEl = windowEl;
  1555. viewportTop = 0; // the window is always at the top left
  1556. viewportLeft = 0; // (and .offset() won't work if called here)
  1557. }
  1558. else {
  1559. viewportOffset = viewportEl.offset();
  1560. viewportTop = viewportOffset.top;
  1561. viewportLeft = viewportOffset.left;
  1562. }
  1563. // if the window is scrolled, it causes the visible area to be further down
  1564. viewportTop += windowEl.scrollTop();
  1565. viewportLeft += windowEl.scrollLeft();
  1566. // constrain to the view port. if constrained by two edges, give precedence to top/left
  1567. if (options.viewportConstrain !== false) {
  1568. top = Math.min(top, viewportTop + viewportEl.outerHeight() - height - this.margin);
  1569. top = Math.max(top, viewportTop + this.margin);
  1570. left = Math.min(left, viewportLeft + viewportEl.outerWidth() - width - this.margin);
  1571. left = Math.max(left, viewportLeft + this.margin);
  1572. }
  1573. this.el.css({
  1574. top: top - origin.top,
  1575. left: left - origin.left
  1576. });
  1577. },
  1578. // Triggers a callback. Calls a function in the option hash of the same name.
  1579. // Arguments beyond the first `name` are forwarded on.
  1580. // TODO: better code reuse for this. Repeat code
  1581. trigger: function(name) {
  1582. if (this.options[name]) {
  1583. this.options[name].apply(this, Array.prototype.slice.call(arguments, 1));
  1584. }
  1585. }
  1586. });
  1587. ;;
  1588. /*
  1589. A cache for the left/right/top/bottom/width/height values for one or more elements.
  1590. Works with both offset (from topleft document) and position (from offsetParent).
  1591. options:
  1592. - els
  1593. - isHorizontal
  1594. - isVertical
  1595. */
  1596. var CoordCache = FC.CoordCache = Class.extend({
  1597. els: null, // jQuery set (assumed to be siblings)
  1598. forcedOffsetParentEl: null, // options can override the natural offsetParent
  1599. origin: null, // {left,top} position of offsetParent of els
  1600. boundingRect: null, // constrain cordinates to this rectangle. {left,right,top,bottom} or null
  1601. isHorizontal: false, // whether to query for left/right/width
  1602. isVertical: false, // whether to query for top/bottom/height
  1603. // arrays of coordinates (offsets from topleft of document)
  1604. lefts: null,
  1605. rights: null,
  1606. tops: null,
  1607. bottoms: null,
  1608. constructor: function(options) {
  1609. this.els = jQuery(options.els);
  1610. this.isHorizontal = options.isHorizontal;
  1611. this.isVertical = options.isVertical;
  1612. this.forcedOffsetParentEl = options.offsetParent ? jQuery(options.offsetParent) : null;
  1613. },
  1614. // Queries the els for coordinates and stores them.
  1615. // Call this method before using and of the get* methods below.
  1616. build: function() {
  1617. var offsetParentEl = this.forcedOffsetParentEl || this.els.eq(0).offsetParent();
  1618. this.origin = offsetParentEl.offset();
  1619. this.boundingRect = this.queryBoundingRect();
  1620. if (this.isHorizontal) {
  1621. this.buildElHorizontals();
  1622. }
  1623. if (this.isVertical) {
  1624. this.buildElVerticals();
  1625. }
  1626. },
  1627. // Destroys all internal data about coordinates, freeing memory
  1628. clear: function() {
  1629. this.origin = null;
  1630. this.boundingRect = null;
  1631. this.lefts = null;
  1632. this.rights = null;
  1633. this.tops = null;
  1634. this.bottoms = null;
  1635. },
  1636. // When called, if coord caches aren't built, builds them
  1637. ensureBuilt: function() {
  1638. if (!this.origin) {
  1639. this.build();
  1640. }
  1641. },
  1642. // Compute and return what the elements' bounding rectangle is, from the user's perspective.
  1643. // Right now, only returns a rectangle if constrained by an overflow:scroll element.
  1644. queryBoundingRect: function() {
  1645. var scrollParentEl = getScrollParent(this.els.eq(0));
  1646. if (!scrollParentEl.is(document)) {
  1647. return getClientRect(scrollParentEl);
  1648. }
  1649. },
  1650. // Populates the left/right internal coordinate arrays
  1651. buildElHorizontals: function() {
  1652. var lefts = [];
  1653. var rights = [];
  1654. this.els.each(function(i, node) {
  1655. var el = jQuery(node);
  1656. var left = el.offset().left;
  1657. var width = el.outerWidth();
  1658. lefts.push(left);
  1659. rights.push(left + width);
  1660. });
  1661. this.lefts = lefts;
  1662. this.rights = rights;
  1663. },
  1664. // Populates the top/bottom internal coordinate arrays
  1665. buildElVerticals: function() {
  1666. var tops = [];
  1667. var bottoms = [];
  1668. this.els.each(function(i, node) {
  1669. var el = jQuery(node);
  1670. var top = el.offset().top;
  1671. var height = el.outerHeight();
  1672. tops.push(top);
  1673. bottoms.push(top + height);
  1674. });
  1675. this.tops = tops;
  1676. this.bottoms = bottoms;
  1677. },
  1678. // Given a left offset (from document left), returns the index of the el that it horizontally intersects.
  1679. // If no intersection is made, or outside of the boundingRect, returns undefined.
  1680. getHorizontalIndex: function(leftOffset) {
  1681. this.ensureBuilt();
  1682. var boundingRect = this.boundingRect;
  1683. var lefts = this.lefts;
  1684. var rights = this.rights;
  1685. var len = lefts.length;
  1686. var i;
  1687. if (!boundingRect || (leftOffset >= boundingRect.left && leftOffset < boundingRect.right)) {
  1688. for (i = 0; i < len; i++) {
  1689. if (leftOffset >= lefts[i] && leftOffset < rights[i]) {
  1690. return i;
  1691. }
  1692. }
  1693. }
  1694. },
  1695. // Given a top offset (from document top), returns the index of the el that it vertically intersects.
  1696. // If no intersection is made, or outside of the boundingRect, returns undefined.
  1697. getVerticalIndex: function(topOffset) {
  1698. this.ensureBuilt();
  1699. var boundingRect = this.boundingRect;
  1700. var tops = this.tops;
  1701. var bottoms = this.bottoms;
  1702. var len = tops.length;
  1703. var i;
  1704. if (!boundingRect || (topOffset >= boundingRect.top && topOffset < boundingRect.bottom)) {
  1705. for (i = 0; i < len; i++) {
  1706. if (topOffset >= tops[i] && topOffset < bottoms[i]) {
  1707. return i;
  1708. }
  1709. }
  1710. }
  1711. },
  1712. // Gets the left offset (from document left) of the element at the given index
  1713. getLeftOffset: function(leftIndex) {
  1714. this.ensureBuilt();
  1715. return this.lefts[leftIndex];
  1716. },
  1717. // Gets the left position (from offsetParent left) of the element at the given index
  1718. getLeftPosition: function(leftIndex) {
  1719. this.ensureBuilt();
  1720. return this.lefts[leftIndex] - this.origin.left;
  1721. },
  1722. // Gets the right offset (from document left) of the element at the given index.
  1723. // This value is NOT relative to the document's right edge, like the CSS concept of "right" would be.
  1724. getRightOffset: function(leftIndex) {
  1725. this.ensureBuilt();
  1726. return this.rights[leftIndex];
  1727. },
  1728. // Gets the right position (from offsetParent left) of the element at the given index.
  1729. // This value is NOT relative to the offsetParent's right edge, like the CSS concept of "right" would be.
  1730. getRightPosition: function(leftIndex) {
  1731. this.ensureBuilt();
  1732. return this.rights[leftIndex] - this.origin.left;
  1733. },
  1734. // Gets the width of the element at the given index
  1735. getWidth: function(leftIndex) {
  1736. this.ensureBuilt();
  1737. return this.rights[leftIndex] - this.lefts[leftIndex];
  1738. },
  1739. // Gets the top offset (from document top) of the element at the given index
  1740. getTopOffset: function(topIndex) {
  1741. this.ensureBuilt();
  1742. return this.tops[topIndex];
  1743. },
  1744. // Gets the top position (from offsetParent top) of the element at the given position
  1745. getTopPosition: function(topIndex) {
  1746. this.ensureBuilt();
  1747. return this.tops[topIndex] - this.origin.top;
  1748. },
  1749. // Gets the bottom offset (from the document top) of the element at the given index.
  1750. // This value is NOT relative to the offsetParent's bottom edge, like the CSS concept of "bottom" would be.
  1751. getBottomOffset: function(topIndex) {
  1752. this.ensureBuilt();
  1753. return this.bottoms[topIndex];
  1754. },
  1755. // Gets the bottom position (from the offsetParent top) of the element at the given index.
  1756. // This value is NOT relative to the offsetParent's bottom edge, like the CSS concept of "bottom" would be.
  1757. getBottomPosition: function(topIndex) {
  1758. this.ensureBuilt();
  1759. return this.bottoms[topIndex] - this.origin.top;
  1760. },
  1761. // Gets the height of the element at the given index
  1762. getHeight: function(topIndex) {
  1763. this.ensureBuilt();
  1764. return this.bottoms[topIndex] - this.tops[topIndex];
  1765. }
  1766. });
  1767. ;;
  1768. /* Tracks a drag's mouse movement, firing various handlers
  1769. ----------------------------------------------------------------------------------------------------------------------*/
  1770. // TODO: use Emitter
  1771. var DragListener = FC.DragListener = Class.extend({
  1772. options: null,
  1773. isListening: false,
  1774. isDragging: false,
  1775. // coordinates of the initial mousedown
  1776. originX: null,
  1777. originY: null,
  1778. // handler attached to the document, bound to the DragListener's `this`
  1779. mousemoveProxy: null,
  1780. mouseupProxy: null,
  1781. // for IE8 bug-fighting behavior, for now
  1782. subjectEl: null, // the element being draged. optional
  1783. subjectHref: null,
  1784. scrollEl: null,
  1785. scrollBounds: null, // { top, bottom, left, right }
  1786. scrollTopVel: null, // pixels per second
  1787. scrollLeftVel: null, // pixels per second
  1788. scrollIntervalId: null, // ID of setTimeout for scrolling animation loop
  1789. scrollHandlerProxy: null, // this-scoped function for handling when scrollEl is scrolled
  1790. scrollSensitivity: 30, // pixels from edge for scrolling to start
  1791. scrollSpeed: 200, // pixels per second, at maximum speed
  1792. scrollIntervalMs: 50, // millisecond wait between scroll increment
  1793. constructor: function(options) {
  1794. options = options || {};
  1795. this.options = options;
  1796. this.subjectEl = options.subjectEl;
  1797. },
  1798. // Call this when the user does a mousedown. Will probably lead to startListening
  1799. mousedown: function(ev) {
  1800. if (isPrimaryMouseButton(ev)) {
  1801. ev.preventDefault(); // prevents native selection in most browsers
  1802. this.startListening(ev);
  1803. // start the drag immediately if there is no minimum distance for a drag start
  1804. if (!this.options.distance) {
  1805. this.startDrag(ev);
  1806. }
  1807. }
  1808. },
  1809. // Call this to start tracking mouse movements
  1810. startListening: function(ev) {
  1811. var scrollParent;
  1812. if (!this.isListening) {
  1813. // grab scroll container and attach handler
  1814. if (ev && this.options.scroll) {
  1815. scrollParent = getScrollParent(jQuery(ev.target));
  1816. if (!scrollParent.is(window) && !scrollParent.is(document)) {
  1817. this.scrollEl = scrollParent;
  1818. // scope to `this`, and use `debounce` to make sure rapid calls don't happen
  1819. this.scrollHandlerProxy = debounce(proxy(this, 'scrollHandler'), 100);
  1820. this.scrollEl.on('scroll', this.scrollHandlerProxy);
  1821. }
  1822. }
  1823. jQuery(document)
  1824. .on('mousemove', this.mousemoveProxy = proxy(this, 'mousemove'))
  1825. .on('mouseup', this.mouseupProxy = proxy(this, 'mouseup'))
  1826. .on('selectstart', this.preventDefault); // prevents native selection in IE<=8
  1827. if (ev) {
  1828. this.originX = ev.pageX;
  1829. this.originY = ev.pageY;
  1830. }
  1831. else {
  1832. // if no starting information was given, origin will be the topleft corner of the screen.
  1833. // if so, dx/dy in the future will be the absolute coordinates.
  1834. this.originX = 0;
  1835. this.originY = 0;
  1836. }
  1837. this.isListening = true;
  1838. this.listenStart(ev);
  1839. }
  1840. },
  1841. // Called when drag listening has started (but a real drag has not necessarily began)
  1842. listenStart: function(ev) {
  1843. this.trigger('listenStart', ev);
  1844. },
  1845. // Called when the user moves the mouse
  1846. mousemove: function(ev) {
  1847. var dx = ev.pageX - this.originX;
  1848. var dy = ev.pageY - this.originY;
  1849. var minDistance;
  1850. var distanceSq; // current distance from the origin, squared
  1851. if (!this.isDragging) { // if not already dragging...
  1852. // then start the drag if the minimum distance criteria is met
  1853. minDistance = this.options.distance || 1;
  1854. distanceSq = dx * dx + dy * dy;
  1855. if (distanceSq >= minDistance * minDistance) { // use pythagorean theorem
  1856. this.startDrag(ev);
  1857. }
  1858. }
  1859. if (this.isDragging) {
  1860. this.drag(dx, dy, ev); // report a drag, even if this mousemove initiated the drag
  1861. }
  1862. },
  1863. // Call this to initiate a legitimate drag.
  1864. // This function is called internally from this class, but can also be called explicitly from outside
  1865. startDrag: function(ev) {
  1866. if (!this.isListening) { // startDrag must have manually initiated
  1867. this.startListening();
  1868. }
  1869. if (!this.isDragging) {
  1870. this.isDragging = true;
  1871. this.dragStart(ev);
  1872. }
  1873. },
  1874. // Called when the actual drag has started (went beyond minDistance)
  1875. dragStart: function(ev) {
  1876. var subjectEl = this.subjectEl;
  1877. this.trigger('dragStart', ev);
  1878. // remove a mousedown'd <a>'s href so it is not visited (IE8 bug)
  1879. if ((this.subjectHref = subjectEl ? subjectEl.attr('href') : null)) {
  1880. subjectEl.removeAttr('href');
  1881. }
  1882. },
  1883. // Called while the mouse is being moved and when we know a legitimate drag is taking place
  1884. drag: function(dx, dy, ev) {
  1885. this.trigger('drag', dx, dy, ev);
  1886. this.updateScroll(ev); // will possibly cause scrolling
  1887. },
  1888. // Called when the user does a mouseup
  1889. mouseup: function(ev) {
  1890. this.stopListening(ev);
  1891. },
  1892. // Called when the drag is over. Will not cause listening to stop however.
  1893. // A concluding 'cellOut' event will NOT be triggered.
  1894. stopDrag: function(ev) {
  1895. if (this.isDragging) {
  1896. this.stopScrolling();
  1897. this.dragStop(ev);
  1898. this.isDragging = false;
  1899. }
  1900. },
  1901. // Called when dragging has been stopped
  1902. dragStop: function(ev) {
  1903. var _this = this;
  1904. this.trigger('dragStop', ev);
  1905. // restore a mousedown'd <a>'s href (for IE8 bug)
  1906. setTimeout(function() { // must be outside of the click's execution
  1907. if (_this.subjectHref) {
  1908. _this.subjectEl.attr('href', _this.subjectHref);
  1909. }
  1910. }, 0);
  1911. },
  1912. // Call this to stop listening to the user's mouse events
  1913. stopListening: function(ev) {
  1914. this.stopDrag(ev); // if there's a current drag, kill it
  1915. if (this.isListening) {
  1916. // remove the scroll handler if there is a scrollEl
  1917. if (this.scrollEl) {
  1918. this.scrollEl.off('scroll', this.scrollHandlerProxy);
  1919. this.scrollHandlerProxy = null;
  1920. }
  1921. jQuery(document)
  1922. .off('mousemove', this.mousemoveProxy)
  1923. .off('mouseup', this.mouseupProxy)
  1924. .off('selectstart', this.preventDefault);
  1925. this.mousemoveProxy = null;
  1926. this.mouseupProxy = null;
  1927. this.isListening = false;
  1928. this.listenStop(ev);
  1929. }
  1930. },
  1931. // Called when drag listening has stopped
  1932. listenStop: function(ev) {
  1933. this.trigger('listenStop', ev);
  1934. },
  1935. // Triggers a callback. Calls a function in the option hash of the same name.
  1936. // Arguments beyond the first `name` are forwarded on.
  1937. trigger: function(name) {
  1938. if (this.options[name]) {
  1939. this.options[name].apply(this, Array.prototype.slice.call(arguments, 1));
  1940. }
  1941. },
  1942. // Stops a given mouse event from doing it's native browser action. In our case, text selection.
  1943. preventDefault: function(ev) {
  1944. ev.preventDefault();
  1945. },
  1946. /* Scrolling
  1947. ------------------------------------------------------------------------------------------------------------------*/
  1948. // Computes and stores the bounding rectangle of scrollEl
  1949. computeScrollBounds: function() {
  1950. var el = this.scrollEl;
  1951. this.scrollBounds = el ? getOuterRect(el) : null;
  1952. // TODO: use getClientRect in future. but prevents auto scrolling when on top of scrollbars
  1953. },
  1954. // Called when the dragging is in progress and scrolling should be updated
  1955. updateScroll: function(ev) {
  1956. var sensitivity = this.scrollSensitivity;
  1957. var bounds = this.scrollBounds;
  1958. var topCloseness, bottomCloseness;
  1959. var leftCloseness, rightCloseness;
  1960. var topVel = 0;
  1961. var leftVel = 0;
  1962. if (bounds) { // only scroll if scrollEl exists
  1963. // compute closeness to edges. valid range is from 0.0 - 1.0
  1964. topCloseness = (sensitivity - (ev.pageY - bounds.top)) / sensitivity;
  1965. bottomCloseness = (sensitivity - (bounds.bottom - ev.pageY)) / sensitivity;
  1966. leftCloseness = (sensitivity - (ev.pageX - bounds.left)) / sensitivity;
  1967. rightCloseness = (sensitivity - (bounds.right - ev.pageX)) / sensitivity;
  1968. // translate vertical closeness into velocity.
  1969. // mouse must be completely in bounds for velocity to happen.
  1970. if (topCloseness >= 0 && topCloseness <= 1) {
  1971. topVel = topCloseness * this.scrollSpeed * -1; // negative. for scrolling up
  1972. }
  1973. else if (bottomCloseness >= 0 && bottomCloseness <= 1) {
  1974. topVel = bottomCloseness * this.scrollSpeed;
  1975. }
  1976. // translate horizontal closeness into velocity
  1977. if (leftCloseness >= 0 && leftCloseness <= 1) {
  1978. leftVel = leftCloseness * this.scrollSpeed * -1; // negative. for scrolling left
  1979. }
  1980. else if (rightCloseness >= 0 && rightCloseness <= 1) {
  1981. leftVel = rightCloseness * this.scrollSpeed;
  1982. }
  1983. }
  1984. this.setScrollVel(topVel, leftVel);
  1985. },
  1986. // Sets the speed-of-scrolling for the scrollEl
  1987. setScrollVel: function(topVel, leftVel) {
  1988. this.scrollTopVel = topVel;
  1989. this.scrollLeftVel = leftVel;
  1990. this.constrainScrollVel(); // massages into realistic values
  1991. // if there is non-zero velocity, and an animation loop hasn't already started, then START
  1992. if ((this.scrollTopVel || this.scrollLeftVel) && !this.scrollIntervalId) {
  1993. this.scrollIntervalId = setInterval(
  1994. proxy(this, 'scrollIntervalFunc'), // scope to `this`
  1995. this.scrollIntervalMs
  1996. );
  1997. }
  1998. },
  1999. // Forces scrollTopVel and scrollLeftVel to be zero if scrolling has already gone all the way
  2000. constrainScrollVel: function() {
  2001. var el = this.scrollEl;
  2002. if (this.scrollTopVel < 0) { // scrolling up?
  2003. if (el.scrollTop() <= 0) { // already scrolled all the way up?
  2004. this.scrollTopVel = 0;
  2005. }
  2006. }
  2007. else if (this.scrollTopVel > 0) { // scrolling down?
  2008. if (el.scrollTop() + el[0].clientHeight >= el[0].scrollHeight) { // already scrolled all the way down?
  2009. this.scrollTopVel = 0;
  2010. }
  2011. }
  2012. if (this.scrollLeftVel < 0) { // scrolling left?
  2013. if (el.scrollLeft() <= 0) { // already scrolled all the left?
  2014. this.scrollLeftVel = 0;
  2015. }
  2016. }
  2017. else if (this.scrollLeftVel > 0) { // scrolling right?
  2018. if (el.scrollLeft() + el[0].clientWidth >= el[0].scrollWidth) { // already scrolled all the way right?
  2019. this.scrollLeftVel = 0;
  2020. }
  2021. }
  2022. },
  2023. // This function gets called during every iteration of the scrolling animation loop
  2024. scrollIntervalFunc: function() {
  2025. var el = this.scrollEl;
  2026. var frac = this.scrollIntervalMs / 1000; // considering animation frequency, what the vel should be mult'd by
  2027. // change the value of scrollEl's scroll
  2028. if (this.scrollTopVel) {
  2029. el.scrollTop(el.scrollTop() + this.scrollTopVel * frac);
  2030. }
  2031. if (this.scrollLeftVel) {
  2032. el.scrollLeft(el.scrollLeft() + this.scrollLeftVel * frac);
  2033. }
  2034. this.constrainScrollVel(); // since the scroll values changed, recompute the velocities
  2035. // if scrolled all the way, which causes the vels to be zero, stop the animation loop
  2036. if (!this.scrollTopVel && !this.scrollLeftVel) {
  2037. this.stopScrolling();
  2038. }
  2039. },
  2040. // Kills any existing scrolling animation loop
  2041. stopScrolling: function() {
  2042. if (this.scrollIntervalId) {
  2043. clearInterval(this.scrollIntervalId);
  2044. this.scrollIntervalId = null;
  2045. // when all done with scrolling, recompute positions since they probably changed
  2046. this.scrollStop();
  2047. }
  2048. },
  2049. // Get called when the scrollEl is scrolled (NOTE: this is delayed via debounce)
  2050. scrollHandler: function() {
  2051. // recompute all coordinates, but *only* if this is *not* part of our scrolling animation
  2052. if (!this.scrollIntervalId) {
  2053. this.scrollStop();
  2054. }
  2055. },
  2056. // Called when scrolling has stopped, whether through auto scroll, or the user scrolling
  2057. scrollStop: function() {
  2058. }
  2059. });
  2060. ;;
  2061. /* Tracks mouse movements over a component and raises events about which hit the mouse is over.
  2062. ------------------------------------------------------------------------------------------------------------------------
  2063. options:
  2064. - subjectEl
  2065. - subjectCenter
  2066. */
  2067. var HitDragListener = DragListener.extend({
  2068. component: null, // converts coordinates to hits
  2069. // methods: prepareHits, releaseHits, queryHit
  2070. origHit: null, // the hit the mouse was over when listening started
  2071. hit: null, // the hit the mouse is over
  2072. coordAdjust: null, // delta that will be added to the mouse coordinates when computing collisions
  2073. constructor: function(component, options) {
  2074. DragListener.call(this, options); // call the super-constructor
  2075. this.component = component;
  2076. },
  2077. // Called when drag listening starts (but a real drag has not necessarily began).
  2078. // ev might be undefined if dragging was started manually.
  2079. listenStart: function(ev) {
  2080. var subjectEl = this.subjectEl;
  2081. var subjectRect;
  2082. var origPoint;
  2083. var point;
  2084. DragListener.prototype.listenStart.apply(this, arguments); // call the super-method
  2085. this.computeCoords();
  2086. if (ev) {
  2087. origPoint = { left: ev.pageX, top: ev.pageY };
  2088. point = origPoint;
  2089. // constrain the point to bounds of the element being dragged
  2090. if (subjectEl) {
  2091. subjectRect = getOuterRect(subjectEl); // used for centering as well
  2092. point = constrainPoint(point, subjectRect);
  2093. }
  2094. this.origHit = this.queryHit(point.left, point.top);
  2095. // treat the center of the subject as the collision point?
  2096. if (subjectEl && this.options.subjectCenter) {
  2097. // only consider the area the subject overlaps the hit. best for large subjects.
  2098. // TODO: skip this if hit didn't supply left/right/top/bottom
  2099. if (this.origHit) {
  2100. subjectRect = intersectRects(this.origHit, subjectRect) ||
  2101. subjectRect; // in case there is no intersection
  2102. }
  2103. point = getRectCenter(subjectRect);
  2104. }
  2105. this.coordAdjust = diffPoints(point, origPoint); // point - origPoint
  2106. }
  2107. else {
  2108. this.origHit = null;
  2109. this.coordAdjust = null;
  2110. }
  2111. },
  2112. // Recomputes the drag-critical positions of elements
  2113. computeCoords: function() {
  2114. this.component.prepareHits();
  2115. this.computeScrollBounds(); // why is this here???
  2116. },
  2117. // Called when the actual drag has started
  2118. dragStart: function(ev) {
  2119. var hit;
  2120. DragListener.prototype.dragStart.apply(this, arguments); // call the super-method
  2121. // might be different from this.origHit if the min-distance is large
  2122. hit = this.queryHit(ev.pageX, ev.pageY);
  2123. // report the initial hit the mouse is over
  2124. // especially important if no min-distance and drag starts immediately
  2125. if (hit) {
  2126. this.hitOver(hit);
  2127. }
  2128. },
  2129. // Called when the drag moves
  2130. drag: function(dx, dy, ev) {
  2131. var hit;
  2132. DragListener.prototype.drag.apply(this, arguments); // call the super-method
  2133. hit = this.queryHit(ev.pageX, ev.pageY);
  2134. if (!isHitsEqual(hit, this.hit)) { // a different hit than before?
  2135. if (this.hit) {
  2136. this.hitOut();
  2137. }
  2138. if (hit) {
  2139. this.hitOver(hit);
  2140. }
  2141. }
  2142. },
  2143. // Called when dragging has been stopped
  2144. dragStop: function() {
  2145. this.hitDone();
  2146. DragListener.prototype.dragStop.apply(this, arguments); // call the super-method
  2147. },
  2148. // Called when a the mouse has just moved over a new hit
  2149. hitOver: function(hit) {
  2150. var isOrig = isHitsEqual(hit, this.origHit);
  2151. this.hit = hit;
  2152. this.trigger('hitOver', this.hit, isOrig, this.origHit);
  2153. },
  2154. // Called when the mouse has just moved out of a hit
  2155. hitOut: function() {
  2156. if (this.hit) {
  2157. this.trigger('hitOut', this.hit);
  2158. this.hitDone();
  2159. this.hit = null;
  2160. }
  2161. },
  2162. // Called after a hitOut. Also called before a dragStop
  2163. hitDone: function() {
  2164. if (this.hit) {
  2165. this.trigger('hitDone', this.hit);
  2166. }
  2167. },
  2168. // Called when drag listening has stopped
  2169. listenStop: function() {
  2170. DragListener.prototype.listenStop.apply(this, arguments); // call the super-method
  2171. this.origHit = null;
  2172. this.hit = null;
  2173. this.component.releaseHits();
  2174. },
  2175. // Called when scrolling has stopped, whether through auto scroll, or the user scrolling
  2176. scrollStop: function() {
  2177. DragListener.prototype.scrollStop.apply(this, arguments); // call the super-method
  2178. this.computeCoords(); // hits' absolute positions will be in new places. recompute
  2179. },
  2180. // Gets the hit underneath the coordinates for the given mouse event
  2181. queryHit: function(left, top) {
  2182. if (this.coordAdjust) {
  2183. left += this.coordAdjust.left;
  2184. top += this.coordAdjust.top;
  2185. }
  2186. return this.component.queryHit(left, top);
  2187. }
  2188. });
  2189. // Returns `true` if the hits are identically equal. `false` otherwise. Must be from the same component.
  2190. // Two null values will be considered equal, as two "out of the component" states are the same.
  2191. function isHitsEqual(hit0, hit1) {
  2192. if (!hit0 && !hit1) {
  2193. return true;
  2194. }
  2195. if (hit0 && hit1) {
  2196. return hit0.component === hit1.component &&
  2197. isHitPropsWithin(hit0, hit1) &&
  2198. isHitPropsWithin(hit1, hit0); // ensures all props are identical
  2199. }
  2200. return false;
  2201. }
  2202. // Returns true if all of subHit's non-standard properties are within superHit
  2203. function isHitPropsWithin(subHit, superHit) {
  2204. for (var propName in subHit) {
  2205. if (!/^(component|left|right|top|bottom)$/.test(propName)) {
  2206. if (subHit[propName] !== superHit[propName]) {
  2207. return false;
  2208. }
  2209. }
  2210. }
  2211. return true;
  2212. }
  2213. ;;
  2214. /* Creates a clone of an element and lets it track the mouse as it moves
  2215. ----------------------------------------------------------------------------------------------------------------------*/
  2216. var MouseFollower = Class.extend({
  2217. options: null,
  2218. sourceEl: null, // the element that will be cloned and made to look like it is dragging
  2219. el: null, // the clone of `sourceEl` that will track the mouse
  2220. parentEl: null, // the element that `el` (the clone) will be attached to
  2221. // the initial position of el, relative to the offset parent. made to match the initial offset of sourceEl
  2222. top0: null,
  2223. left0: null,
  2224. // the initial position of the mouse
  2225. mouseY0: null,
  2226. mouseX0: null,
  2227. // the number of pixels the mouse has moved from its initial position
  2228. topDelta: null,
  2229. leftDelta: null,
  2230. mousemoveProxy: null, // document mousemove handler, bound to the MouseFollower's `this`
  2231. isFollowing: false,
  2232. isHidden: false,
  2233. isAnimating: false, // doing the revert animation?
  2234. constructor: function(sourceEl, options) {
  2235. this.options = options = options || {};
  2236. this.sourceEl = sourceEl;
  2237. this.parentEl = options.parentEl ? jQuery(options.parentEl) : sourceEl.parent(); // default to sourceEl's parent
  2238. },
  2239. // Causes the element to start following the mouse
  2240. start: function(ev) {
  2241. if (!this.isFollowing) {
  2242. this.isFollowing = true;
  2243. this.mouseY0 = ev.pageY;
  2244. this.mouseX0 = ev.pageX;
  2245. this.topDelta = 0;
  2246. this.leftDelta = 0;
  2247. if (!this.isHidden) {
  2248. this.updatePosition();
  2249. }
  2250. jQuery(document).on('mousemove', this.mousemoveProxy = proxy(this, 'mousemove'));
  2251. }
  2252. },
  2253. // Causes the element to stop following the mouse. If shouldRevert is true, will animate back to original position.
  2254. // `callback` gets invoked when the animation is complete. If no animation, it is invoked immediately.
  2255. stop: function(shouldRevert, callback) {
  2256. var _this = this;
  2257. var revertDuration = this.options.revertDuration;
  2258. function complete() {
  2259. this.isAnimating = false;
  2260. _this.removeElement();
  2261. this.top0 = this.left0 = null; // reset state for future updatePosition calls
  2262. if (callback) {
  2263. callback();
  2264. }
  2265. }
  2266. if (this.isFollowing && !this.isAnimating) { // disallow more than one stop animation at a time
  2267. this.isFollowing = false;
  2268. jQuery(document).off('mousemove', this.mousemoveProxy);
  2269. if (shouldRevert && revertDuration && !this.isHidden) { // do a revert animation?
  2270. this.isAnimating = true;
  2271. this.el.animate({
  2272. top: this.top0,
  2273. left: this.left0
  2274. }, {
  2275. duration: revertDuration,
  2276. complete: complete
  2277. });
  2278. }
  2279. else {
  2280. complete();
  2281. }
  2282. }
  2283. },
  2284. // Gets the tracking element. Create it if necessary
  2285. getEl: function() {
  2286. var el = this.el;
  2287. if (!el) {
  2288. this.sourceEl.width(); // hack to force IE8 to compute correct bounding box
  2289. el = this.el = this.sourceEl.clone()
  2290. .css({
  2291. position: 'absolute',
  2292. visibility: '', // in case original element was hidden (commonly through hideEvents())
  2293. display: this.isHidden ? 'none' : '', // for when initially hidden
  2294. margin: 0,
  2295. right: 'auto', // erase and set width instead
  2296. bottom: 'auto', // erase and set height instead
  2297. width: this.sourceEl.width(), // explicit height in case there was a 'right' value
  2298. height: this.sourceEl.height(), // explicit width in case there was a 'bottom' value
  2299. opacity: this.options.opacity || '',
  2300. zIndex: this.options.zIndex
  2301. })
  2302. .appendTo(this.parentEl);
  2303. }
  2304. return el;
  2305. },
  2306. // Removes the tracking element if it has already been created
  2307. removeElement: function() {
  2308. if (this.el) {
  2309. this.el.remove();
  2310. this.el = null;
  2311. }
  2312. },
  2313. // Update the CSS position of the tracking element
  2314. updatePosition: function() {
  2315. var sourceOffset;
  2316. var origin;
  2317. this.getEl(); // ensure this.el
  2318. // make sure origin info was computed
  2319. if (this.top0 === null) {
  2320. this.sourceEl.width(); // hack to force IE8 to compute correct bounding box
  2321. sourceOffset = this.sourceEl.offset();
  2322. origin = this.el.offsetParent().offset();
  2323. this.top0 = sourceOffset.top - origin.top;
  2324. this.left0 = sourceOffset.left - origin.left;
  2325. }
  2326. this.el.css({
  2327. top: this.top0 + this.topDelta,
  2328. left: this.left0 + this.leftDelta
  2329. });
  2330. },
  2331. // Gets called when the user moves the mouse
  2332. mousemove: function(ev) {
  2333. this.topDelta = ev.pageY - this.mouseY0;
  2334. this.leftDelta = ev.pageX - this.mouseX0;
  2335. if (!this.isHidden) {
  2336. this.updatePosition();
  2337. }
  2338. },
  2339. // Temporarily makes the tracking element invisible. Can be called before following starts
  2340. hide: function() {
  2341. if (!this.isHidden) {
  2342. this.isHidden = true;
  2343. if (this.el) {
  2344. this.el.hide();
  2345. }
  2346. }
  2347. },
  2348. // Show the tracking element after it has been temporarily hidden
  2349. show: function() {
  2350. if (this.isHidden) {
  2351. this.isHidden = false;
  2352. this.updatePosition();
  2353. this.getEl().show();
  2354. }
  2355. }
  2356. });
  2357. ;;
  2358. /* An abstract class comprised of a "grid" of areas that each represent a specific datetime
  2359. ----------------------------------------------------------------------------------------------------------------------*/
  2360. var Grid = FC.Grid = Class.extend({
  2361. view: null, // a View object
  2362. isRTL: null, // shortcut to the view's isRTL option
  2363. start: null,
  2364. end: null,
  2365. el: null, // the containing element
  2366. elsByFill: null, // a hash of jQuery element sets used for rendering each fill. Keyed by fill name.
  2367. externalDragStartProxy: null, // binds the Grid's scope to externalDragStart (in DayGrid.events)
  2368. // derived from options
  2369. eventTimeFormat: null,
  2370. displayEventTime: null,
  2371. displayEventEnd: null,
  2372. minResizeDuration: null, // TODO: hack. set by subclasses. minumum event resize duration
  2373. // if defined, holds the unit identified (ex: "year" or "month") that determines the level of granularity
  2374. // of the date areas. if not defined, assumes to be day and time granularity.
  2375. // TODO: port isTimeScale into same system?
  2376. largeUnit: null,
  2377. constructor: function(view) {
  2378. this.view = view;
  2379. this.isRTL = view.opt('isRTL');
  2380. this.elsByFill = {};
  2381. this.externalDragStartProxy = proxy(this, 'externalDragStart');
  2382. },
  2383. /* Options
  2384. ------------------------------------------------------------------------------------------------------------------*/
  2385. // Generates the format string used for event time text, if not explicitly defined by 'timeFormat'
  2386. computeEventTimeFormat: function() {
  2387. return this.view.opt('smallTimeFormat');
  2388. },
  2389. // Determines whether events should have their end times displayed, if not explicitly defined by 'displayEventTime'.
  2390. // Only applies to non-all-day events.
  2391. computeDisplayEventTime: function() {
  2392. return true;
  2393. },
  2394. // Determines whether events should have their end times displayed, if not explicitly defined by 'displayEventEnd'
  2395. computeDisplayEventEnd: function() {
  2396. return true;
  2397. },
  2398. /* Dates
  2399. ------------------------------------------------------------------------------------------------------------------*/
  2400. // Tells the grid about what period of time to display.
  2401. // Any date-related internal data should be generated.
  2402. setRange: function(range) {
  2403. this.start = range.start.clone();
  2404. this.end = range.end.clone();
  2405. this.rangeUpdated();
  2406. this.processRangeOptions();
  2407. },
  2408. // Called when internal variables that rely on the range should be updated
  2409. rangeUpdated: function() {
  2410. },
  2411. // Updates values that rely on options and also relate to range
  2412. processRangeOptions: function() {
  2413. var view = this.view;
  2414. var displayEventTime;
  2415. var displayEventEnd;
  2416. this.eventTimeFormat =
  2417. view.opt('eventTimeFormat') ||
  2418. view.opt('timeFormat') || // deprecated
  2419. this.computeEventTimeFormat();
  2420. displayEventTime = view.opt('displayEventTime');
  2421. if (displayEventTime == null) {
  2422. displayEventTime = this.computeDisplayEventTime(); // might be based off of range
  2423. }
  2424. displayEventEnd = view.opt('displayEventEnd');
  2425. if (displayEventEnd == null) {
  2426. displayEventEnd = this.computeDisplayEventEnd(); // might be based off of range
  2427. }
  2428. this.displayEventTime = displayEventTime;
  2429. this.displayEventEnd = displayEventEnd;
  2430. },
  2431. // Converts a span (has unzoned start/end and any other grid-specific location information)
  2432. // into an array of segments (pieces of events whose format is decided by the grid).
  2433. spanToSegs: function(span) {
  2434. // subclasses must implement
  2435. },
  2436. // Diffs the two dates, returning a duration, based on granularity of the grid
  2437. // TODO: port isTimeScale into this system?
  2438. diffDates: function(a, b) {
  2439. if (this.largeUnit) {
  2440. return diffByUnit(a, b, this.largeUnit);
  2441. }
  2442. else {
  2443. return diffDayTime(a, b);
  2444. }
  2445. },
  2446. /* Hit Area
  2447. ------------------------------------------------------------------------------------------------------------------*/
  2448. // Called before one or more queryHit calls might happen. Should prepare any cached coordinates for queryHit
  2449. prepareHits: function() {
  2450. },
  2451. // Called when queryHit calls have subsided. Good place to clear any coordinate caches.
  2452. releaseHits: function() {
  2453. },
  2454. // Given coordinates from the topleft of the document, return data about the date-related area underneath.
  2455. // Can return an object with arbitrary properties (although top/right/left/bottom are encouraged).
  2456. // Must have a `grid` property, a reference to this current grid. TODO: avoid this
  2457. // The returned object will be processed by getHitSpan and getHitEl.
  2458. queryHit: function(leftOffset, topOffset) {
  2459. },
  2460. // Given position-level information about a date-related area within the grid,
  2461. // should return an object with at least a start/end date. Can provide other information as well.
  2462. getHitSpan: function(hit) {
  2463. },
  2464. // Given position-level information about a date-related area within the grid,
  2465. // should return a jQuery element that best represents it. passed to dayClick callback.
  2466. getHitEl: function(hit) {
  2467. },
  2468. /* Rendering
  2469. ------------------------------------------------------------------------------------------------------------------*/
  2470. // Sets the container element that the grid should render inside of.
  2471. // Does other DOM-related initializations.
  2472. setElement: function(el) {
  2473. var _this = this;
  2474. this.el = el;
  2475. // attach a handler to the grid's root element.
  2476. // jQuery will take care of unregistering them when removeElement gets called.
  2477. el.on('mousedown', function(ev) {
  2478. if (
  2479. !jQuery(ev.target).is('.fc-event-container *, .fc-more') && // not an an event element, or "more.." link
  2480. !jQuery(ev.target).closest('.fc-popover').length // not on a popover (like the "more.." events one)
  2481. ) {
  2482. _this.dayMousedown(ev);
  2483. }
  2484. });
  2485. // attach event-element-related handlers. in Grid.events
  2486. // same garbage collection note as above.
  2487. this.bindSegHandlers();
  2488. this.bindGlobalHandlers();
  2489. },
  2490. // Removes the grid's container element from the DOM. Undoes any other DOM-related attachments.
  2491. // DOES NOT remove any content beforehand (doesn't clear events or call unrenderDates), unlike View
  2492. removeElement: function() {
  2493. this.unbindGlobalHandlers();
  2494. this.el.remove();
  2495. // NOTE: we don't null-out this.el for the same reasons we don't do it within View::removeElement
  2496. },
  2497. // Renders the basic structure of grid view before any content is rendered
  2498. renderSkeleton: function() {
  2499. // subclasses should implement
  2500. },
  2501. // Renders the grid's date-related content (like areas that represent days/times).
  2502. // Assumes setRange has already been called and the skeleton has already been rendered.
  2503. renderDates: function() {
  2504. // subclasses should implement
  2505. },
  2506. // Unrenders the grid's date-related content
  2507. unrenderDates: function() {
  2508. // subclasses should implement
  2509. },
  2510. /* Handlers
  2511. ------------------------------------------------------------------------------------------------------------------*/
  2512. // Binds DOM handlers to elements that reside outside the grid, such as the document
  2513. bindGlobalHandlers: function() {
  2514. jQuery(document).on('dragstart sortstart', this.externalDragStartProxy); // jqui
  2515. },
  2516. // Unbinds DOM handlers from elements that reside outside the grid
  2517. unbindGlobalHandlers: function() {
  2518. jQuery(document).off('dragstart sortstart', this.externalDragStartProxy); // jqui
  2519. },
  2520. // Process a mousedown on an element that represents a day. For day clicking and selecting.
  2521. dayMousedown: function(ev) {
  2522. var _this = this;
  2523. var view = this.view;
  2524. var isSelectable = view.opt('selectable');
  2525. var dayClickHit; // null if invalid dayClick
  2526. var selectionSpan; // null if invalid selection
  2527. // this listener tracks a mousedown on a day element, and a subsequent drag.
  2528. // if the drag ends on the same day, it is a 'dayClick'.
  2529. // if 'selectable' is enabled, this listener also detects selections.
  2530. var dragListener = new HitDragListener(this, {
  2531. //distance: 5, // needs more work if we want dayClick to fire correctly
  2532. scroll: view.opt('dragScroll'),
  2533. dragStart: function() {
  2534. view.unselect(); // since we could be rendering a new selection, we want to clear any old one
  2535. },
  2536. hitOver: function(hit, isOrig, origHit) {
  2537. if (origHit) { // click needs to have started on a hit
  2538. dayClickHit = isOrig ? hit : null; // single-hit selection is a day click
  2539. if (isSelectable) {
  2540. selectionSpan = _this.computeSelection(
  2541. _this.getHitSpan(origHit),
  2542. _this.getHitSpan(hit)
  2543. );
  2544. if (selectionSpan) {
  2545. _this.renderSelection(selectionSpan);
  2546. }
  2547. else if (selectionSpan === false) {
  2548. disableCursor();
  2549. }
  2550. }
  2551. }
  2552. },
  2553. hitOut: function() {
  2554. dayClickHit = null;
  2555. selectionSpan = null;
  2556. _this.unrenderSelection();
  2557. enableCursor();
  2558. },
  2559. listenStop: function(ev) {
  2560. if (dayClickHit) {
  2561. view.triggerDayClick(
  2562. _this.getHitSpan(dayClickHit),
  2563. _this.getHitEl(dayClickHit),
  2564. ev
  2565. );
  2566. }
  2567. if (selectionSpan) {
  2568. // the selection will already have been rendered. just report it
  2569. view.reportSelection(selectionSpan, ev);
  2570. }
  2571. enableCursor();
  2572. }
  2573. });
  2574. dragListener.mousedown(ev); // start listening, which will eventually initiate a dragStart
  2575. },
  2576. /* Event Helper
  2577. ------------------------------------------------------------------------------------------------------------------*/
  2578. // TODO: should probably move this to Grid.events, like we did event dragging / resizing
  2579. // Renders a mock event at the given event location, which contains zoned start/end properties.
  2580. renderEventLocationHelper: function(eventLocation, sourceSeg) {
  2581. var fakeEvent = this.fabricateHelperEvent(eventLocation, sourceSeg);
  2582. this.renderHelper(fakeEvent, sourceSeg); // do the actual rendering
  2583. },
  2584. // Builds a fake event given zoned event date properties and a segment is should be inspired from.
  2585. // The range's end can be null, in which case the mock event that is rendered will have a null end time.
  2586. // `sourceSeg` is the internal segment object involved in the drag. If null, something external is dragging.
  2587. fabricateHelperEvent: function(eventLocation, sourceSeg) {
  2588. var fakeEvent = sourceSeg ? createObject(sourceSeg.event) : {}; // mask the original event object if possible
  2589. fakeEvent.start = eventLocation.start.clone();
  2590. fakeEvent.end = eventLocation.end ? eventLocation.end.clone() : null;
  2591. fakeEvent.allDay = null; // force it to be freshly computed by normalizeEventDates
  2592. this.view.calendar.normalizeEventDates(fakeEvent);
  2593. // this extra className will be useful for differentiating real events from mock events in CSS
  2594. fakeEvent.className = (fakeEvent.className || []).concat('fc-helper');
  2595. // if something external is being dragged in, don't render a resizer
  2596. if (!sourceSeg) {
  2597. fakeEvent.editable = false;
  2598. }
  2599. return fakeEvent;
  2600. },
  2601. // Renders a mock event. Given zoned event date properties.
  2602. renderHelper: function(eventLocation, sourceSeg) {
  2603. // subclasses must implement
  2604. },
  2605. // Unrenders a mock event
  2606. unrenderHelper: function() {
  2607. // subclasses must implement
  2608. },
  2609. /* Selection
  2610. ------------------------------------------------------------------------------------------------------------------*/
  2611. // Renders a visual indication of a selection. Will highlight by default but can be overridden by subclasses.
  2612. // Given a span (unzoned start/end and other misc data)
  2613. renderSelection: function(span) {
  2614. this.renderHighlight(span);
  2615. },
  2616. // Unrenders any visual indications of a selection. Will unrender a highlight by default.
  2617. unrenderSelection: function() {
  2618. this.unrenderHighlight();
  2619. },
  2620. // Given the first and last date-spans of a selection, returns another date-span object.
  2621. // Subclasses can override and provide additional data in the span object. Will be passed to renderSelection().
  2622. // Will return false if the selection is invalid and this should be indicated to the user.
  2623. // Will return null/undefined if a selection invalid but no error should be reported.
  2624. computeSelection: function(span0, span1) {
  2625. var span = this.computeSelectionSpan(span0, span1);
  2626. if (span && !this.view.calendar.isSelectionSpanAllowed(span)) {
  2627. return false;
  2628. }
  2629. return span;
  2630. },
  2631. // Given two spans, must return the combination of the two.
  2632. // TODO: do this separation of concerns (combining VS validation) for event dnd/resize too.
  2633. computeSelectionSpan: function(span0, span1) {
  2634. var dates = [ span0.start, span0.end, span1.start, span1.end ];
  2635. dates.sort(compareNumbers); // sorts chronologically. works with Moments
  2636. return { start: dates[0].clone(), end: dates[3].clone() };
  2637. },
  2638. /* Highlight
  2639. ------------------------------------------------------------------------------------------------------------------*/
  2640. // Renders an emphasis on the given date range. Given a span (unzoned start/end and other misc data)
  2641. renderHighlight: function(span) {
  2642. this.renderFill('highlight', this.spanToSegs(span));
  2643. },
  2644. // Unrenders the emphasis on a date range
  2645. unrenderHighlight: function() {
  2646. this.unrenderFill('highlight');
  2647. },
  2648. // Generates an array of classNames for rendering the highlight. Used by the fill system.
  2649. highlightSegClasses: function() {
  2650. return [ 'fc-highlight' ];
  2651. },
  2652. /* Business Hours
  2653. ------------------------------------------------------------------------------------------------------------------*/
  2654. renderBusinessHours: function() {
  2655. },
  2656. unrenderBusinessHours: function() {
  2657. },
  2658. /* Now Indicator
  2659. ------------------------------------------------------------------------------------------------------------------*/
  2660. getNowIndicatorUnit: function() {
  2661. },
  2662. renderNowIndicator: function(date) {
  2663. },
  2664. unrenderNowIndicator: function() {
  2665. },
  2666. /* Fill System (highlight, background events, business hours)
  2667. --------------------------------------------------------------------------------------------------------------------
  2668. TODO: remove this system. like we did in TimeGrid
  2669. */
  2670. // Renders a set of rectangles over the given segments of time.
  2671. // MUST RETURN a subset of segs, the segs that were actually rendered.
  2672. // Responsible for populating this.elsByFill. TODO: better API for expressing this requirement
  2673. renderFill: function(type, segs) {
  2674. // subclasses must implement
  2675. },
  2676. // Unrenders a specific type of fill that is currently rendered on the grid
  2677. unrenderFill: function(type) {
  2678. var el = this.elsByFill[type];
  2679. if (el) {
  2680. el.remove();
  2681. delete this.elsByFill[type];
  2682. }
  2683. },
  2684. // Renders and assigns an `el` property for each fill segment. Generic enough to work with different types.
  2685. // Only returns segments that successfully rendered.
  2686. // To be harnessed by renderFill (implemented by subclasses).
  2687. // Analagous to renderFgSegEls.
  2688. renderFillSegEls: function(type, segs) {
  2689. var _this = this;
  2690. var segElMethod = this[type + 'SegEl'];
  2691. var html = '';
  2692. var renderedSegs = [];
  2693. var i;
  2694. if (segs.length) {
  2695. // build a large concatenation of segment HTML
  2696. for (i = 0; i < segs.length; i++) {
  2697. html += this.fillSegHtml(type, segs[i]);
  2698. }
  2699. // Grab individual elements from the combined HTML string. Use each as the default rendering.
  2700. // Then, compute the 'el' for each segment.
  2701. jQuery(html).each(function(i, node) {
  2702. var seg = segs[i];
  2703. var el = jQuery(node);
  2704. // allow custom filter methods per-type
  2705. if (segElMethod) {
  2706. el = segElMethod.call(_this, seg, el);
  2707. }
  2708. if (el) { // custom filters did not cancel the render
  2709. el = jQuery(el); // allow custom filter to return raw DOM node
  2710. // correct element type? (would be bad if a non-TD were inserted into a table for example)
  2711. if (el.is(_this.fillSegTag)) {
  2712. seg.el = el;
  2713. renderedSegs.push(seg);
  2714. }
  2715. }
  2716. });
  2717. }
  2718. return renderedSegs;
  2719. },
  2720. fillSegTag: 'div', // subclasses can override
  2721. // Builds the HTML needed for one fill segment. Generic enought o work with different types.
  2722. fillSegHtml: function(type, seg) {
  2723. // custom hooks per-type
  2724. var classesMethod = this[type + 'SegClasses'];
  2725. var cssMethod = this[type + 'SegCss'];
  2726. var classes = classesMethod ? classesMethod.call(this, seg) : [];
  2727. var css = cssToStr(cssMethod ? cssMethod.call(this, seg) : {});
  2728. return '<' + this.fillSegTag +
  2729. (classes.length ? ' class="' + classes.join(' ') + '"' : '') +
  2730. (css ? ' style="' + css + '"' : '') +
  2731. ' />';
  2732. },
  2733. /* Generic rendering utilities for subclasses
  2734. ------------------------------------------------------------------------------------------------------------------*/
  2735. // Computes HTML classNames for a single-day element
  2736. getDayClasses: function(date) {
  2737. var view = this.view;
  2738. var today = view.calendar.getNow();
  2739. var classes = [ 'fc-' + dayIDs[date.day()] ];
  2740. if (
  2741. view.intervalDuration.as('months') == 1 &&
  2742. date.month() != view.intervalStart.month()
  2743. ) {
  2744. classes.push('fc-other-month');
  2745. }
  2746. if (date.isSame(today, 'day')) {
  2747. classes.push(
  2748. 'fc-today',
  2749. view.highlightStateClass
  2750. );
  2751. }
  2752. else if (date < today) {
  2753. classes.push('fc-past');
  2754. }
  2755. else {
  2756. classes.push('fc-future');
  2757. }
  2758. return classes;
  2759. }
  2760. });
  2761. ;;
  2762. /* Event-rendering and event-interaction methods for the abstract Grid class
  2763. ----------------------------------------------------------------------------------------------------------------------*/
  2764. Grid.mixin({
  2765. mousedOverSeg: null, // the segment object the user's mouse is over. null if over nothing
  2766. isDraggingSeg: false, // is a segment being dragged? boolean
  2767. isResizingSeg: false, // is a segment being resized? boolean
  2768. isDraggingExternal: false, // jqui-dragging an external element? boolean
  2769. segs: null, // the *event* segments currently rendered in the grid. TODO: rename to `eventSegs`
  2770. // Renders the given events onto the grid
  2771. renderEvents: function(events) {
  2772. var bgEvents = [];
  2773. var fgEvents = [];
  2774. var i;
  2775. for (i = 0; i < events.length; i++) {
  2776. (isBgEvent(events[i]) ? bgEvents : fgEvents).push(events[i]);
  2777. }
  2778. this.segs = [].concat( // record all segs
  2779. this.renderBgEvents(bgEvents),
  2780. this.renderFgEvents(fgEvents)
  2781. );
  2782. },
  2783. renderBgEvents: function(events) {
  2784. var segs = this.eventsToSegs(events);
  2785. // renderBgSegs might return a subset of segs, segs that were actually rendered
  2786. return this.renderBgSegs(segs) || segs;
  2787. },
  2788. renderFgEvents: function(events) {
  2789. var segs = this.eventsToSegs(events);
  2790. // renderFgSegs might return a subset of segs, segs that were actually rendered
  2791. return this.renderFgSegs(segs) || segs;
  2792. },
  2793. // Unrenders all events currently rendered on the grid
  2794. unrenderEvents: function() {
  2795. this.triggerSegMouseout(); // trigger an eventMouseout if user's mouse is over an event
  2796. this.unrenderFgSegs();
  2797. this.unrenderBgSegs();
  2798. this.segs = null;
  2799. },
  2800. // Retrieves all rendered segment objects currently rendered on the grid
  2801. getEventSegs: function() {
  2802. return this.segs || [];
  2803. },
  2804. /* Foreground Segment Rendering
  2805. ------------------------------------------------------------------------------------------------------------------*/
  2806. // Renders foreground event segments onto the grid. May return a subset of segs that were rendered.
  2807. renderFgSegs: function(segs) {
  2808. // subclasses must implement
  2809. },
  2810. // Unrenders all currently rendered foreground segments
  2811. unrenderFgSegs: function() {
  2812. // subclasses must implement
  2813. },
  2814. // Renders and assigns an `el` property for each foreground event segment.
  2815. // Only returns segments that successfully rendered.
  2816. // A utility that subclasses may use.
  2817. renderFgSegEls: function(segs, disableResizing) {
  2818. var view = this.view;
  2819. var html = '';
  2820. var renderedSegs = [];
  2821. var i;
  2822. if (segs.length) { // don't build an empty html string
  2823. // build a large concatenation of event segment HTML
  2824. for (i = 0; i < segs.length; i++) {
  2825. html += this.fgSegHtml(segs[i], disableResizing);
  2826. }
  2827. // Grab individual elements from the combined HTML string. Use each as the default rendering.
  2828. // Then, compute the 'el' for each segment. An el might be null if the eventRender callback returned false.
  2829. jQuery(html).each(function(i, node) {
  2830. var seg = segs[i];
  2831. var el = view.resolveEventEl(seg.event, jQuery(node));
  2832. if (el) {
  2833. el.data('fc-seg', seg); // used by handlers
  2834. seg.el = el;
  2835. renderedSegs.push(seg);
  2836. }
  2837. });
  2838. }
  2839. return renderedSegs;
  2840. },
  2841. // Generates the HTML for the default rendering of a foreground event segment. Used by renderFgSegEls()
  2842. fgSegHtml: function(seg, disableResizing) {
  2843. // subclasses should implement
  2844. },
  2845. /* Background Segment Rendering
  2846. ------------------------------------------------------------------------------------------------------------------*/
  2847. // Renders the given background event segments onto the grid.
  2848. // Returns a subset of the segs that were actually rendered.
  2849. renderBgSegs: function(segs) {
  2850. return this.renderFill('bgEvent', segs);
  2851. },
  2852. // Unrenders all the currently rendered background event segments
  2853. unrenderBgSegs: function() {
  2854. this.unrenderFill('bgEvent');
  2855. },
  2856. // Renders a background event element, given the default rendering. Called by the fill system.
  2857. bgEventSegEl: function(seg, el) {
  2858. return this.view.resolveEventEl(seg.event, el); // will filter through eventRender
  2859. },
  2860. // Generates an array of classNames to be used for the default rendering of a background event.
  2861. // Called by the fill system.
  2862. bgEventSegClasses: function(seg) {
  2863. var event = seg.event;
  2864. var source = event.source || {};
  2865. return [ 'fc-bgevent' ].concat(
  2866. event.className,
  2867. source.className || []
  2868. );
  2869. },
  2870. // Generates a semicolon-separated CSS string to be used for the default rendering of a background event.
  2871. // Called by the fill system.
  2872. bgEventSegCss: function(seg) {
  2873. return {
  2874. 'background-color': this.getSegSkinCss(seg)['background-color']
  2875. };
  2876. },
  2877. // Generates an array of classNames to be used for the rendering business hours overlay. Called by the fill system.
  2878. businessHoursSegClasses: function(seg) {
  2879. return [ 'fc-nonbusiness', 'fc-bgevent' ];
  2880. },
  2881. /* Handlers
  2882. ------------------------------------------------------------------------------------------------------------------*/
  2883. // Attaches event-element-related handlers to the container element and leverage bubbling
  2884. bindSegHandlers: function() {
  2885. var _this = this;
  2886. var view = this.view;
  2887. jQuery.each(
  2888. {
  2889. mouseenter: function(seg, ev) {
  2890. _this.triggerSegMouseover(seg, ev);
  2891. },
  2892. mouseleave: function(seg, ev) {
  2893. _this.triggerSegMouseout(seg, ev);
  2894. },
  2895. click: function(seg, ev) {
  2896. return view.trigger('eventClick', this, seg.event, ev); // can return `false` to cancel
  2897. },
  2898. mousedown: function(seg, ev) {
  2899. if (jQuery(ev.target).is('.fc-resizer') && view.isEventResizable(seg.event)) {
  2900. _this.segResizeMousedown(seg, ev, jQuery(ev.target).is('.fc-start-resizer'));
  2901. }
  2902. else if (view.isEventDraggable(seg.event)) {
  2903. _this.segDragMousedown(seg, ev);
  2904. }
  2905. }
  2906. },
  2907. function(name, func) {
  2908. // attach the handler to the container element and only listen for real event elements via bubbling
  2909. _this.el.on(name, '.fc-event-container > *', function(ev) {
  2910. var seg = jQuery(this).data('fc-seg'); // grab segment data. put there by View::renderEvents
  2911. // only call the handlers if there is not a drag/resize in progress
  2912. if (seg && !_this.isDraggingSeg && !_this.isResizingSeg) {
  2913. return func.call(this, seg, ev); // `this` will be the event element
  2914. }
  2915. });
  2916. }
  2917. );
  2918. },
  2919. // Updates internal state and triggers handlers for when an event element is moused over
  2920. triggerSegMouseover: function(seg, ev) {
  2921. if (!this.mousedOverSeg) {
  2922. this.mousedOverSeg = seg;
  2923. this.view.trigger('eventMouseover', seg.el[0], seg.event, ev);
  2924. }
  2925. },
  2926. // Updates internal state and triggers handlers for when an event element is moused out.
  2927. // Can be given no arguments, in which case it will mouseout the segment that was previously moused over.
  2928. triggerSegMouseout: function(seg, ev) {
  2929. ev = ev || {}; // if given no args, make a mock mouse event
  2930. if (this.mousedOverSeg) {
  2931. seg = seg || this.mousedOverSeg; // if given no args, use the currently moused-over segment
  2932. this.mousedOverSeg = null;
  2933. this.view.trigger('eventMouseout', seg.el[0], seg.event, ev);
  2934. }
  2935. },
  2936. /* Event Dragging
  2937. ------------------------------------------------------------------------------------------------------------------*/
  2938. // Called when the user does a mousedown on an event, which might lead to dragging.
  2939. // Generic enough to work with any type of Grid.
  2940. segDragMousedown: function(seg, ev) {
  2941. var _this = this;
  2942. var view = this.view;
  2943. var calendar = view.calendar;
  2944. var el = seg.el;
  2945. var event = seg.event;
  2946. var dropLocation; // zoned event date properties
  2947. // A clone of the original element that will move with the mouse
  2948. var mouseFollower = new MouseFollower(seg.el, {
  2949. parentEl: view.el,
  2950. opacity: view.opt('dragOpacity'),
  2951. revertDuration: view.opt('dragRevertDuration'),
  2952. zIndex: 2 // one above the .fc-view
  2953. });
  2954. // Tracks mouse movement over the *view's* coordinate map. Allows dragging and dropping between subcomponents
  2955. // of the view.
  2956. var dragListener = new HitDragListener(view, {
  2957. distance: 5,
  2958. scroll: view.opt('dragScroll'),
  2959. subjectEl: el,
  2960. subjectCenter: true,
  2961. listenStart: function(ev) {
  2962. mouseFollower.hide(); // don't show until we know this is a real drag
  2963. mouseFollower.start(ev);
  2964. },
  2965. dragStart: function(ev) {
  2966. _this.triggerSegMouseout(seg, ev); // ensure a mouseout on the manipulated event has been reported
  2967. _this.segDragStart(seg, ev);
  2968. view.hideEvent(event); // hide all event segments. our mouseFollower will take over
  2969. },
  2970. hitOver: function(hit, isOrig, origHit) {
  2971. // starting hit could be forced (DayGrid.limit)
  2972. if (seg.hit) {
  2973. origHit = seg.hit;
  2974. }
  2975. // since we are querying the parent view, might not belong to this grid
  2976. dropLocation = _this.computeEventDrop(
  2977. origHit.component.getHitSpan(origHit),
  2978. hit.component.getHitSpan(hit),
  2979. event
  2980. );
  2981. if (dropLocation && !calendar.isEventSpanAllowed(_this.eventToSpan(dropLocation), event)) {
  2982. disableCursor();
  2983. dropLocation = null;
  2984. }
  2985. // if a valid drop location, have the subclass render a visual indication
  2986. if (dropLocation && view.renderDrag(dropLocation, seg)) {
  2987. mouseFollower.hide(); // if the subclass is already using a mock event "helper", hide our own
  2988. }
  2989. else {
  2990. mouseFollower.show(); // otherwise, have the helper follow the mouse (no snapping)
  2991. }
  2992. if (isOrig) {
  2993. dropLocation = null; // needs to have moved hits to be a valid drop
  2994. }
  2995. },
  2996. hitOut: function() { // called before mouse moves to a different hit OR moved out of all hits
  2997. view.unrenderDrag(); // unrender whatever was done in renderDrag
  2998. mouseFollower.show(); // show in case we are moving out of all hits
  2999. dropLocation = null;
  3000. },
  3001. hitDone: function() { // Called after a hitOut OR before a dragStop
  3002. enableCursor();
  3003. },
  3004. dragStop: function(ev) {
  3005. // do revert animation if hasn't changed. calls a callback when finished (whether animation or not)
  3006. mouseFollower.stop(!dropLocation, function() {
  3007. view.unrenderDrag();
  3008. view.showEvent(event);
  3009. _this.segDragStop(seg, ev);
  3010. if (dropLocation) {
  3011. view.reportEventDrop(event, dropLocation, this.largeUnit, el, ev);
  3012. }
  3013. });
  3014. },
  3015. listenStop: function() {
  3016. mouseFollower.stop(); // put in listenStop in case there was a mousedown but the drag never started
  3017. }
  3018. });
  3019. dragListener.mousedown(ev); // start listening, which will eventually lead to a dragStart
  3020. },
  3021. // Called before event segment dragging starts
  3022. segDragStart: function(seg, ev) {
  3023. this.isDraggingSeg = true;
  3024. this.view.trigger('eventDragStart', seg.el[0], seg.event, ev, {}); // last argument is jqui dummy
  3025. },
  3026. // Called after event segment dragging stops
  3027. segDragStop: function(seg, ev) {
  3028. this.isDraggingSeg = false;
  3029. this.view.trigger('eventDragStop', seg.el[0], seg.event, ev, {}); // last argument is jqui dummy
  3030. },
  3031. // Given the spans an event drag began, and the span event was dropped, calculates the new zoned start/end/allDay
  3032. // values for the event. Subclasses may override and set additional properties to be used by renderDrag.
  3033. // A falsy returned value indicates an invalid drop.
  3034. // DOES NOT consider overlap/constraint.
  3035. computeEventDrop: function(startSpan, endSpan, event) {
  3036. var calendar = this.view.calendar;
  3037. var dragStart = startSpan.start;
  3038. var dragEnd = endSpan.start;
  3039. var delta;
  3040. var dropLocation; // zoned event date properties
  3041. if (dragStart.hasTime() === dragEnd.hasTime()) {
  3042. delta = this.diffDates(dragEnd, dragStart);
  3043. // if an all-day event was in a timed area and it was dragged to a different time,
  3044. // guarantee an end and adjust start/end to have times
  3045. if (event.allDay && durationHasTime(delta)) {
  3046. dropLocation = {
  3047. start: event.start.clone(),
  3048. end: calendar.getEventEnd(event), // will be an ambig day
  3049. allDay: false // for normalizeEventTimes
  3050. };
  3051. calendar.normalizeEventTimes(dropLocation);
  3052. }
  3053. // othewise, work off existing values
  3054. else {
  3055. dropLocation = {
  3056. start: event.start.clone(),
  3057. end: event.end ? event.end.clone() : null,
  3058. allDay: event.allDay // keep it the same
  3059. };
  3060. }
  3061. dropLocation.start.add(delta);
  3062. if (dropLocation.end) {
  3063. dropLocation.end.add(delta);
  3064. }
  3065. }
  3066. else {
  3067. // if switching from day <-> timed, start should be reset to the dropped date, and the end cleared
  3068. dropLocation = {
  3069. start: dragEnd.clone(),
  3070. end: null, // end should be cleared
  3071. allDay: !dragEnd.hasTime()
  3072. };
  3073. }
  3074. return dropLocation;
  3075. },
  3076. // Utility for apply dragOpacity to a jQuery set
  3077. applyDragOpacity: function(els) {
  3078. var opacity = this.view.opt('dragOpacity');
  3079. if (opacity != null) {
  3080. els.each(function(i, node) {
  3081. // Don't use jQuery (will set an IE filter), do it the old fashioned way.
  3082. // In IE8, a helper element will disappears if there's a filter.
  3083. node.style.opacity = opacity;
  3084. });
  3085. }
  3086. },
  3087. /* External Element Dragging
  3088. ------------------------------------------------------------------------------------------------------------------*/
  3089. // Called when a jQuery UI drag is initiated anywhere in the DOM
  3090. externalDragStart: function(ev, ui) {
  3091. var view = this.view;
  3092. var el;
  3093. var accept;
  3094. if (view.opt('droppable')) { // only listen if this setting is on
  3095. el = jQuery((ui ? ui.item : null) || ev.target);
  3096. // Test that the dragged element passes the dropAccept selector or filter function.
  3097. // FYI, the default is "*" (matches all)
  3098. accept = view.opt('dropAccept');
  3099. if (jQuery.isFunction(accept) ? accept.call(el[0], el) : el.is(accept)) {
  3100. if (!this.isDraggingExternal) { // prevent double-listening if fired twice
  3101. this.listenToExternalDrag(el, ev, ui);
  3102. }
  3103. }
  3104. }
  3105. },
  3106. // Called when a jQuery UI drag starts and it needs to be monitored for dropping
  3107. listenToExternalDrag: function(el, ev, ui) {
  3108. var _this = this;
  3109. var calendar = this.view.calendar;
  3110. var meta = getDraggedElMeta(el); // extra data about event drop, including possible event to create
  3111. var dropLocation; // a null value signals an unsuccessful drag
  3112. // listener that tracks mouse movement over date-associated pixel regions
  3113. var dragListener = new HitDragListener(this, {
  3114. listenStart: function() {
  3115. _this.isDraggingExternal = true;
  3116. },
  3117. hitOver: function(hit) {
  3118. dropLocation = _this.computeExternalDrop(
  3119. hit.component.getHitSpan(hit), // since we are querying the parent view, might not belong to this grid
  3120. meta
  3121. );
  3122. if ( // invalid hit?
  3123. dropLocation &&
  3124. !calendar.isExternalSpanAllowed(_this.eventToSpan(dropLocation), dropLocation, meta.eventProps)
  3125. ) {
  3126. disableCursor();
  3127. dropLocation = null;
  3128. }
  3129. if (dropLocation) {
  3130. _this.renderDrag(dropLocation); // called without a seg parameter
  3131. }
  3132. },
  3133. hitOut: function() {
  3134. dropLocation = null; // signal unsuccessful
  3135. },
  3136. hitDone: function() { // Called after a hitOut OR before a dragStop
  3137. enableCursor();
  3138. _this.unrenderDrag();
  3139. },
  3140. dragStop: function() {
  3141. if (dropLocation) { // element was dropped on a valid hit
  3142. _this.view.reportExternalDrop(meta, dropLocation, el, ev, ui);
  3143. }
  3144. },
  3145. listenStop: function() {
  3146. _this.isDraggingExternal = false;
  3147. }
  3148. });
  3149. dragListener.startDrag(ev); // start listening immediately
  3150. },
  3151. // Given a hit to be dropped upon, and misc data associated with the jqui drag (guaranteed to be a plain object),
  3152. // returns the zoned start/end dates for the event that would result from the hypothetical drop. end might be null.
  3153. // Returning a null value signals an invalid drop hit.
  3154. // DOES NOT consider overlap/constraint.
  3155. computeExternalDrop: function(span, meta) {
  3156. var calendar = this.view.calendar;
  3157. var dropLocation = {
  3158. start: calendar.applyTimezone(span.start), // simulate a zoned event start date
  3159. end: null
  3160. };
  3161. // if dropped on an all-day span, and element's metadata specified a time, set it
  3162. if (meta.startTime && !dropLocation.start.hasTime()) {
  3163. dropLocation.start.time(meta.startTime);
  3164. }
  3165. if (meta.duration) {
  3166. dropLocation.end = dropLocation.start.clone().add(meta.duration);
  3167. }
  3168. return dropLocation;
  3169. },
  3170. /* Drag Rendering (for both events and an external elements)
  3171. ------------------------------------------------------------------------------------------------------------------*/
  3172. // Renders a visual indication of an event or external element being dragged.
  3173. // `dropLocation` contains hypothetical start/end/allDay values the event would have if dropped. end can be null.
  3174. // `seg` is the internal segment object that is being dragged. If dragging an external element, `seg` is null.
  3175. // A truthy returned value indicates this method has rendered a helper element.
  3176. renderDrag: function(dropLocation, seg) {
  3177. // subclasses must implement
  3178. },
  3179. // Unrenders a visual indication of an event or external element being dragged
  3180. unrenderDrag: function() {
  3181. // subclasses must implement
  3182. },
  3183. /* Resizing
  3184. ------------------------------------------------------------------------------------------------------------------*/
  3185. // Called when the user does a mousedown on an event's resizer, which might lead to resizing.
  3186. // Generic enough to work with any type of Grid.
  3187. segResizeMousedown: function(seg, ev, isStart) {
  3188. var _this = this;
  3189. var view = this.view;
  3190. var calendar = view.calendar;
  3191. var el = seg.el;
  3192. var event = seg.event;
  3193. var eventEnd = calendar.getEventEnd(event);
  3194. var resizeLocation; // zoned event date properties. falsy if invalid resize
  3195. // Tracks mouse movement over the *grid's* coordinate map
  3196. var dragListener = new HitDragListener(this, {
  3197. distance: 5,
  3198. scroll: view.opt('dragScroll'),
  3199. subjectEl: el,
  3200. dragStart: function(ev) {
  3201. _this.triggerSegMouseout(seg, ev); // ensure a mouseout on the manipulated event has been reported
  3202. _this.segResizeStart(seg, ev);
  3203. },
  3204. hitOver: function(hit, isOrig, origHit) {
  3205. var origHitSpan = _this.getHitSpan(origHit);
  3206. var hitSpan = _this.getHitSpan(hit);
  3207. resizeLocation = isStart ?
  3208. _this.computeEventStartResize(origHitSpan, hitSpan, event) :
  3209. _this.computeEventEndResize(origHitSpan, hitSpan, event);
  3210. if (resizeLocation) {
  3211. if (!calendar.isEventSpanAllowed(_this.eventToSpan(resizeLocation), event)) {
  3212. disableCursor();
  3213. resizeLocation = null;
  3214. }
  3215. // no change? (TODO: how does this work with timezones?)
  3216. else if (resizeLocation.start.isSame(event.start) && resizeLocation.end.isSame(eventEnd)) {
  3217. resizeLocation = null;
  3218. }
  3219. }
  3220. if (resizeLocation) {
  3221. view.hideEvent(event);
  3222. _this.renderEventResize(resizeLocation, seg);
  3223. }
  3224. },
  3225. hitOut: function() { // called before mouse moves to a different hit OR moved out of all hits
  3226. resizeLocation = null;
  3227. },
  3228. hitDone: function() { // resets the rendering to show the original event
  3229. _this.unrenderEventResize();
  3230. view.showEvent(event);
  3231. enableCursor();
  3232. },
  3233. dragStop: function(ev) {
  3234. _this.segResizeStop(seg, ev);
  3235. if (resizeLocation) { // valid date to resize to?
  3236. view.reportEventResize(event, resizeLocation, this.largeUnit, el, ev);
  3237. }
  3238. }
  3239. });
  3240. dragListener.mousedown(ev); // start listening, which will eventually lead to a dragStart
  3241. },
  3242. // Called before event segment resizing starts
  3243. segResizeStart: function(seg, ev) {
  3244. this.isResizingSeg = true;
  3245. this.view.trigger('eventResizeStart', seg.el[0], seg.event, ev, {}); // last argument is jqui dummy
  3246. },
  3247. // Called after event segment resizing stops
  3248. segResizeStop: function(seg, ev) {
  3249. this.isResizingSeg = false;
  3250. this.view.trigger('eventResizeStop', seg.el[0], seg.event, ev, {}); // last argument is jqui dummy
  3251. },
  3252. // Returns new date-information for an event segment being resized from its start
  3253. computeEventStartResize: function(startSpan, endSpan, event) {
  3254. return this.computeEventResize('start', startSpan, endSpan, event);
  3255. },
  3256. // Returns new date-information for an event segment being resized from its end
  3257. computeEventEndResize: function(startSpan, endSpan, event) {
  3258. return this.computeEventResize('end', startSpan, endSpan, event);
  3259. },
  3260. // Returns new zoned date information for an event segment being resized from its start OR end
  3261. // `type` is either 'start' or 'end'.
  3262. // DOES NOT consider overlap/constraint.
  3263. computeEventResize: function(type, startSpan, endSpan, event) {
  3264. var calendar = this.view.calendar;
  3265. var delta = this.diffDates(endSpan[type], startSpan[type]);
  3266. var resizeLocation; // zoned event date properties
  3267. var defaultDuration;
  3268. // build original values to work from, guaranteeing a start and end
  3269. resizeLocation = {
  3270. start: event.start.clone(),
  3271. end: calendar.getEventEnd(event),
  3272. allDay: event.allDay
  3273. };
  3274. // if an all-day event was in a timed area and was resized to a time, adjust start/end to have times
  3275. if (resizeLocation.allDay && durationHasTime(delta)) {
  3276. resizeLocation.allDay = false;
  3277. calendar.normalizeEventTimes(resizeLocation);
  3278. }
  3279. resizeLocation[type].add(delta); // apply delta to start or end
  3280. // if the event was compressed too small, find a new reasonable duration for it
  3281. if (!resizeLocation.start.isBefore(resizeLocation.end)) {
  3282. defaultDuration =
  3283. this.minResizeDuration || // TODO: hack
  3284. (event.allDay ?
  3285. calendar.defaultAllDayEventDuration :
  3286. calendar.defaultTimedEventDuration);
  3287. if (type == 'start') { // resizing the start?
  3288. resizeLocation.start = resizeLocation.end.clone().subtract(defaultDuration);
  3289. }
  3290. else { // resizing the end?
  3291. resizeLocation.end = resizeLocation.start.clone().add(defaultDuration);
  3292. }
  3293. }
  3294. return resizeLocation;
  3295. },
  3296. // Renders a visual indication of an event being resized.
  3297. // `range` has the updated dates of the event. `seg` is the original segment object involved in the drag.
  3298. renderEventResize: function(range, seg) {
  3299. // subclasses must implement
  3300. },
  3301. // Unrenders a visual indication of an event being resized.
  3302. unrenderEventResize: function() {
  3303. // subclasses must implement
  3304. },
  3305. /* Rendering Utils
  3306. ------------------------------------------------------------------------------------------------------------------*/
  3307. // Compute the text that should be displayed on an event's element.
  3308. // `range` can be the Event object itself, or something range-like, with at least a `start`.
  3309. // If event times are disabled, or the event has no time, will return a blank string.
  3310. // If not specified, formatStr will default to the eventTimeFormat setting,
  3311. // and displayEnd will default to the displayEventEnd setting.
  3312. getEventTimeText: function(range, formatStr, displayEnd) {
  3313. if (formatStr == null) {
  3314. formatStr = this.eventTimeFormat;
  3315. }
  3316. if (displayEnd == null) {
  3317. displayEnd = this.displayEventEnd;
  3318. }
  3319. if (this.displayEventTime && range.start.hasTime()) {
  3320. if (displayEnd && range.end) {
  3321. return this.view.formatRange(range, formatStr);
  3322. }
  3323. else {
  3324. return range.start.format(formatStr);
  3325. }
  3326. }
  3327. return '';
  3328. },
  3329. // Generic utility for generating the HTML classNames for an event segment's element
  3330. getSegClasses: function(seg, isDraggable, isResizable) {
  3331. var event = seg.event;
  3332. var classes = [
  3333. 'fc-event',
  3334. seg.isStart ? 'fc-start' : 'fc-not-start',
  3335. seg.isEnd ? 'fc-end' : 'fc-not-end'
  3336. ].concat(
  3337. event.className,
  3338. event.source ? event.source.className : []
  3339. );
  3340. if (isDraggable) {
  3341. classes.push('fc-draggable');
  3342. }
  3343. if (isResizable) {
  3344. classes.push('fc-resizable');
  3345. }
  3346. return classes;
  3347. },
  3348. // Utility for generating event skin-related CSS properties
  3349. getSegSkinCss: function(seg) {
  3350. var event = seg.event;
  3351. var view = this.view;
  3352. var source = event.source || {};
  3353. var eventColor = event.color;
  3354. var sourceColor = source.color;
  3355. var optionColor = view.opt('eventColor');
  3356. return {
  3357. 'background-color':
  3358. event.backgroundColor ||
  3359. eventColor ||
  3360. source.backgroundColor ||
  3361. sourceColor ||
  3362. view.opt('eventBackgroundColor') ||
  3363. optionColor,
  3364. 'border-color':
  3365. event.borderColor ||
  3366. eventColor ||
  3367. source.borderColor ||
  3368. sourceColor ||
  3369. view.opt('eventBorderColor') ||
  3370. optionColor,
  3371. color:
  3372. event.textColor ||
  3373. source.textColor ||
  3374. view.opt('eventTextColor')
  3375. };
  3376. },
  3377. /* Converting events -> eventRange -> eventSpan -> eventSegs
  3378. ------------------------------------------------------------------------------------------------------------------*/
  3379. // Generates an array of segments for the given single event
  3380. // Can accept an event "location" as well (which only has start/end and no allDay)
  3381. eventToSegs: function(event) {
  3382. return this.eventsToSegs([ event ]);
  3383. },
  3384. eventToSpan: function(event) {
  3385. return this.eventToSpans(event)[0];
  3386. },
  3387. // Generates spans (always unzoned) for the given event.
  3388. // Does not do any inverting for inverse-background events.
  3389. // Can accept an event "location" as well (which only has start/end and no allDay)
  3390. eventToSpans: function(event) {
  3391. var range = this.eventToRange(event);
  3392. return this.eventRangeToSpans(range, event);
  3393. },
  3394. // Converts an array of event objects into an array of event segment objects.
  3395. // A custom `segSliceFunc` may be given for arbitrarily slicing up events.
  3396. // Doesn't guarantee an order for the resulting array.
  3397. eventsToSegs: function(allEvents, segSliceFunc) {
  3398. var _this = this;
  3399. var eventsById = groupEventsById(allEvents);
  3400. var segs = [];
  3401. jQuery.each(eventsById, function(id, events) {
  3402. var ranges = [];
  3403. var i;
  3404. for (i = 0; i < events.length; i++) {
  3405. ranges.push(_this.eventToRange(events[i]));
  3406. }
  3407. // inverse-background events (utilize only the first event in calculations)
  3408. if (isInverseBgEvent(events[0])) {
  3409. ranges = _this.invertRanges(ranges);
  3410. for (i = 0; i < ranges.length; i++) {
  3411. segs.push.apply(segs, // append to
  3412. _this.eventRangeToSegs(ranges[i], events[0], segSliceFunc));
  3413. }
  3414. }
  3415. // normal event ranges
  3416. else {
  3417. for (i = 0; i < ranges.length; i++) {
  3418. segs.push.apply(segs, // append to
  3419. _this.eventRangeToSegs(ranges[i], events[i], segSliceFunc));
  3420. }
  3421. }
  3422. });
  3423. return segs;
  3424. },
  3425. // Generates the unzoned start/end dates an event appears to occupy
  3426. // Can accept an event "location" as well (which only has start/end and no allDay)
  3427. eventToRange: function(event) {
  3428. return {
  3429. start: event.start.clone().stripZone(),
  3430. end: (
  3431. event.end ?
  3432. event.end.clone() :
  3433. // derive the end from the start and allDay. compute allDay if necessary
  3434. this.view.calendar.getDefaultEventEnd(
  3435. event.allDay != null ?
  3436. event.allDay :
  3437. !event.start.hasTime(),
  3438. event.start
  3439. )
  3440. ).stripZone()
  3441. };
  3442. },
  3443. // Given an event's range (unzoned start/end), and the event itself,
  3444. // slice into segments (using the segSliceFunc function if specified)
  3445. eventRangeToSegs: function(range, event, segSliceFunc) {
  3446. var spans = this.eventRangeToSpans(range, event);
  3447. var segs = [];
  3448. var i;
  3449. for (i = 0; i < spans.length; i++) {
  3450. segs.push.apply(segs, // append to
  3451. this.eventSpanToSegs(spans[i], event, segSliceFunc));
  3452. }
  3453. return segs;
  3454. },
  3455. // Given an event's unzoned date range, return an array of "span" objects.
  3456. // Subclasses can override.
  3457. eventRangeToSpans: function(range, event) {
  3458. return [ jQuery.extend({}, range) ]; // copy into a single-item array
  3459. },
  3460. // Given an event's span (unzoned start/end and other misc data), and the event itself,
  3461. // slices into segments and attaches event-derived properties to them.
  3462. eventSpanToSegs: function(span, event, segSliceFunc) {
  3463. var segs = segSliceFunc ? segSliceFunc(span) : this.spanToSegs(span);
  3464. var i, seg;
  3465. for (i = 0; i < segs.length; i++) {
  3466. seg = segs[i];
  3467. seg.event = event;
  3468. seg.eventStartMS = +span.start; // TODO: not the best name after making spans unzoned
  3469. seg.eventDurationMS = span.end - span.start;
  3470. }
  3471. return segs;
  3472. },
  3473. // Produces a new array of range objects that will cover all the time NOT covered by the given ranges.
  3474. // SIDE EFFECT: will mutate the given array and will use its date references.
  3475. invertRanges: function(ranges) {
  3476. var view = this.view;
  3477. var viewStart = view.start.clone(); // need a copy
  3478. var viewEnd = view.end.clone(); // need a copy
  3479. var inverseRanges = [];
  3480. var start = viewStart; // the end of the previous range. the start of the new range
  3481. var i, range;
  3482. // ranges need to be in order. required for our date-walking algorithm
  3483. ranges.sort(compareRanges);
  3484. for (i = 0; i < ranges.length; i++) {
  3485. range = ranges[i];
  3486. // add the span of time before the event (if there is any)
  3487. if (range.start > start) { // compare millisecond time (skip any ambig logic)
  3488. inverseRanges.push({
  3489. start: start,
  3490. end: range.start
  3491. });
  3492. }
  3493. start = range.end;
  3494. }
  3495. // add the span of time after the last event (if there is any)
  3496. if (start < viewEnd) { // compare millisecond time (skip any ambig logic)
  3497. inverseRanges.push({
  3498. start: start,
  3499. end: viewEnd
  3500. });
  3501. }
  3502. return inverseRanges;
  3503. },
  3504. sortEventSegs: function(segs) {
  3505. segs.sort(proxy(this, 'compareEventSegs'));
  3506. },
  3507. // A cmp function for determining which segments should take visual priority
  3508. compareEventSegs: function(seg1, seg2) {
  3509. return seg1.eventStartMS - seg2.eventStartMS || // earlier events go first
  3510. seg2.eventDurationMS - seg1.eventDurationMS || // tie? longer events go first
  3511. seg2.event.allDay - seg1.event.allDay || // tie? put all-day events first (booleans cast to 0/1)
  3512. compareByFieldSpecs(seg1.event, seg2.event, this.view.eventOrderSpecs);
  3513. }
  3514. });
  3515. /* Utilities
  3516. ----------------------------------------------------------------------------------------------------------------------*/
  3517. function isBgEvent(event) { // returns true if background OR inverse-background
  3518. var rendering = getEventRendering(event);
  3519. return rendering === 'background' || rendering === 'inverse-background';
  3520. }
  3521. FC.isBgEvent = isBgEvent; // export
  3522. function isInverseBgEvent(event) {
  3523. return getEventRendering(event) === 'inverse-background';
  3524. }
  3525. function getEventRendering(event) {
  3526. return firstDefined((event.source || {}).rendering, event.rendering);
  3527. }
  3528. function groupEventsById(events) {
  3529. var eventsById = {};
  3530. var i, event;
  3531. for (i = 0; i < events.length; i++) {
  3532. event = events[i];
  3533. (eventsById[event._id] || (eventsById[event._id] = [])).push(event);
  3534. }
  3535. return eventsById;
  3536. }
  3537. // A cmp function for determining which non-inverted "ranges" (see above) happen earlier
  3538. function compareRanges(range1, range2) {
  3539. return range1.start - range2.start; // earlier ranges go first
  3540. }
  3541. /* External-Dragging-Element Data
  3542. ----------------------------------------------------------------------------------------------------------------------*/
  3543. // Require all HTML5 data-* attributes used by FullCalendar to have this prefix.
  3544. // A value of '' will query attributes like data-event. A value of 'fc' will query attributes like data-fc-event.
  3545. FC.dataAttrPrefix = '';
  3546. // Given a jQuery element that might represent a dragged FullCalendar event, returns an intermediate data structure
  3547. // to be used for Event Object creation.
  3548. // A defined `.eventProps`, even when empty, indicates that an event should be created.
  3549. function getDraggedElMeta(el) {
  3550. var prefix = FC.dataAttrPrefix;
  3551. var eventProps; // properties for creating the event, not related to date/time
  3552. var startTime; // a Duration
  3553. var duration;
  3554. var stick;
  3555. if (prefix) { prefix += '-'; }
  3556. eventProps = el.data(prefix + 'event') || null;
  3557. if (eventProps) {
  3558. if (typeof eventProps === 'object') {
  3559. eventProps = jQuery.extend({}, eventProps); // make a copy
  3560. }
  3561. else { // something like 1 or true. still signal event creation
  3562. eventProps = {};
  3563. }
  3564. // pluck special-cased date/time properties
  3565. startTime = eventProps.start;
  3566. if (startTime == null) { startTime = eventProps.time; } // accept 'time' as well
  3567. duration = eventProps.duration;
  3568. stick = eventProps.stick;
  3569. delete eventProps.start;
  3570. delete eventProps.time;
  3571. delete eventProps.duration;
  3572. delete eventProps.stick;
  3573. }
  3574. // fallback to standalone attribute values for each of the date/time properties
  3575. if (startTime == null) { startTime = el.data(prefix + 'start'); }
  3576. if (startTime == null) { startTime = el.data(prefix + 'time'); } // accept 'time' as well
  3577. if (duration == null) { duration = el.data(prefix + 'duration'); }
  3578. if (stick == null) { stick = el.data(prefix + 'stick'); }
  3579. // massage into correct data types
  3580. startTime = startTime != null ? moment.duration(startTime) : null;
  3581. duration = duration != null ? moment.duration(duration) : null;
  3582. stick = Boolean(stick);
  3583. return { eventProps: eventProps, startTime: startTime, duration: duration, stick: stick };
  3584. }
  3585. ;;
  3586. /*
  3587. A set of rendering and date-related methods for a visual component comprised of one or more rows of day columns.
  3588. Prerequisite: the object being mixed into needs to be a *Grid*
  3589. */
  3590. var DayTableMixin = FC.DayTableMixin = {
  3591. breakOnWeeks: false, // should create a new row for each week?
  3592. dayDates: null, // whole-day dates for each column. left to right
  3593. dayIndices: null, // for each day from start, the offset
  3594. daysPerRow: null,
  3595. rowCnt: null,
  3596. colCnt: null,
  3597. colHeadFormat: null,
  3598. // Populates internal variables used for date calculation and rendering
  3599. updateDayTable: function() {
  3600. var view = this.view;
  3601. var date = this.start.clone();
  3602. var dayIndex = -1;
  3603. var dayIndices = [];
  3604. var dayDates = [];
  3605. var daysPerRow;
  3606. var firstDay;
  3607. var rowCnt;
  3608. while (date.isBefore(this.end)) { // loop each day from start to end
  3609. if (view.isHiddenDay(date)) {
  3610. dayIndices.push(dayIndex + 0.5); // mark that it's between indices
  3611. }
  3612. else {
  3613. dayIndex++;
  3614. dayIndices.push(dayIndex);
  3615. dayDates.push(date.clone());
  3616. }
  3617. date.add(1, 'days');
  3618. }
  3619. if (this.breakOnWeeks) {
  3620. // count columns until the day-of-week repeats
  3621. firstDay = dayDates[0].day();
  3622. for (daysPerRow = 1; daysPerRow < dayDates.length; daysPerRow++) {
  3623. if (dayDates[daysPerRow].day() == firstDay) {
  3624. break;
  3625. }
  3626. }
  3627. rowCnt = Math.ceil(dayDates.length / daysPerRow);
  3628. }
  3629. else {
  3630. rowCnt = 1;
  3631. daysPerRow = dayDates.length;
  3632. }
  3633. this.dayDates = dayDates;
  3634. this.dayIndices = dayIndices;
  3635. this.daysPerRow = daysPerRow;
  3636. this.rowCnt = rowCnt;
  3637. this.updateDayTableCols();
  3638. },
  3639. // Computes and assigned the colCnt property and updates any options that may be computed from it
  3640. updateDayTableCols: function() {
  3641. this.colCnt = this.computeColCnt();
  3642. this.colHeadFormat = this.view.opt('columnFormat') || this.computeColHeadFormat();
  3643. },
  3644. // Determines how many columns there should be in the table
  3645. computeColCnt: function() {
  3646. return this.daysPerRow;
  3647. },
  3648. // Computes the ambiguously-timed moment for the given cell
  3649. getCellDate: function(row, col) {
  3650. return this.dayDates[
  3651. this.getCellDayIndex(row, col)
  3652. ].clone();
  3653. },
  3654. // Computes the ambiguously-timed date range for the given cell
  3655. getCellRange: function(row, col) {
  3656. var start = this.getCellDate(row, col);
  3657. var end = start.clone().add(1, 'days');
  3658. return { start: start, end: end };
  3659. },
  3660. // Returns the number of day cells, chronologically, from the first of the grid (0-based)
  3661. getCellDayIndex: function(row, col) {
  3662. return row * this.daysPerRow + this.getColDayIndex(col);
  3663. },
  3664. // Returns the numner of day cells, chronologically, from the first cell in *any given row*
  3665. getColDayIndex: function(col) {
  3666. if (this.isRTL) {
  3667. return this.colCnt - 1 - col;
  3668. }
  3669. else {
  3670. return col;
  3671. }
  3672. },
  3673. // Given a date, returns its chronolocial cell-index from the first cell of the grid.
  3674. // If the date lies between cells (because of hiddenDays), returns a floating-point value between offsets.
  3675. // If before the first offset, returns a negative number.
  3676. // If after the last offset, returns an offset past the last cell offset.
  3677. // Only works for *start* dates of cells. Will not work for exclusive end dates for cells.
  3678. getDateDayIndex: function(date) {
  3679. var dayIndices = this.dayIndices;
  3680. var dayOffset = date.diff(this.start, 'days');
  3681. if (dayOffset < 0) {
  3682. return dayIndices[0] - 1;
  3683. }
  3684. else if (dayOffset >= dayIndices.length) {
  3685. return dayIndices[dayIndices.length - 1] + 1;
  3686. }
  3687. else {
  3688. return dayIndices[dayOffset];
  3689. }
  3690. },
  3691. /* Options
  3692. ------------------------------------------------------------------------------------------------------------------*/
  3693. // Computes a default column header formatting string if `colFormat` is not explicitly defined
  3694. computeColHeadFormat: function() {
  3695. // if more than one week row, or if there are a lot of columns with not much space,
  3696. // put just the day numbers will be in each cell
  3697. if (this.rowCnt > 1 || this.colCnt > 10) {
  3698. return 'ddd'; // "Sat"
  3699. }
  3700. // multiple days, so full single date string WON'T be in title text
  3701. else if (this.colCnt > 1) {
  3702. return this.view.opt('dayOfMonthFormat'); // "Sat 12/10"
  3703. }
  3704. // single day, so full single date string will probably be in title text
  3705. else {
  3706. return 'dddd'; // "Saturday"
  3707. }
  3708. },
  3709. /* Slicing
  3710. ------------------------------------------------------------------------------------------------------------------*/
  3711. // Slices up a date range into a segment for every week-row it intersects with
  3712. sliceRangeByRow: function(range) {
  3713. var daysPerRow = this.daysPerRow;
  3714. var normalRange = this.view.computeDayRange(range); // make whole-day range, considering nextDayThreshold
  3715. var rangeFirst = this.getDateDayIndex(normalRange.start); // inclusive first index
  3716. var rangeLast = this.getDateDayIndex(normalRange.end.clone().subtract(1, 'days')); // inclusive last index
  3717. var segs = [];
  3718. var row;
  3719. var rowFirst, rowLast; // inclusive day-index range for current row
  3720. var segFirst, segLast; // inclusive day-index range for segment
  3721. for (row = 0; row < this.rowCnt; row++) {
  3722. rowFirst = row * daysPerRow;
  3723. rowLast = rowFirst + daysPerRow - 1;
  3724. // intersect segment's offset range with the row's
  3725. segFirst = Math.max(rangeFirst, rowFirst);
  3726. segLast = Math.min(rangeLast, rowLast);
  3727. // deal with in-between indices
  3728. segFirst = Math.ceil(segFirst); // in-between starts round to next cell
  3729. segLast = Math.floor(segLast); // in-between ends round to prev cell
  3730. if (segFirst <= segLast) { // was there any intersection with the current row?
  3731. segs.push({
  3732. row: row,
  3733. // normalize to start of row
  3734. firstRowDayIndex: segFirst - rowFirst,
  3735. lastRowDayIndex: segLast - rowFirst,
  3736. // must be matching integers to be the segment's start/end
  3737. isStart: segFirst === rangeFirst,
  3738. isEnd: segLast === rangeLast
  3739. });
  3740. }
  3741. }
  3742. return segs;
  3743. },
  3744. // Slices up a date range into a segment for every day-cell it intersects with.
  3745. // TODO: make more DRY with sliceRangeByRow somehow.
  3746. sliceRangeByDay: function(range) {
  3747. var daysPerRow = this.daysPerRow;
  3748. var normalRange = this.view.computeDayRange(range); // make whole-day range, considering nextDayThreshold
  3749. var rangeFirst = this.getDateDayIndex(normalRange.start); // inclusive first index
  3750. var rangeLast = this.getDateDayIndex(normalRange.end.clone().subtract(1, 'days')); // inclusive last index
  3751. var segs = [];
  3752. var row;
  3753. var rowFirst, rowLast; // inclusive day-index range for current row
  3754. var i;
  3755. var segFirst, segLast; // inclusive day-index range for segment
  3756. for (row = 0; row < this.rowCnt; row++) {
  3757. rowFirst = row * daysPerRow;
  3758. rowLast = rowFirst + daysPerRow - 1;
  3759. for (i = rowFirst; i <= rowLast; i++) {
  3760. // intersect segment's offset range with the row's
  3761. segFirst = Math.max(rangeFirst, i);
  3762. segLast = Math.min(rangeLast, i);
  3763. // deal with in-between indices
  3764. segFirst = Math.ceil(segFirst); // in-between starts round to next cell
  3765. segLast = Math.floor(segLast); // in-between ends round to prev cell
  3766. if (segFirst <= segLast) { // was there any intersection with the current row?
  3767. segs.push({
  3768. row: row,
  3769. // normalize to start of row
  3770. firstRowDayIndex: segFirst - rowFirst,
  3771. lastRowDayIndex: segLast - rowFirst,
  3772. // must be matching integers to be the segment's start/end
  3773. isStart: segFirst === rangeFirst,
  3774. isEnd: segLast === rangeLast
  3775. });
  3776. }
  3777. }
  3778. }
  3779. return segs;
  3780. },
  3781. /* Header Rendering
  3782. ------------------------------------------------------------------------------------------------------------------*/
  3783. renderHeadHtml: function() {
  3784. var view = this.view;
  3785. return '' +
  3786. '<div class="fc-row ' + view.widgetHeaderClass + '">' +
  3787. '<table>' +
  3788. '<thead>' +
  3789. this.renderHeadTrHtml() +
  3790. '</thead>' +
  3791. '</table>' +
  3792. '</div>';
  3793. },
  3794. renderHeadIntroHtml: function() {
  3795. return this.renderIntroHtml(); // fall back to generic
  3796. },
  3797. renderHeadTrHtml: function() {
  3798. return '' +
  3799. '<tr>' +
  3800. (this.isRTL ? '' : this.renderHeadIntroHtml()) +
  3801. this.renderHeadDateCellsHtml() +
  3802. (this.isRTL ? this.renderHeadIntroHtml() : '') +
  3803. '</tr>';
  3804. },
  3805. renderHeadDateCellsHtml: function() {
  3806. var htmls = [];
  3807. var col, date;
  3808. for (col = 0; col < this.colCnt; col++) {
  3809. date = this.getCellDate(0, col);
  3810. htmls.push(this.renderHeadDateCellHtml(date));
  3811. }
  3812. return htmls.join('');
  3813. },
  3814. // TODO: when internalApiVersion, accept an object for HTML attributes
  3815. // (colspan should be no different)
  3816. renderHeadDateCellHtml: function(date, colspan, otherAttrs) {
  3817. var view = this.view;
  3818. return '' +
  3819. '<th class="fc-day-header ' + view.widgetHeaderClass + ' fc-' + dayIDs[date.day()] + '"' +
  3820. (this.rowCnt == 1 ?
  3821. ' data-date="' + date.format('YYYY-MM-DD') + '"' :
  3822. '') +
  3823. (colspan > 1 ?
  3824. ' colspan="' + colspan + '"' :
  3825. '') +
  3826. (otherAttrs ?
  3827. ' ' + otherAttrs :
  3828. '') +
  3829. '>' +
  3830. htmlEscape(date.format(this.colHeadFormat)) +
  3831. '</th>';
  3832. },
  3833. /* Background Rendering
  3834. ------------------------------------------------------------------------------------------------------------------*/
  3835. renderBgTrHtml: function(row) {
  3836. return '' +
  3837. '<tr>' +
  3838. (this.isRTL ? '' : this.renderBgIntroHtml(row)) +
  3839. this.renderBgCellsHtml(row) +
  3840. (this.isRTL ? this.renderBgIntroHtml(row) : '') +
  3841. '</tr>';
  3842. },
  3843. renderBgIntroHtml: function(row) {
  3844. return this.renderIntroHtml(); // fall back to generic
  3845. },
  3846. renderBgCellsHtml: function(row) {
  3847. var htmls = [];
  3848. var col, date;
  3849. for (col = 0; col < this.colCnt; col++) {
  3850. date = this.getCellDate(row, col);
  3851. htmls.push(this.renderBgCellHtml(date));
  3852. }
  3853. return htmls.join('');
  3854. },
  3855. renderBgCellHtml: function(date, otherAttrs) {
  3856. var view = this.view;
  3857. var classes = this.getDayClasses(date);
  3858. classes.unshift('fc-day', view.widgetContentClass);
  3859. return '<td class="' + classes.join(' ') + '"' +
  3860. ' data-date="' + date.format('YYYY-MM-DD') + '"' + // if date has a time, won't format it
  3861. (otherAttrs ?
  3862. ' ' + otherAttrs :
  3863. '') +
  3864. '></td>';
  3865. },
  3866. /* Generic
  3867. ------------------------------------------------------------------------------------------------------------------*/
  3868. // Generates the default HTML intro for any row. User classes should override
  3869. renderIntroHtml: function() {
  3870. },
  3871. // TODO: a generic method for dealing with <tr>, RTL, intro
  3872. // when increment internalApiVersion
  3873. // wrapTr (scheduler)
  3874. /* Utils
  3875. ------------------------------------------------------------------------------------------------------------------*/
  3876. // Applies the generic "intro" and "outro" HTML to the given cells.
  3877. // Intro means the leftmost cell when the calendar is LTR and the rightmost cell when RTL. Vice-versa for outro.
  3878. bookendCells: function(trEl) {
  3879. var introHtml = this.renderIntroHtml();
  3880. if (introHtml) {
  3881. if (this.isRTL) {
  3882. trEl.append(introHtml);
  3883. }
  3884. else {
  3885. trEl.prepend(introHtml);
  3886. }
  3887. }
  3888. }
  3889. };
  3890. ;;
  3891. /* A component that renders a grid of whole-days that runs horizontally. There can be multiple rows, one per week.
  3892. ----------------------------------------------------------------------------------------------------------------------*/
  3893. var DayGrid = FC.DayGrid = Grid.extend(DayTableMixin, {
  3894. numbersVisible: false, // should render a row for day/week numbers? set by outside view. TODO: make internal
  3895. bottomCoordPadding: 0, // hack for extending the hit area for the last row of the coordinate grid
  3896. rowEls: null, // set of fake row elements
  3897. cellEls: null, // set of whole-day elements comprising the row's background
  3898. helperEls: null, // set of cell skeleton elements for rendering the mock event "helper"
  3899. rowCoordCache: null,
  3900. colCoordCache: null,
  3901. // Renders the rows and columns into the component's `this.el`, which should already be assigned.
  3902. // isRigid determins whether the individual rows should ignore the contents and be a constant height.
  3903. // Relies on the view's colCnt and rowCnt. In the future, this component should probably be self-sufficient.
  3904. renderDates: function(isRigid) {
  3905. var view = this.view;
  3906. var rowCnt = this.rowCnt;
  3907. var colCnt = this.colCnt;
  3908. var html = '';
  3909. var row;
  3910. var col;
  3911. for (row = 0; row < rowCnt; row++) {
  3912. html += this.renderDayRowHtml(row, isRigid);
  3913. }
  3914. this.el.html(html);
  3915. this.rowEls = this.el.find('.fc-row');
  3916. this.cellEls = this.el.find('.fc-day');
  3917. this.rowCoordCache = new CoordCache({
  3918. els: this.rowEls,
  3919. isVertical: true
  3920. });
  3921. this.colCoordCache = new CoordCache({
  3922. els: this.cellEls.slice(0, this.colCnt), // only the first row
  3923. isHorizontal: true
  3924. });
  3925. // trigger dayRender with each cell's element
  3926. for (row = 0; row < rowCnt; row++) {
  3927. for (col = 0; col < colCnt; col++) {
  3928. view.trigger(
  3929. 'dayRender',
  3930. null,
  3931. this.getCellDate(row, col),
  3932. this.getCellEl(row, col)
  3933. );
  3934. }
  3935. }
  3936. },
  3937. unrenderDates: function() {
  3938. this.removeSegPopover();
  3939. },
  3940. renderBusinessHours: function() {
  3941. var events = this.view.calendar.getBusinessHoursEvents(true); // wholeDay=true
  3942. var segs = this.eventsToSegs(events);
  3943. this.renderFill('businessHours', segs, 'bgevent');
  3944. },
  3945. // Generates the HTML for a single row, which is a div that wraps a table.
  3946. // `row` is the row number.
  3947. renderDayRowHtml: function(row, isRigid) {
  3948. var view = this.view;
  3949. var classes = [ 'fc-row', 'fc-week', view.widgetContentClass ];
  3950. if (isRigid) {
  3951. classes.push('fc-rigid');
  3952. }
  3953. return '' +
  3954. '<div class="' + classes.join(' ') + '">' +
  3955. '<div class="fc-bg">' +
  3956. '<table>' +
  3957. this.renderBgTrHtml(row) +
  3958. '</table>' +
  3959. '</div>' +
  3960. '<div class="fc-content-skeleton">' +
  3961. '<table>' +
  3962. (this.numbersVisible ?
  3963. '<thead>' +
  3964. this.renderNumberTrHtml(row) +
  3965. '</thead>' :
  3966. ''
  3967. ) +
  3968. '</table>' +
  3969. '</div>' +
  3970. '</div>';
  3971. },
  3972. /* Grid Number Rendering
  3973. ------------------------------------------------------------------------------------------------------------------*/
  3974. renderNumberTrHtml: function(row) {
  3975. return '' +
  3976. '<tr>' +
  3977. (this.isRTL ? '' : this.renderNumberIntroHtml(row)) +
  3978. this.renderNumberCellsHtml(row) +
  3979. (this.isRTL ? this.renderNumberIntroHtml(row) : '') +
  3980. '</tr>';
  3981. },
  3982. renderNumberIntroHtml: function(row) {
  3983. return this.renderIntroHtml();
  3984. },
  3985. renderNumberCellsHtml: function(row) {
  3986. var htmls = [];
  3987. var col, date;
  3988. for (col = 0; col < this.colCnt; col++) {
  3989. date = this.getCellDate(row, col);
  3990. htmls.push(this.renderNumberCellHtml(date));
  3991. }
  3992. return htmls.join('');
  3993. },
  3994. // Generates the HTML for the <td>s of the "number" row in the DayGrid's content skeleton.
  3995. // The number row will only exist if either day numbers or week numbers are turned on.
  3996. renderNumberCellHtml: function(date) {
  3997. var classes;
  3998. if (!this.view.dayNumbersVisible) { // if there are week numbers but not day numbers
  3999. return '<td/>'; // will create an empty space above events :(
  4000. }
  4001. classes = this.getDayClasses(date);
  4002. classes.unshift('fc-day-number');
  4003. if( this.view.opt("rendingNumberCellFun") ){
  4004. var str = this.view.opt("rendingNumberCellFun").call(this,date,date.format(),date.date());
  4005. return '<td class="' + classes.join(' ') + '" data-date="' + date.format() + '">' +
  4006. date.date() + (str ? str : '') +
  4007. '</td>'
  4008. }else{
  4009. return '' +
  4010. '<td class="' + classes.join(' ') + '" data-date="' + date.format() + '">' +
  4011. date.date() +
  4012. '</td>';
  4013. }
  4014. },
  4015. /* Options
  4016. ------------------------------------------------------------------------------------------------------------------*/
  4017. // Computes a default event time formatting string if `timeFormat` is not explicitly defined
  4018. computeEventTimeFormat: function() {
  4019. return this.view.opt('extraSmallTimeFormat'); // like "6p" or "6:30p"
  4020. },
  4021. // Computes a default `displayEventEnd` value if one is not expliclty defined
  4022. computeDisplayEventEnd: function() {
  4023. return this.colCnt == 1; // we'll likely have space if there's only one day
  4024. },
  4025. /* Dates
  4026. ------------------------------------------------------------------------------------------------------------------*/
  4027. rangeUpdated: function() {
  4028. this.updateDayTable();
  4029. },
  4030. // Slices up the given span (unzoned start/end with other misc data) into an array of segments
  4031. spanToSegs: function(span) {
  4032. var segs = this.sliceRangeByRow(span);
  4033. var i, seg;
  4034. for (i = 0; i < segs.length; i++) {
  4035. seg = segs[i];
  4036. if (this.isRTL) {
  4037. seg.leftCol = this.daysPerRow - 1 - seg.lastRowDayIndex;
  4038. seg.rightCol = this.daysPerRow - 1 - seg.firstRowDayIndex;
  4039. }
  4040. else {
  4041. seg.leftCol = seg.firstRowDayIndex;
  4042. seg.rightCol = seg.lastRowDayIndex;
  4043. }
  4044. }
  4045. return segs;
  4046. },
  4047. /* Hit System
  4048. ------------------------------------------------------------------------------------------------------------------*/
  4049. prepareHits: function() {
  4050. this.colCoordCache.build();
  4051. this.rowCoordCache.build();
  4052. this.rowCoordCache.bottoms[this.rowCnt - 1] += this.bottomCoordPadding; // hack
  4053. },
  4054. releaseHits: function() {
  4055. this.colCoordCache.clear();
  4056. this.rowCoordCache.clear();
  4057. },
  4058. queryHit: function(leftOffset, topOffset) {
  4059. var col = this.colCoordCache.getHorizontalIndex(leftOffset);
  4060. var row = this.rowCoordCache.getVerticalIndex(topOffset);
  4061. if (row != null && col != null) {
  4062. return this.getCellHit(row, col);
  4063. }
  4064. },
  4065. getHitSpan: function(hit) {
  4066. return this.getCellRange(hit.row, hit.col);
  4067. },
  4068. getHitEl: function(hit) {
  4069. return this.getCellEl(hit.row, hit.col);
  4070. },
  4071. /* Cell System
  4072. ------------------------------------------------------------------------------------------------------------------*/
  4073. // FYI: the first column is the leftmost column, regardless of date
  4074. getCellHit: function(row, col) {
  4075. return {
  4076. row: row,
  4077. col: col,
  4078. component: this, // needed unfortunately :(
  4079. left: this.colCoordCache.getLeftOffset(col),
  4080. right: this.colCoordCache.getRightOffset(col),
  4081. top: this.rowCoordCache.getTopOffset(row),
  4082. bottom: this.rowCoordCache.getBottomOffset(row)
  4083. };
  4084. },
  4085. getCellEl: function(row, col) {
  4086. return this.cellEls.eq(row * this.colCnt + col);
  4087. },
  4088. /* Event Drag Visualization
  4089. ------------------------------------------------------------------------------------------------------------------*/
  4090. // TODO: move to DayGrid.event, similar to what we did with Grid's drag methods
  4091. // Renders a visual indication of an event or external element being dragged.
  4092. // `eventLocation` has zoned start and end (optional)
  4093. renderDrag: function(eventLocation, seg) {
  4094. // always render a highlight underneath
  4095. this.renderHighlight(this.eventToSpan(eventLocation));
  4096. // if a segment from the same calendar but another component is being dragged, render a helper event
  4097. if (seg && !seg.el.closest(this.el).length) {
  4098. this.renderEventLocationHelper(eventLocation, seg);
  4099. this.applyDragOpacity(this.helperEls);
  4100. return true; // a helper has been rendered
  4101. }
  4102. },
  4103. // Unrenders any visual indication of a hovering event
  4104. unrenderDrag: function() {
  4105. this.unrenderHighlight();
  4106. this.unrenderHelper();
  4107. },
  4108. /* Event Resize Visualization
  4109. ------------------------------------------------------------------------------------------------------------------*/
  4110. // Renders a visual indication of an event being resized
  4111. renderEventResize: function(eventLocation, seg) {
  4112. this.renderHighlight(this.eventToSpan(eventLocation));
  4113. this.renderEventLocationHelper(eventLocation, seg);
  4114. },
  4115. // Unrenders a visual indication of an event being resized
  4116. unrenderEventResize: function() {
  4117. this.unrenderHighlight();
  4118. this.unrenderHelper();
  4119. },
  4120. /* Event Helper
  4121. ------------------------------------------------------------------------------------------------------------------*/
  4122. // Renders a mock "helper" event. `sourceSeg` is the associated internal segment object. It can be null.
  4123. renderHelper: function(event, sourceSeg) {
  4124. var helperNodes = [];
  4125. var segs = this.eventToSegs(event);
  4126. var rowStructs;
  4127. segs = this.renderFgSegEls(segs); // assigns each seg's el and returns a subset of segs that were rendered
  4128. rowStructs = this.renderSegRows(segs);
  4129. // inject each new event skeleton into each associated row
  4130. this.rowEls.each(function(row, rowNode) {
  4131. var rowEl = jQuery(rowNode); // the .fc-row
  4132. var skeletonEl = jQuery('<div class="fc-helper-skeleton"><table/></div>'); // will be absolutely positioned
  4133. var skeletonTop;
  4134. // If there is an original segment, match the top position. Otherwise, put it at the row's top level
  4135. if (sourceSeg && sourceSeg.row === row) {
  4136. skeletonTop = sourceSeg.el.position().top;
  4137. }
  4138. else {
  4139. skeletonTop = rowEl.find('.fc-content-skeleton tbody').position().top;
  4140. }
  4141. skeletonEl.css('top', skeletonTop)
  4142. .find('table')
  4143. .append(rowStructs[row].tbodyEl);
  4144. rowEl.append(skeletonEl);
  4145. helperNodes.push(skeletonEl[0]);
  4146. });
  4147. this.helperEls = jQuery(helperNodes); // array -> jQuery set
  4148. },
  4149. // Unrenders any visual indication of a mock helper event
  4150. unrenderHelper: function() {
  4151. if (this.helperEls) {
  4152. this.helperEls.remove();
  4153. this.helperEls = null;
  4154. }
  4155. },
  4156. /* Fill System (highlight, background events, business hours)
  4157. ------------------------------------------------------------------------------------------------------------------*/
  4158. fillSegTag: 'td', // override the default tag name
  4159. // Renders a set of rectangles over the given segments of days.
  4160. // Only returns segments that successfully rendered.
  4161. renderFill: function(type, segs, className) {
  4162. var nodes = [];
  4163. var i, seg;
  4164. var skeletonEl;
  4165. segs = this.renderFillSegEls(type, segs); // assignes `.el` to each seg. returns successfully rendered segs
  4166. for (i = 0; i < segs.length; i++) {
  4167. seg = segs[i];
  4168. skeletonEl = this.renderFillRow(type, seg, className);
  4169. this.rowEls.eq(seg.row).append(skeletonEl);
  4170. nodes.push(skeletonEl[0]);
  4171. }
  4172. this.elsByFill[type] = jQuery(nodes);
  4173. return segs;
  4174. },
  4175. // Generates the HTML needed for one row of a fill. Requires the seg's el to be rendered.
  4176. renderFillRow: function(type, seg, className) {
  4177. var colCnt = this.colCnt;
  4178. var startCol = seg.leftCol;
  4179. var endCol = seg.rightCol + 1;
  4180. var skeletonEl;
  4181. var trEl;
  4182. className = className || type.toLowerCase();
  4183. skeletonEl = jQuery(
  4184. '<div class="fc-' + className + '-skeleton">' +
  4185. '<table><tr/></table>' +
  4186. '</div>'
  4187. );
  4188. trEl = skeletonEl.find('tr');
  4189. if (startCol > 0) {
  4190. trEl.append('<td colspan="' + startCol + '"/>');
  4191. }
  4192. trEl.append(
  4193. seg.el.attr('colspan', endCol - startCol)
  4194. );
  4195. if (endCol < colCnt) {
  4196. trEl.append('<td colspan="' + (colCnt - endCol) + '"/>');
  4197. }
  4198. this.bookendCells(trEl);
  4199. return skeletonEl;
  4200. }
  4201. });
  4202. ;;
  4203. /* Event-rendering methods for the DayGrid class
  4204. ----------------------------------------------------------------------------------------------------------------------*/
  4205. DayGrid.mixin({
  4206. rowStructs: null, // an array of objects, each holding information about a row's foreground event-rendering
  4207. // Unrenders all events currently rendered on the grid
  4208. unrenderEvents: function() {
  4209. this.removeSegPopover(); // removes the "more.." events popover
  4210. Grid.prototype.unrenderEvents.apply(this, arguments); // calls the super-method
  4211. },
  4212. // Retrieves all rendered segment objects currently rendered on the grid
  4213. getEventSegs: function() {
  4214. return Grid.prototype.getEventSegs.call(this) // get the segments from the super-method
  4215. .concat(this.popoverSegs || []); // append the segments from the "more..." popover
  4216. },
  4217. // Renders the given background event segments onto the grid
  4218. renderBgSegs: function(segs) {
  4219. // don't render timed background events
  4220. var allDaySegs = jQuery.grep(segs, function(seg) {
  4221. return seg.event.allDay;
  4222. });
  4223. return Grid.prototype.renderBgSegs.call(this, allDaySegs); // call the super-method
  4224. },
  4225. // Renders the given foreground event segments onto the grid
  4226. renderFgSegs: function(segs) {
  4227. var rowStructs;
  4228. // render an `.el` on each seg
  4229. // returns a subset of the segs. segs that were actually rendered
  4230. segs = this.renderFgSegEls(segs);
  4231. rowStructs = this.rowStructs = this.renderSegRows(segs);
  4232. // append to each row's content skeleton
  4233. this.rowEls.each(function(i, rowNode) {
  4234. jQuery(rowNode).find('.fc-content-skeleton > table').append(
  4235. rowStructs[i].tbodyEl
  4236. );
  4237. });
  4238. return segs; // return only the segs that were actually rendered
  4239. },
  4240. // Unrenders all currently rendered foreground event segments
  4241. unrenderFgSegs: function() {
  4242. var rowStructs = this.rowStructs || [];
  4243. var rowStruct;
  4244. while ((rowStruct = rowStructs.pop())) {
  4245. rowStruct.tbodyEl.remove();
  4246. }
  4247. this.rowStructs = null;
  4248. },
  4249. // Uses the given events array to generate <tbody> elements that should be appended to each row's content skeleton.
  4250. // Returns an array of rowStruct objects (see the bottom of `renderSegRow`).
  4251. // PRECONDITION: each segment shoud already have a rendered and assigned `.el`
  4252. renderSegRows: function(segs) {
  4253. var rowStructs = [];
  4254. var segRows;
  4255. var row;
  4256. segRows = this.groupSegRows(segs); // group into nested arrays
  4257. // iterate each row of segment groupings
  4258. for (row = 0; row < segRows.length; row++) {
  4259. rowStructs.push(
  4260. this.renderSegRow(row, segRows[row])
  4261. );
  4262. }
  4263. return rowStructs;
  4264. },
  4265. // Builds the HTML to be used for the default element for an individual segment
  4266. fgSegHtml: function(seg, disableResizing) {
  4267. var view = this.view;
  4268. var event = seg.event;
  4269. var isDraggable = view.isEventDraggable(event);
  4270. var isResizableFromStart = !disableResizing && event.allDay &&
  4271. seg.isStart && view.isEventResizableFromStart(event);
  4272. var isResizableFromEnd = !disableResizing && event.allDay &&
  4273. seg.isEnd && view.isEventResizableFromEnd(event);
  4274. var classes = this.getSegClasses(seg, isDraggable, isResizableFromStart || isResizableFromEnd);
  4275. var skinCss = cssToStr(this.getSegSkinCss(seg));
  4276. var timeHtml = '';
  4277. var timeText;
  4278. var titleHtml;
  4279. classes.unshift('fc-day-grid-event', 'fc-h-event');
  4280. // Only display a timed events time if it is the starting segment
  4281. if (seg.isStart) {
  4282. timeText = this.getEventTimeText(event);
  4283. if (timeText) {
  4284. timeHtml = '<span class="fc-time">' + htmlEscape(timeText) + '</span>';
  4285. }
  4286. }
  4287. titleHtml =
  4288. '<span class="fc-title">' +
  4289. (htmlEscape(event.title || '') || '&nbsp;') + // we always want one line of height
  4290. '</span>';
  4291. return '<a class="' + classes.join(' ') + '"' +
  4292. (event.url ?
  4293. ' href="' + htmlEscape(event.url) + '"' :
  4294. ''
  4295. ) +
  4296. (skinCss ?
  4297. ' style="' + skinCss + '"' :
  4298. ''
  4299. ) +
  4300. '>' +
  4301. '<div class="fc-content">' +
  4302. (this.isRTL ?
  4303. titleHtml + ' ' + timeHtml : // put a natural space in between
  4304. timeHtml + ' ' + titleHtml //
  4305. ) +
  4306. '</div>' +
  4307. (isResizableFromStart ?
  4308. '<div class="fc-resizer fc-start-resizer" />' :
  4309. ''
  4310. ) +
  4311. (isResizableFromEnd ?
  4312. '<div class="fc-resizer fc-end-resizer" />' :
  4313. ''
  4314. ) +
  4315. '</a>';
  4316. },
  4317. // Given a row # and an array of segments all in the same row, render a <tbody> element, a skeleton that contains
  4318. // the segments. Returns object with a bunch of internal data about how the render was calculated.
  4319. // NOTE: modifies rowSegs
  4320. renderSegRow: function(row, rowSegs) {
  4321. var colCnt = this.colCnt;
  4322. var segLevels = this.buildSegLevels(rowSegs); // group into sub-arrays of levels
  4323. var levelCnt = Math.max(1, segLevels.length); // ensure at least one level
  4324. var tbody = jQuery('<tbody/>');
  4325. var segMatrix = []; // lookup for which segments are rendered into which level+col cells
  4326. var cellMatrix = []; // lookup for all <td> elements of the level+col matrix
  4327. var loneCellMatrix = []; // lookup for <td> elements that only take up a single column
  4328. var i, levelSegs;
  4329. var col;
  4330. var tr;
  4331. var j, seg;
  4332. var td;
  4333. // populates empty cells from the current column (`col`) to `endCol`
  4334. function emptyCellsUntil(endCol) {
  4335. while (col < endCol) {
  4336. // try to grab a cell from the level above and extend its rowspan. otherwise, create a fresh cell
  4337. td = (loneCellMatrix[i - 1] || [])[col];
  4338. if (td) {
  4339. td.attr(
  4340. 'rowspan',
  4341. parseInt(td.attr('rowspan') || 1, 10) + 1
  4342. );
  4343. }
  4344. else {
  4345. td = jQuery('<td/>');
  4346. tr.append(td);
  4347. }
  4348. cellMatrix[i][col] = td;
  4349. loneCellMatrix[i][col] = td;
  4350. col++;
  4351. }
  4352. }
  4353. for (i = 0; i < levelCnt; i++) { // iterate through all levels
  4354. levelSegs = segLevels[i];
  4355. col = 0;
  4356. tr = jQuery('<tr/>');
  4357. segMatrix.push([]);
  4358. cellMatrix.push([]);
  4359. loneCellMatrix.push([]);
  4360. // levelCnt might be 1 even though there are no actual levels. protect against this.
  4361. // this single empty row is useful for styling.
  4362. if (levelSegs) {
  4363. for (j = 0; j < levelSegs.length; j++) { // iterate through segments in level
  4364. seg = levelSegs[j];
  4365. emptyCellsUntil(seg.leftCol);
  4366. // create a container that occupies or more columns. append the event element.
  4367. td = jQuery('<td class="fc-event-container"/>').append(seg.el);
  4368. if (seg.leftCol != seg.rightCol) {
  4369. td.attr('colspan', seg.rightCol - seg.leftCol + 1);
  4370. }
  4371. else { // a single-column segment
  4372. loneCellMatrix[i][col] = td;
  4373. }
  4374. while (col <= seg.rightCol) {
  4375. cellMatrix[i][col] = td;
  4376. segMatrix[i][col] = seg;
  4377. col++;
  4378. }
  4379. tr.append(td);
  4380. }
  4381. }
  4382. emptyCellsUntil(colCnt); // finish off the row
  4383. this.bookendCells(tr);
  4384. tbody.append(tr);
  4385. }
  4386. return { // a "rowStruct"
  4387. row: row, // the row number
  4388. tbodyEl: tbody,
  4389. cellMatrix: cellMatrix,
  4390. segMatrix: segMatrix,
  4391. segLevels: segLevels,
  4392. segs: rowSegs
  4393. };
  4394. },
  4395. // Stacks a flat array of segments, which are all assumed to be in the same row, into subarrays of vertical levels.
  4396. // NOTE: modifies segs
  4397. buildSegLevels: function(segs) {
  4398. var levels = [];
  4399. var i, seg;
  4400. var j;
  4401. // Give preference to elements with certain criteria, so they have
  4402. // a chance to be closer to the top.
  4403. this.sortEventSegs(segs);
  4404. for (i = 0; i < segs.length; i++) {
  4405. seg = segs[i];
  4406. // loop through levels, starting with the topmost, until the segment doesn't collide with other segments
  4407. for (j = 0; j < levels.length; j++) {
  4408. if (!isDaySegCollision(seg, levels[j])) {
  4409. break;
  4410. }
  4411. }
  4412. // `j` now holds the desired subrow index
  4413. seg.level = j;
  4414. // create new level array if needed and append segment
  4415. (levels[j] || (levels[j] = [])).push(seg);
  4416. }
  4417. // order segments left-to-right. very important if calendar is RTL
  4418. for (j = 0; j < levels.length; j++) {
  4419. levels[j].sort(compareDaySegCols);
  4420. }
  4421. return levels;
  4422. },
  4423. // Given a flat array of segments, return an array of sub-arrays, grouped by each segment's row
  4424. groupSegRows: function(segs) {
  4425. var segRows = [];
  4426. var i;
  4427. for (i = 0; i < this.rowCnt; i++) {
  4428. segRows.push([]);
  4429. }
  4430. for (i = 0; i < segs.length; i++) {
  4431. segRows[segs[i].row].push(segs[i]);
  4432. }
  4433. return segRows;
  4434. }
  4435. });
  4436. // Computes whether two segments' columns collide. They are assumed to be in the same row.
  4437. function isDaySegCollision(seg, otherSegs) {
  4438. var i, otherSeg;
  4439. for (i = 0; i < otherSegs.length; i++) {
  4440. otherSeg = otherSegs[i];
  4441. if (
  4442. otherSeg.leftCol <= seg.rightCol &&
  4443. otherSeg.rightCol >= seg.leftCol
  4444. ) {
  4445. return true;
  4446. }
  4447. }
  4448. return false;
  4449. }
  4450. // A cmp function for determining the leftmost event
  4451. function compareDaySegCols(a, b) {
  4452. return a.leftCol - b.leftCol;
  4453. }
  4454. ;;
  4455. /* Methods relate to limiting the number events for a given day on a DayGrid
  4456. ----------------------------------------------------------------------------------------------------------------------*/
  4457. // NOTE: all the segs being passed around in here are foreground segs
  4458. DayGrid.mixin({
  4459. segPopover: null, // the Popover that holds events that can't fit in a cell. null when not visible
  4460. popoverSegs: null, // an array of segment objects that the segPopover holds. null when not visible
  4461. removeSegPopover: function() {
  4462. if (this.segPopover) {
  4463. this.segPopover.hide(); // in handler, will call segPopover's removeElement
  4464. }
  4465. },
  4466. // Limits the number of "levels" (vertically stacking layers of events) for each row of the grid.
  4467. // `levelLimit` can be false (don't limit), a number, or true (should be computed).
  4468. limitRows: function(levelLimit) {
  4469. var rowStructs = this.rowStructs || [];
  4470. var row; // row #
  4471. var rowLevelLimit;
  4472. for (row = 0; row < rowStructs.length; row++) {
  4473. this.unlimitRow(row);
  4474. if (!levelLimit) {
  4475. rowLevelLimit = false;
  4476. }
  4477. else if (typeof levelLimit === 'number') {
  4478. rowLevelLimit = levelLimit;
  4479. }
  4480. else {
  4481. rowLevelLimit = this.computeRowLevelLimit(row);
  4482. }
  4483. if (rowLevelLimit !== false) {
  4484. this.limitRow(row, rowLevelLimit);
  4485. }
  4486. }
  4487. },
  4488. // Computes the number of levels a row will accomodate without going outside its bounds.
  4489. // Assumes the row is "rigid" (maintains a constant height regardless of what is inside).
  4490. // `row` is the row number.
  4491. computeRowLevelLimit: function(row) {
  4492. var rowEl = this.rowEls.eq(row); // the containing "fake" row div
  4493. var rowHeight = rowEl.height(); // TODO: cache somehow?
  4494. var trEls = this.rowStructs[row].tbodyEl.children();
  4495. var i, trEl;
  4496. var trHeight;
  4497. function iterInnerHeights(i, childNode) {
  4498. trHeight = Math.max(trHeight, jQuery(childNode).outerHeight());
  4499. }
  4500. // Reveal one level <tr> at a time and stop when we find one out of bounds
  4501. for (i = 0; i < trEls.length; i++) {
  4502. trEl = trEls.eq(i).removeClass('fc-limited'); // reset to original state (reveal)
  4503. // with rowspans>1 and IE8, trEl.outerHeight() would return the height of the largest cell,
  4504. // so instead, find the tallest inner content element.
  4505. trHeight = 0;
  4506. trEl.find('> td > :first-child').each(iterInnerHeights);
  4507. if (trEl.position().top + trHeight > rowHeight) {
  4508. return i;
  4509. }
  4510. }
  4511. return false; // should not limit at all
  4512. },
  4513. // Limits the given grid row to the maximum number of levels and injects "more" links if necessary.
  4514. // `row` is the row number.
  4515. // `levelLimit` is a number for the maximum (inclusive) number of levels allowed.
  4516. limitRow: function(row, levelLimit) {
  4517. var _this = this;
  4518. var rowStruct = this.rowStructs[row];
  4519. var moreNodes = []; // array of "more" <a> links and <td> DOM nodes
  4520. var col = 0; // col #, left-to-right (not chronologically)
  4521. var levelSegs; // array of segment objects in the last allowable level, ordered left-to-right
  4522. var cellMatrix; // a matrix (by level, then column) of all <td> jQuery elements in the row
  4523. var limitedNodes; // array of temporarily hidden level <tr> and segment <td> DOM nodes
  4524. var i, seg;
  4525. var segsBelow; // array of segment objects below `seg` in the current `col`
  4526. var totalSegsBelow; // total number of segments below `seg` in any of the columns `seg` occupies
  4527. var colSegsBelow; // array of segment arrays, below seg, one for each column (offset from segs's first column)
  4528. var td, rowspan;
  4529. var segMoreNodes; // array of "more" <td> cells that will stand-in for the current seg's cell
  4530. var j;
  4531. var moreTd, moreWrap, moreLink;
  4532. // Iterates through empty level cells and places "more" links inside if need be
  4533. function emptyCellsUntil(endCol) { // goes from current `col` to `endCol`
  4534. while (col < endCol) {
  4535. segsBelow = _this.getCellSegs(row, col, levelLimit);
  4536. if (segsBelow.length) {
  4537. td = cellMatrix[levelLimit - 1][col];
  4538. moreLink = _this.renderMoreLink(row, col, segsBelow);
  4539. moreWrap = jQuery('<div/>').append(moreLink);
  4540. td.append(moreWrap);
  4541. moreNodes.push(moreWrap[0]);
  4542. }
  4543. col++;
  4544. }
  4545. }
  4546. if (levelLimit && levelLimit < rowStruct.segLevels.length) { // is it actually over the limit?
  4547. levelSegs = rowStruct.segLevels[levelLimit - 1];
  4548. cellMatrix = rowStruct.cellMatrix;
  4549. limitedNodes = rowStruct.tbodyEl.children().slice(levelLimit) // get level <tr> elements past the limit
  4550. .addClass('fc-limited').get(); // hide elements and get a simple DOM-nodes array
  4551. // iterate though segments in the last allowable level
  4552. for (i = 0; i < levelSegs.length; i++) {
  4553. seg = levelSegs[i];
  4554. emptyCellsUntil(seg.leftCol); // process empty cells before the segment
  4555. // determine *all* segments below `seg` that occupy the same columns
  4556. colSegsBelow = [];
  4557. totalSegsBelow = 0;
  4558. while (col <= seg.rightCol) {
  4559. segsBelow = this.getCellSegs(row, col, levelLimit);
  4560. colSegsBelow.push(segsBelow);
  4561. totalSegsBelow += segsBelow.length;
  4562. col++;
  4563. }
  4564. if (totalSegsBelow) { // do we need to replace this segment with one or many "more" links?
  4565. td = cellMatrix[levelLimit - 1][seg.leftCol]; // the segment's parent cell
  4566. rowspan = td.attr('rowspan') || 1;
  4567. segMoreNodes = [];
  4568. // make a replacement <td> for each column the segment occupies. will be one for each colspan
  4569. for (j = 0; j < colSegsBelow.length; j++) {
  4570. moreTd = jQuery('<td class="fc-more-cell"/>').attr('rowspan', rowspan);
  4571. segsBelow = colSegsBelow[j];
  4572. moreLink = this.renderMoreLink(
  4573. row,
  4574. seg.leftCol + j,
  4575. [ seg ].concat(segsBelow) // count seg as hidden too
  4576. );
  4577. moreWrap = jQuery('<div/>').append(moreLink);
  4578. moreTd.append(moreWrap);
  4579. segMoreNodes.push(moreTd[0]);
  4580. moreNodes.push(moreTd[0]);
  4581. }
  4582. td.addClass('fc-limited').after(jQuery(segMoreNodes)); // hide original <td> and inject replacements
  4583. limitedNodes.push(td[0]);
  4584. }
  4585. }
  4586. emptyCellsUntil(this.colCnt); // finish off the level
  4587. rowStruct.moreEls = jQuery(moreNodes); // for easy undoing later
  4588. rowStruct.limitedEls = jQuery(limitedNodes); // for easy undoing later
  4589. }
  4590. },
  4591. // Reveals all levels and removes all "more"-related elements for a grid's row.
  4592. // `row` is a row number.
  4593. unlimitRow: function(row) {
  4594. var rowStruct = this.rowStructs[row];
  4595. if (rowStruct.moreEls) {
  4596. rowStruct.moreEls.remove();
  4597. rowStruct.moreEls = null;
  4598. }
  4599. if (rowStruct.limitedEls) {
  4600. rowStruct.limitedEls.removeClass('fc-limited');
  4601. rowStruct.limitedEls = null;
  4602. }
  4603. },
  4604. // Renders an <a> element that represents hidden event element for a cell.
  4605. // Responsible for attaching click handler as well.
  4606. renderMoreLink: function(row, col, hiddenSegs) {
  4607. var _this = this;
  4608. var view = this.view;
  4609. return jQuery('<a class="fc-more"/>')
  4610. .text(
  4611. this.getMoreLinkText(hiddenSegs.length)
  4612. )
  4613. .on('click', function(ev) {
  4614. var clickOption = view.opt('eventLimitClick');
  4615. var date = _this.getCellDate(row, col);
  4616. var moreEl = jQuery(this);
  4617. var dayEl = _this.getCellEl(row, col);
  4618. var allSegs = _this.getCellSegs(row, col);
  4619. // rescope the segments to be within the cell's date
  4620. var reslicedAllSegs = _this.resliceDaySegs(allSegs, date);
  4621. var reslicedHiddenSegs = _this.resliceDaySegs(hiddenSegs, date);
  4622. if (typeof clickOption === 'function') {
  4623. // the returned value can be an atomic option
  4624. clickOption = view.trigger('eventLimitClick', null, {
  4625. date: date,
  4626. dayEl: dayEl,
  4627. moreEl: moreEl,
  4628. segs: reslicedAllSegs,
  4629. hiddenSegs: reslicedHiddenSegs
  4630. }, ev);
  4631. }
  4632. if (clickOption === 'popover') {
  4633. _this.showSegPopover(row, col, moreEl, reslicedAllSegs);
  4634. }
  4635. else if (typeof clickOption === 'string') { // a view name
  4636. view.calendar.zoomTo(date, clickOption);
  4637. }
  4638. });
  4639. },
  4640. // Reveals the popover that displays all events within a cell
  4641. showSegPopover: function(row, col, moreLink, segs) {
  4642. var _this = this;
  4643. var view = this.view;
  4644. var moreWrap = moreLink.parent(); // the <div> wrapper around the <a>
  4645. var topEl; // the element we want to match the top coordinate of
  4646. var options;
  4647. if (this.rowCnt == 1) {
  4648. topEl = view.el; // will cause the popover to cover any sort of header
  4649. }
  4650. else {
  4651. topEl = this.rowEls.eq(row); // will align with top of row
  4652. }
  4653. options = {
  4654. className: 'fc-more-popover',
  4655. content: this.renderSegPopoverContent(row, col, segs),
  4656. parentEl: this.el,
  4657. top: topEl.offset().top,
  4658. autoHide: true, // when the user clicks elsewhere, hide the popover
  4659. viewportConstrain: view.opt('popoverViewportConstrain'),
  4660. hide: function() {
  4661. // kill everything when the popover is hidden
  4662. _this.segPopover.removeElement();
  4663. _this.segPopover = null;
  4664. _this.popoverSegs = null;
  4665. }
  4666. };
  4667. // Determine horizontal coordinate.
  4668. // We use the moreWrap instead of the <td> to avoid border confusion.
  4669. if (this.isRTL) {
  4670. options.right = moreWrap.offset().left + moreWrap.outerWidth() + 1; // +1 to be over cell border
  4671. }
  4672. else {
  4673. options.left = moreWrap.offset().left - 1; // -1 to be over cell border
  4674. }
  4675. this.segPopover = new Popover(options);
  4676. this.segPopover.show();
  4677. },
  4678. // Builds the inner DOM contents of the segment popover
  4679. renderSegPopoverContent: function(row, col, segs) {
  4680. var view = this.view;
  4681. var isTheme = view.opt('theme');
  4682. var title = this.getCellDate(row, col).format(view.opt('dayPopoverFormat'));
  4683. var content = jQuery(
  4684. '<div class="fc-header ' + view.widgetHeaderClass + '">' +
  4685. '<span class="fc-close ' +
  4686. (isTheme ? 'ui-icon ui-icon-closethick' : 'fc-icon fc-icon-x') +
  4687. '"></span>' +
  4688. '<span class="fc-title">' +
  4689. htmlEscape(title) +
  4690. '</span>' +
  4691. '<div class="fc-clear"/>' +
  4692. '</div>' +
  4693. '<div class="fc-body ' + view.widgetContentClass + '">' +
  4694. '<div class="fc-event-container"></div>' +
  4695. '</div>'
  4696. );
  4697. var segContainer = content.find('.fc-event-container');
  4698. var i;
  4699. // render each seg's `el` and only return the visible segs
  4700. segs = this.renderFgSegEls(segs, true); // disableResizing=true
  4701. this.popoverSegs = segs;
  4702. for (i = 0; i < segs.length; i++) {
  4703. // because segments in the popover are not part of a grid coordinate system, provide a hint to any
  4704. // grids that want to do drag-n-drop about which cell it came from
  4705. this.prepareHits();
  4706. segs[i].hit = this.getCellHit(row, col);
  4707. this.releaseHits();
  4708. segContainer.append(segs[i].el);
  4709. }
  4710. return content;
  4711. },
  4712. // Given the events within an array of segment objects, reslice them to be in a single day
  4713. resliceDaySegs: function(segs, dayDate) {
  4714. // build an array of the original events
  4715. var events = jQuery.map(segs, function(seg) {
  4716. return seg.event;
  4717. });
  4718. var dayStart = dayDate.clone();
  4719. var dayEnd = dayStart.clone().add(1, 'days');
  4720. var dayRange = { start: dayStart, end: dayEnd };
  4721. // slice the events with a custom slicing function
  4722. segs = this.eventsToSegs(
  4723. events,
  4724. function(range) {
  4725. var seg = intersectRanges(range, dayRange); // undefind if no intersection
  4726. return seg ? [ seg ] : []; // must return an array of segments
  4727. }
  4728. );
  4729. // force an order because eventsToSegs doesn't guarantee one
  4730. this.sortEventSegs(segs);
  4731. return segs;
  4732. },
  4733. // Generates the text that should be inside a "more" link, given the number of events it represents
  4734. getMoreLinkText: function(num) {
  4735. var opt = this.view.opt('eventLimitText');
  4736. if (typeof opt === 'function') {
  4737. return opt(num);
  4738. }
  4739. else {
  4740. return '+' + num + ' ' + opt;
  4741. }
  4742. },
  4743. // Returns segments within a given cell.
  4744. // If `startLevel` is specified, returns only events including and below that level. Otherwise returns all segs.
  4745. getCellSegs: function(row, col, startLevel) {
  4746. var segMatrix = this.rowStructs[row].segMatrix;
  4747. var level = startLevel || 0;
  4748. var segs = [];
  4749. var seg;
  4750. while (level < segMatrix.length) {
  4751. seg = segMatrix[level][col];
  4752. if (seg) {
  4753. segs.push(seg);
  4754. }
  4755. level++;
  4756. }
  4757. return segs;
  4758. }
  4759. });
  4760. ;;
  4761. /* A component that renders one or more columns of vertical time slots
  4762. ----------------------------------------------------------------------------------------------------------------------*/
  4763. // We mixin DayTable, even though there is only a single row of days
  4764. var TimeGrid = FC.TimeGrid = Grid.extend(DayTableMixin, {
  4765. slotDuration: null, // duration of a "slot", a distinct time segment on given day, visualized by lines
  4766. snapDuration: null, // granularity of time for dragging and selecting
  4767. snapsPerSlot: null,
  4768. minTime: null, // Duration object that denotes the first visible time of any given day
  4769. maxTime: null, // Duration object that denotes the exclusive visible end time of any given day
  4770. labelFormat: null, // formatting string for times running along vertical axis
  4771. labelInterval: null, // duration of how often a label should be displayed for a slot
  4772. colEls: null, // cells elements in the day-row background
  4773. slatEls: null, // elements running horizontally across all columns
  4774. nowIndicatorEls: null,
  4775. colCoordCache: null,
  4776. slatCoordCache: null,
  4777. constructor: function() {
  4778. Grid.apply(this, arguments); // call the super-constructor
  4779. this.processOptions();
  4780. },
  4781. // Renders the time grid into `this.el`, which should already be assigned.
  4782. // Relies on the view's colCnt. In the future, this component should probably be self-sufficient.
  4783. renderDates: function() {
  4784. this.el.html(this.renderHtml());
  4785. this.colEls = this.el.find('.fc-day');
  4786. this.slatEls = this.el.find('.fc-slats tr');
  4787. this.colCoordCache = new CoordCache({
  4788. els: this.colEls,
  4789. isHorizontal: true
  4790. });
  4791. this.slatCoordCache = new CoordCache({
  4792. els: this.slatEls,
  4793. isVertical: true
  4794. });
  4795. this.renderContentSkeleton();
  4796. },
  4797. // Renders the basic HTML skeleton for the grid
  4798. renderHtml: function() {
  4799. return '' +
  4800. '<div class="fc-bg">' +
  4801. '<table>' +
  4802. this.renderBgTrHtml(0) + // row=0
  4803. '</table>' +
  4804. '</div>' +
  4805. '<div class="fc-slats">' +
  4806. '<table>' +
  4807. this.renderSlatRowHtml() +
  4808. '</table>' +
  4809. '</div>';
  4810. },
  4811. // Generates the HTML for the horizontal "slats" that run width-wise. Has a time axis on a side. Depends on RTL.
  4812. renderSlatRowHtml: function() {
  4813. var view = this.view;
  4814. var isRTL = this.isRTL;
  4815. var html = '';
  4816. var slotTime = moment.duration(+this.minTime); // wish there was .clone() for durations
  4817. var slotDate; // will be on the view's first day, but we only care about its time
  4818. var isLabeled;
  4819. var axisHtml;
  4820. // Calculate the time for each slot
  4821. while (slotTime < this.maxTime) {
  4822. slotDate = this.start.clone().time(slotTime);
  4823. isLabeled = isInt(divideDurationByDuration(slotTime, this.labelInterval));
  4824. axisHtml =
  4825. '<td class="fc-axis fc-time ' + view.widgetContentClass + '" ' + view.axisStyleAttr() + '>' +
  4826. (isLabeled ?
  4827. '<span>' + // for matchCellWidths
  4828. htmlEscape(slotDate.format(this.labelFormat)) +
  4829. '</span>' :
  4830. ''
  4831. ) +
  4832. '</td>';
  4833. html +=
  4834. '<tr data-time="' + slotDate.format('HH:mm:ss') + '"' +
  4835. (isLabeled ? '' : ' class="fc-minor"') +
  4836. '>' +
  4837. (!isRTL ? axisHtml : '') +
  4838. '<td class="' + view.widgetContentClass + '"/>' +
  4839. (isRTL ? axisHtml : '') +
  4840. "</tr>";
  4841. slotTime.add(this.slotDuration);
  4842. }
  4843. return html;
  4844. },
  4845. /* Options
  4846. ------------------------------------------------------------------------------------------------------------------*/
  4847. // Parses various options into properties of this object
  4848. processOptions: function() {
  4849. var view = this.view;
  4850. var slotDuration = view.opt('slotDuration');
  4851. var snapDuration = view.opt('snapDuration');
  4852. var input;
  4853. slotDuration = moment.duration(slotDuration);
  4854. snapDuration = snapDuration ? moment.duration(snapDuration) : slotDuration;
  4855. this.slotDuration = slotDuration;
  4856. this.snapDuration = snapDuration;
  4857. this.snapsPerSlot = slotDuration / snapDuration; // TODO: ensure an integer multiple?
  4858. this.minResizeDuration = snapDuration; // hack
  4859. this.minTime = moment.duration(view.opt('minTime'));
  4860. this.maxTime = moment.duration(view.opt('maxTime'));
  4861. // might be an array value (for TimelineView).
  4862. // if so, getting the most granular entry (the last one probably).
  4863. input = view.opt('slotLabelFormat');
  4864. if (jQuery.isArray(input)) {
  4865. input = input[input.length - 1];
  4866. }
  4867. this.labelFormat =
  4868. input ||
  4869. view.opt('axisFormat') || // deprecated
  4870. view.opt('smallTimeFormat'); // the computed default
  4871. input = view.opt('slotLabelInterval');
  4872. this.labelInterval = input ?
  4873. moment.duration(input) :
  4874. this.computeLabelInterval(slotDuration);
  4875. },
  4876. // Computes an automatic value for slotLabelInterval
  4877. computeLabelInterval: function(slotDuration) {
  4878. var i;
  4879. var labelInterval;
  4880. var slotsPerLabel;
  4881. // find the smallest stock label interval that results in more than one slots-per-label
  4882. for (i = AGENDA_STOCK_SUB_DURATIONS.length - 1; i >= 0; i--) {
  4883. labelInterval = moment.duration(AGENDA_STOCK_SUB_DURATIONS[i]);
  4884. slotsPerLabel = divideDurationByDuration(labelInterval, slotDuration);
  4885. if (isInt(slotsPerLabel) && slotsPerLabel > 1) {
  4886. return labelInterval;
  4887. }
  4888. }
  4889. return moment.duration(slotDuration); // fall back. clone
  4890. },
  4891. // Computes a default event time formatting string if `timeFormat` is not explicitly defined
  4892. computeEventTimeFormat: function() {
  4893. return this.view.opt('noMeridiemTimeFormat'); // like "6:30" (no AM/PM)
  4894. },
  4895. // Computes a default `displayEventEnd` value if one is not expliclty defined
  4896. computeDisplayEventEnd: function() {
  4897. return true;
  4898. },
  4899. /* Hit System
  4900. ------------------------------------------------------------------------------------------------------------------*/
  4901. prepareHits: function() {
  4902. this.colCoordCache.build();
  4903. this.slatCoordCache.build();
  4904. },
  4905. releaseHits: function() {
  4906. this.colCoordCache.clear();
  4907. // NOTE: don't clear slatCoordCache because we rely on it for computeTimeTop
  4908. },
  4909. queryHit: function(leftOffset, topOffset) {
  4910. var snapsPerSlot = this.snapsPerSlot;
  4911. var colCoordCache = this.colCoordCache;
  4912. var slatCoordCache = this.slatCoordCache;
  4913. var colIndex = colCoordCache.getHorizontalIndex(leftOffset);
  4914. var slatIndex = slatCoordCache.getVerticalIndex(topOffset);
  4915. if (colIndex != null && slatIndex != null) {
  4916. var slatTop = slatCoordCache.getTopOffset(slatIndex);
  4917. var slatHeight = slatCoordCache.getHeight(slatIndex);
  4918. var partial = (topOffset - slatTop) / slatHeight; // floating point number between 0 and 1
  4919. var localSnapIndex = Math.floor(partial * snapsPerSlot); // the snap # relative to start of slat
  4920. var snapIndex = slatIndex * snapsPerSlot + localSnapIndex;
  4921. var snapTop = slatTop + (localSnapIndex / snapsPerSlot) * slatHeight;
  4922. var snapBottom = slatTop + ((localSnapIndex + 1) / snapsPerSlot) * slatHeight;
  4923. return {
  4924. col: colIndex,
  4925. snap: snapIndex,
  4926. component: this, // needed unfortunately :(
  4927. left: colCoordCache.getLeftOffset(colIndex),
  4928. right: colCoordCache.getRightOffset(colIndex),
  4929. top: snapTop,
  4930. bottom: snapBottom
  4931. };
  4932. }
  4933. },
  4934. getHitSpan: function(hit) {
  4935. var start = this.getCellDate(0, hit.col); // row=0
  4936. var time = this.computeSnapTime(hit.snap); // pass in the snap-index
  4937. var end;
  4938. start.time(time);
  4939. end = start.clone().add(this.snapDuration);
  4940. return { start: start, end: end };
  4941. },
  4942. getHitEl: function(hit) {
  4943. return this.colEls.eq(hit.col);
  4944. },
  4945. /* Dates
  4946. ------------------------------------------------------------------------------------------------------------------*/
  4947. rangeUpdated: function() {
  4948. this.updateDayTable();
  4949. },
  4950. // Given a row number of the grid, representing a "snap", returns a time (Duration) from its start-of-day
  4951. computeSnapTime: function(snapIndex) {
  4952. return moment.duration(this.minTime + this.snapDuration * snapIndex);
  4953. },
  4954. // Slices up the given span (unzoned start/end with other misc data) into an array of segments
  4955. spanToSegs: function(span) {
  4956. var segs = this.sliceRangeByTimes(span);
  4957. var i;
  4958. for (i = 0; i < segs.length; i++) {
  4959. if (this.isRTL) {
  4960. segs[i].col = this.daysPerRow - 1 - segs[i].dayIndex;
  4961. }
  4962. else {
  4963. segs[i].col = segs[i].dayIndex;
  4964. }
  4965. }
  4966. return segs;
  4967. },
  4968. sliceRangeByTimes: function(range) {
  4969. var segs = [];
  4970. var seg;
  4971. var dayIndex;
  4972. var dayDate;
  4973. var dayRange;
  4974. for (dayIndex = 0; dayIndex < this.daysPerRow; dayIndex++) {
  4975. dayDate = this.dayDates[dayIndex].clone(); // TODO: better API for this?
  4976. dayRange = {
  4977. start: dayDate.clone().time(this.minTime),
  4978. end: dayDate.clone().time(this.maxTime)
  4979. };
  4980. seg = intersectRanges(range, dayRange); // both will be ambig timezone
  4981. if (seg) {
  4982. seg.dayIndex = dayIndex;
  4983. segs.push(seg);
  4984. }
  4985. }
  4986. return segs;
  4987. },
  4988. /* Coordinates
  4989. ------------------------------------------------------------------------------------------------------------------*/
  4990. updateSize: function(isResize) { // NOT a standard Grid method
  4991. this.slatCoordCache.build();
  4992. if (isResize) {
  4993. this.updateSegVerticals(
  4994. [].concat(this.fgSegs || [], this.bgSegs || [], this.businessSegs || [])
  4995. );
  4996. }
  4997. },
  4998. // Computes the top coordinate, relative to the bounds of the grid, of the given date.
  4999. // A `startOfDayDate` must be given for avoiding ambiguity over how to treat midnight.
  5000. computeDateTop: function(date, startOfDayDate) {
  5001. return this.computeTimeTop(
  5002. moment.duration(
  5003. date - startOfDayDate.clone().stripTime()
  5004. )
  5005. );
  5006. },
  5007. // Computes the top coordinate, relative to the bounds of the grid, of the given time (a Duration).
  5008. computeTimeTop: function(time) {
  5009. var len = this.slatEls.length;
  5010. var slatCoverage = (time - this.minTime) / this.slotDuration; // floating-point value of # of slots covered
  5011. var slatIndex;
  5012. var slatRemainder;
  5013. // compute a floating-point number for how many slats should be progressed through.
  5014. // from 0 to number of slats (inclusive)
  5015. // constrained because minTime/maxTime might be customized.
  5016. slatCoverage = Math.max(0, slatCoverage);
  5017. slatCoverage = Math.min(len, slatCoverage);
  5018. // an integer index of the furthest whole slat
  5019. // from 0 to number slats (*exclusive*, so len-1)
  5020. slatIndex = Math.floor(slatCoverage);
  5021. slatIndex = Math.min(slatIndex, len - 1);
  5022. // how much further through the slatIndex slat (from 0.0-1.0) must be covered in addition.
  5023. // could be 1.0 if slatCoverage is covering *all* the slots
  5024. slatRemainder = slatCoverage - slatIndex;
  5025. return this.slatCoordCache.getTopPosition(slatIndex) +
  5026. this.slatCoordCache.getHeight(slatIndex) * slatRemainder;
  5027. },
  5028. /* Event Drag Visualization
  5029. ------------------------------------------------------------------------------------------------------------------*/
  5030. // Renders a visual indication of an event being dragged over the specified date(s).
  5031. // A returned value of `true` signals that a mock "helper" event has been rendered.
  5032. renderDrag: function(eventLocation, seg) {
  5033. if (seg) { // if there is event information for this drag, render a helper event
  5034. this.renderEventLocationHelper(eventLocation, seg);
  5035. for (var i = 0; i < this.helperSegs.length; i++) {
  5036. this.applyDragOpacity(this.helperSegs[i].el);
  5037. }
  5038. return true; // signal that a helper has been rendered
  5039. }
  5040. else {
  5041. // otherwise, just render a highlight
  5042. this.renderHighlight(this.eventToSpan(eventLocation));
  5043. }
  5044. },
  5045. // Unrenders any visual indication of an event being dragged
  5046. unrenderDrag: function() {
  5047. this.unrenderHelper();
  5048. this.unrenderHighlight();
  5049. },
  5050. /* Event Resize Visualization
  5051. ------------------------------------------------------------------------------------------------------------------*/
  5052. // Renders a visual indication of an event being resized
  5053. renderEventResize: function(eventLocation, seg) {
  5054. this.renderEventLocationHelper(eventLocation, seg);
  5055. },
  5056. // Unrenders any visual indication of an event being resized
  5057. unrenderEventResize: function() {
  5058. this.unrenderHelper();
  5059. },
  5060. /* Event Helper
  5061. ------------------------------------------------------------------------------------------------------------------*/
  5062. // Renders a mock "helper" event. `sourceSeg` is the original segment object and might be null (an external drag)
  5063. renderHelper: function(event, sourceSeg) {
  5064. this.renderHelperSegs(this.eventToSegs(event), sourceSeg);
  5065. },
  5066. // Unrenders any mock helper event
  5067. unrenderHelper: function() {
  5068. this.unrenderHelperSegs();
  5069. },
  5070. /* Business Hours
  5071. ------------------------------------------------------------------------------------------------------------------*/
  5072. renderBusinessHours: function() {
  5073. var events = this.view.calendar.getBusinessHoursEvents();
  5074. var segs = this.eventsToSegs(events);
  5075. this.renderBusinessSegs(segs);
  5076. },
  5077. unrenderBusinessHours: function() {
  5078. this.unrenderBusinessSegs();
  5079. },
  5080. /* Now Indicator
  5081. ------------------------------------------------------------------------------------------------------------------*/
  5082. getNowIndicatorUnit: function() {
  5083. return 'minute'; // will refresh on the minute
  5084. },
  5085. renderNowIndicator: function(date) {
  5086. // seg system might be overkill, but it handles scenario where line needs to be rendered
  5087. // more than once because of columns with the same date (resources columns for example)
  5088. var segs = this.spanToSegs({ start: date, end: date });
  5089. var top = this.computeDateTop(date, date);
  5090. var nodes = [];
  5091. var i;
  5092. // render lines within the columns
  5093. for (i = 0; i < segs.length; i++) {
  5094. nodes.push(jQuery('<div class="fc-now-indicator fc-now-indicator-line"></div>')
  5095. .css('top', top)
  5096. .appendTo(this.colContainerEls.eq(segs[i].col))[0]);
  5097. }
  5098. // render an arrow over the axis
  5099. if (segs.length > 0) { // is the current time in view?
  5100. nodes.push(jQuery('<div class="fc-now-indicator fc-now-indicator-arrow"></div>')
  5101. .css('top', top)
  5102. .appendTo(this.el.find('.fc-content-skeleton'))[0]);
  5103. }
  5104. this.nowIndicatorEls = jQuery(nodes);
  5105. },
  5106. unrenderNowIndicator: function() {
  5107. if (this.nowIndicatorEls) {
  5108. this.nowIndicatorEls.remove();
  5109. this.nowIndicatorEls = null;
  5110. }
  5111. },
  5112. /* Selection
  5113. ------------------------------------------------------------------------------------------------------------------*/
  5114. // Renders a visual indication of a selection. Overrides the default, which was to simply render a highlight.
  5115. renderSelection: function(span) {
  5116. if (this.view.opt('selectHelper')) { // this setting signals that a mock helper event should be rendered
  5117. // normally acceps an eventLocation, span has a start/end, which is good enough
  5118. this.renderEventLocationHelper(span);
  5119. }
  5120. else {
  5121. this.renderHighlight(span);
  5122. }
  5123. },
  5124. // Unrenders any visual indication of a selection
  5125. unrenderSelection: function() {
  5126. this.unrenderHelper();
  5127. this.unrenderHighlight();
  5128. },
  5129. /* Highlight
  5130. ------------------------------------------------------------------------------------------------------------------*/
  5131. renderHighlight: function(span) {
  5132. this.renderHighlightSegs(this.spanToSegs(span));
  5133. },
  5134. unrenderHighlight: function() {
  5135. this.unrenderHighlightSegs();
  5136. }
  5137. });
  5138. ;;
  5139. /* Methods for rendering SEGMENTS, pieces of content that live on the view
  5140. ( this file is no longer just for events )
  5141. ----------------------------------------------------------------------------------------------------------------------*/
  5142. TimeGrid.mixin({
  5143. colContainerEls: null, // containers for each column
  5144. // inner-containers for each column where different types of segs live
  5145. fgContainerEls: null,
  5146. bgContainerEls: null,
  5147. helperContainerEls: null,
  5148. highlightContainerEls: null,
  5149. businessContainerEls: null,
  5150. // arrays of different types of displayed segments
  5151. fgSegs: null,
  5152. bgSegs: null,
  5153. helperSegs: null,
  5154. highlightSegs: null,
  5155. businessSegs: null,
  5156. // Renders the DOM that the view's content will live in
  5157. renderContentSkeleton: function() {
  5158. var cellHtml = '';
  5159. var i;
  5160. var skeletonEl;
  5161. for (i = 0; i < this.colCnt; i++) {
  5162. cellHtml +=
  5163. '<td>' +
  5164. '<div class="fc-content-col">' +
  5165. '<div class="fc-event-container fc-helper-container"></div>' +
  5166. '<div class="fc-event-container"></div>' +
  5167. '<div class="fc-highlight-container"></div>' +
  5168. '<div class="fc-bgevent-container"></div>' +
  5169. '<div class="fc-business-container"></div>' +
  5170. '</div>' +
  5171. '</td>';
  5172. }
  5173. skeletonEl = jQuery(
  5174. '<div class="fc-content-skeleton">' +
  5175. '<table>' +
  5176. '<tr>' + cellHtml + '</tr>' +
  5177. '</table>' +
  5178. '</div>'
  5179. );
  5180. this.colContainerEls = skeletonEl.find('.fc-content-col');
  5181. this.helperContainerEls = skeletonEl.find('.fc-helper-container');
  5182. this.fgContainerEls = skeletonEl.find('.fc-event-container:not(.fc-helper-container)');
  5183. this.bgContainerEls = skeletonEl.find('.fc-bgevent-container');
  5184. this.highlightContainerEls = skeletonEl.find('.fc-highlight-container');
  5185. this.businessContainerEls = skeletonEl.find('.fc-business-container');
  5186. this.bookendCells(skeletonEl.find('tr')); // TODO: do this on string level
  5187. this.el.append(skeletonEl);
  5188. },
  5189. /* Foreground Events
  5190. ------------------------------------------------------------------------------------------------------------------*/
  5191. renderFgSegs: function(segs) {
  5192. segs = this.renderFgSegsIntoContainers(segs, this.fgContainerEls);
  5193. this.fgSegs = segs;
  5194. return segs; // needed for Grid::renderEvents
  5195. },
  5196. unrenderFgSegs: function() {
  5197. this.unrenderNamedSegs('fgSegs');
  5198. },
  5199. /* Foreground Helper Events
  5200. ------------------------------------------------------------------------------------------------------------------*/
  5201. renderHelperSegs: function(segs, sourceSeg) {
  5202. var i, seg;
  5203. var sourceEl;
  5204. segs = this.renderFgSegsIntoContainers(segs, this.helperContainerEls);
  5205. // Try to make the segment that is in the same row as sourceSeg look the same
  5206. for (i = 0; i < segs.length; i++) {
  5207. seg = segs[i];
  5208. if (sourceSeg && sourceSeg.col === seg.col) {
  5209. sourceEl = sourceSeg.el;
  5210. seg.el.css({
  5211. left: sourceEl.css('left'),
  5212. right: sourceEl.css('right'),
  5213. 'margin-left': sourceEl.css('margin-left'),
  5214. 'margin-right': sourceEl.css('margin-right')
  5215. });
  5216. }
  5217. }
  5218. this.helperSegs = segs;
  5219. },
  5220. unrenderHelperSegs: function() {
  5221. this.unrenderNamedSegs('helperSegs');
  5222. },
  5223. /* Background Events
  5224. ------------------------------------------------------------------------------------------------------------------*/
  5225. renderBgSegs: function(segs) {
  5226. segs = this.renderFillSegEls('bgEvent', segs); // TODO: old fill system
  5227. this.updateSegVerticals(segs);
  5228. this.attachSegsByCol(this.groupSegsByCol(segs), this.bgContainerEls);
  5229. this.bgSegs = segs;
  5230. return segs; // needed for Grid::renderEvents
  5231. },
  5232. unrenderBgSegs: function() {
  5233. this.unrenderNamedSegs('bgSegs');
  5234. },
  5235. /* Highlight
  5236. ------------------------------------------------------------------------------------------------------------------*/
  5237. renderHighlightSegs: function(segs) {
  5238. segs = this.renderFillSegEls('highlight', segs); // TODO: old fill system
  5239. this.updateSegVerticals(segs);
  5240. this.attachSegsByCol(this.groupSegsByCol(segs), this.highlightContainerEls);
  5241. this.highlightSegs = segs;
  5242. },
  5243. unrenderHighlightSegs: function() {
  5244. this.unrenderNamedSegs('highlightSegs');
  5245. },
  5246. /* Business Hours
  5247. ------------------------------------------------------------------------------------------------------------------*/
  5248. renderBusinessSegs: function(segs) {
  5249. segs = this.renderFillSegEls('businessHours', segs); // TODO: old fill system
  5250. this.updateSegVerticals(segs);
  5251. this.attachSegsByCol(this.groupSegsByCol(segs), this.businessContainerEls);
  5252. this.businessSegs = segs;
  5253. },
  5254. unrenderBusinessSegs: function() {
  5255. this.unrenderNamedSegs('businessSegs');
  5256. },
  5257. /* Seg Rendering Utils
  5258. ------------------------------------------------------------------------------------------------------------------*/
  5259. // Given a flat array of segments, return an array of sub-arrays, grouped by each segment's col
  5260. groupSegsByCol: function(segs) {
  5261. var segsByCol = [];
  5262. var i;
  5263. for (i = 0; i < this.colCnt; i++) {
  5264. segsByCol.push([]);
  5265. }
  5266. for (i = 0; i < segs.length; i++) {
  5267. segsByCol[segs[i].col].push(segs[i]);
  5268. }
  5269. return segsByCol;
  5270. },
  5271. // Given segments grouped by column, insert the segments' elements into a parallel array of container
  5272. // elements, each living within a column.
  5273. attachSegsByCol: function(segsByCol, containerEls) {
  5274. var col;
  5275. var segs;
  5276. var i;
  5277. for (col = 0; col < this.colCnt; col++) { // iterate each column grouping
  5278. segs = segsByCol[col];
  5279. for (i = 0; i < segs.length; i++) {
  5280. containerEls.eq(col).append(segs[i].el);
  5281. }
  5282. }
  5283. },
  5284. // Given the name of a property of `this` object, assumed to be an array of segments,
  5285. // loops through each segment and removes from DOM. Will null-out the property afterwards.
  5286. unrenderNamedSegs: function(propName) {
  5287. var segs = this[propName];
  5288. var i;
  5289. if (segs) {
  5290. for (i = 0; i < segs.length; i++) {
  5291. segs[i].el.remove();
  5292. }
  5293. this[propName] = null;
  5294. }
  5295. },
  5296. /* Foreground Event Rendering Utils
  5297. ------------------------------------------------------------------------------------------------------------------*/
  5298. // Given an array of foreground segments, render a DOM element for each, computes position,
  5299. // and attaches to the column inner-container elements.
  5300. renderFgSegsIntoContainers: function(segs, containerEls) {
  5301. var segsByCol;
  5302. var col;
  5303. segs = this.renderFgSegEls(segs); // will call fgSegHtml
  5304. segsByCol = this.groupSegsByCol(segs);
  5305. for (col = 0; col < this.colCnt; col++) {
  5306. this.updateFgSegCoords(segsByCol[col]);
  5307. }
  5308. this.attachSegsByCol(segsByCol, containerEls);
  5309. return segs;
  5310. },
  5311. // Renders the HTML for a single event segment's default rendering
  5312. fgSegHtml: function(seg, disableResizing) {
  5313. var view = this.view;
  5314. var event = seg.event;
  5315. var isDraggable = view.isEventDraggable(event);
  5316. var isResizableFromStart = !disableResizing && seg.isStart && view.isEventResizableFromStart(event);
  5317. var isResizableFromEnd = !disableResizing && seg.isEnd && view.isEventResizableFromEnd(event);
  5318. var classes = this.getSegClasses(seg, isDraggable, isResizableFromStart || isResizableFromEnd);
  5319. var skinCss = cssToStr(this.getSegSkinCss(seg));
  5320. var timeText;
  5321. var fullTimeText; // more verbose time text. for the print stylesheet
  5322. var startTimeText; // just the start time text
  5323. classes.unshift('fc-time-grid-event', 'fc-v-event');
  5324. if (view.isMultiDayEvent(event)) { // if the event appears to span more than one day...
  5325. // Don't display time text on segments that run entirely through a day.
  5326. // That would appear as midnight-midnight and would look dumb.
  5327. // Otherwise, display the time text for the *segment's* times (like 6pm-midnight or midnight-10am)
  5328. if (seg.isStart || seg.isEnd) {
  5329. timeText = this.getEventTimeText(seg);
  5330. fullTimeText = this.getEventTimeText(seg, 'LT');
  5331. startTimeText = this.getEventTimeText(seg, null, false); // displayEnd=false
  5332. }
  5333. } else {
  5334. // Display the normal time text for the *event's* times
  5335. timeText = this.getEventTimeText(event);
  5336. fullTimeText = this.getEventTimeText(event, 'LT');
  5337. startTimeText = this.getEventTimeText(event, null, false); // displayEnd=false
  5338. }
  5339. return '<a class="' + classes.join(' ') + '"' +
  5340. (event.url ?
  5341. ' href="' + htmlEscape(event.url) + '"' :
  5342. ''
  5343. ) +
  5344. (skinCss ?
  5345. ' style="' + skinCss + '"' :
  5346. ''
  5347. ) +
  5348. '>' +
  5349. '<div class="fc-content">' +
  5350. (timeText ?
  5351. '<div class="fc-time"' +
  5352. ' data-start="' + htmlEscape(startTimeText) + '"' +
  5353. ' data-full="' + htmlEscape(fullTimeText) + '"' +
  5354. '>' +
  5355. '<span>' + htmlEscape(timeText) + '</span>' +
  5356. '</div>' :
  5357. ''
  5358. ) +
  5359. (event.title ?
  5360. '<div class="fc-title">' +
  5361. htmlEscape(event.title) +
  5362. '</div>' :
  5363. ''
  5364. ) +
  5365. '</div>' +
  5366. '<div class="fc-bg"/>' +
  5367. /* TODO: write CSS for this
  5368. (isResizableFromStart ?
  5369. '<div class="fc-resizer fc-start-resizer" />' :
  5370. ''
  5371. ) +
  5372. */
  5373. (isResizableFromEnd ?
  5374. '<div class="fc-resizer fc-end-resizer" />' :
  5375. ''
  5376. ) +
  5377. '</a>';
  5378. },
  5379. /* Seg Position Utils
  5380. ------------------------------------------------------------------------------------------------------------------*/
  5381. // Refreshes the CSS top/bottom coordinates for each segment element.
  5382. // Works when called after initial render, after a window resize/zoom for example.
  5383. updateSegVerticals: function(segs) {
  5384. this.computeSegVerticals(segs);
  5385. this.assignSegVerticals(segs);
  5386. },
  5387. // For each segment in an array, computes and assigns its top and bottom properties
  5388. computeSegVerticals: function(segs) {
  5389. var i, seg;
  5390. for (i = 0; i < segs.length; i++) {
  5391. seg = segs[i];
  5392. seg.top = this.computeDateTop(seg.start, seg.start);
  5393. seg.bottom = this.computeDateTop(seg.end, seg.start);
  5394. }
  5395. },
  5396. // Given segments that already have their top/bottom properties computed, applies those values to
  5397. // the segments' elements.
  5398. assignSegVerticals: function(segs) {
  5399. var i, seg;
  5400. for (i = 0; i < segs.length; i++) {
  5401. seg = segs[i];
  5402. seg.el.css(this.generateSegVerticalCss(seg));
  5403. }
  5404. },
  5405. // Generates an object with CSS properties for the top/bottom coordinates of a segment element
  5406. generateSegVerticalCss: function(seg) {
  5407. return {
  5408. top: seg.top,
  5409. bottom: -seg.bottom // flipped because needs to be space beyond bottom edge of event container
  5410. };
  5411. },
  5412. /* Foreground Event Positioning Utils
  5413. ------------------------------------------------------------------------------------------------------------------*/
  5414. // Given segments that are assumed to all live in the *same column*,
  5415. // compute their verical/horizontal coordinates and assign to their elements.
  5416. updateFgSegCoords: function(segs) {
  5417. this.computeSegVerticals(segs); // horizontals relies on this
  5418. this.computeFgSegHorizontals(segs); // compute horizontal coordinates, z-index's, and reorder the array
  5419. this.assignSegVerticals(segs);
  5420. this.assignFgSegHorizontals(segs);
  5421. },
  5422. // Given an array of segments that are all in the same column, sets the backwardCoord and forwardCoord on each.
  5423. // NOTE: Also reorders the given array by date!
  5424. computeFgSegHorizontals: function(segs) {
  5425. var levels;
  5426. var level0;
  5427. var i;
  5428. this.sortEventSegs(segs); // order by certain criteria
  5429. levels = buildSlotSegLevels(segs);
  5430. computeForwardSlotSegs(levels);
  5431. if ((level0 = levels[0])) {
  5432. for (i = 0; i < level0.length; i++) {
  5433. computeSlotSegPressures(level0[i]);
  5434. }
  5435. for (i = 0; i < level0.length; i++) {
  5436. this.computeFgSegForwardBack(level0[i], 0, 0);
  5437. }
  5438. }
  5439. },
  5440. // Calculate seg.forwardCoord and seg.backwardCoord for the segment, where both values range
  5441. // from 0 to 1. If the calendar is left-to-right, the seg.backwardCoord maps to "left" and
  5442. // seg.forwardCoord maps to "right" (via percentage). Vice-versa if the calendar is right-to-left.
  5443. //
  5444. // The segment might be part of a "series", which means consecutive segments with the same pressure
  5445. // who's width is unknown until an edge has been hit. `seriesBackwardPressure` is the number of
  5446. // segments behind this one in the current series, and `seriesBackwardCoord` is the starting
  5447. // coordinate of the first segment in the series.
  5448. computeFgSegForwardBack: function(seg, seriesBackwardPressure, seriesBackwardCoord) {
  5449. var forwardSegs = seg.forwardSegs;
  5450. var i;
  5451. if (seg.forwardCoord === undefined) { // not already computed
  5452. if (!forwardSegs.length) {
  5453. // if there are no forward segments, this segment should butt up against the edge
  5454. seg.forwardCoord = 1;
  5455. }
  5456. else {
  5457. // sort highest pressure first
  5458. this.sortForwardSegs(forwardSegs);
  5459. // this segment's forwardCoord will be calculated from the backwardCoord of the
  5460. // highest-pressure forward segment.
  5461. this.computeFgSegForwardBack(forwardSegs[0], seriesBackwardPressure + 1, seriesBackwardCoord);
  5462. seg.forwardCoord = forwardSegs[0].backwardCoord;
  5463. }
  5464. // calculate the backwardCoord from the forwardCoord. consider the series
  5465. seg.backwardCoord = seg.forwardCoord -
  5466. (seg.forwardCoord - seriesBackwardCoord) / // available width for series
  5467. (seriesBackwardPressure + 1); // # of segments in the series
  5468. // use this segment's coordinates to computed the coordinates of the less-pressurized
  5469. // forward segments
  5470. for (i=0; i<forwardSegs.length; i++) {
  5471. this.computeFgSegForwardBack(forwardSegs[i], 0, seg.forwardCoord);
  5472. }
  5473. }
  5474. },
  5475. sortForwardSegs: function(forwardSegs) {
  5476. forwardSegs.sort(proxy(this, 'compareForwardSegs'));
  5477. },
  5478. // A cmp function for determining which forward segment to rely on more when computing coordinates.
  5479. compareForwardSegs: function(seg1, seg2) {
  5480. // put higher-pressure first
  5481. return seg2.forwardPressure - seg1.forwardPressure ||
  5482. // put segments that are closer to initial edge first (and favor ones with no coords yet)
  5483. (seg1.backwardCoord || 0) - (seg2.backwardCoord || 0) ||
  5484. // do normal sorting...
  5485. this.compareEventSegs(seg1, seg2);
  5486. },
  5487. // Given foreground event segments that have already had their position coordinates computed,
  5488. // assigns position-related CSS values to their elements.
  5489. assignFgSegHorizontals: function(segs) {
  5490. var i, seg;
  5491. for (i = 0; i < segs.length; i++) {
  5492. seg = segs[i];
  5493. seg.el.css(this.generateFgSegHorizontalCss(seg));
  5494. // if the height is short, add a className for alternate styling
  5495. if (seg.bottom - seg.top < 30) {
  5496. seg.el.addClass('fc-short');
  5497. }
  5498. }
  5499. },
  5500. // Generates an object with CSS properties/values that should be applied to an event segment element.
  5501. // Contains important positioning-related properties that should be applied to any event element, customized or not.
  5502. generateFgSegHorizontalCss: function(seg) {
  5503. var shouldOverlap = this.view.opt('slotEventOverlap');
  5504. var backwardCoord = seg.backwardCoord; // the left side if LTR. the right side if RTL. floating-point
  5505. var forwardCoord = seg.forwardCoord; // the right side if LTR. the left side if RTL. floating-point
  5506. var props = this.generateSegVerticalCss(seg); // get top/bottom first
  5507. var left; // amount of space from left edge, a fraction of the total width
  5508. var right; // amount of space from right edge, a fraction of the total width
  5509. if (shouldOverlap) {
  5510. // double the width, but don't go beyond the maximum forward coordinate (1.0)
  5511. forwardCoord = Math.min(1, backwardCoord + (forwardCoord - backwardCoord) * 2);
  5512. }
  5513. if (this.isRTL) {
  5514. left = 1 - forwardCoord;
  5515. right = backwardCoord;
  5516. }
  5517. else {
  5518. left = backwardCoord;
  5519. right = 1 - forwardCoord;
  5520. }
  5521. props.zIndex = seg.level + 1; // convert from 0-base to 1-based
  5522. props.left = left * 100 + '%';
  5523. props.right = right * 100 + '%';
  5524. if (shouldOverlap && seg.forwardPressure) {
  5525. // add padding to the edge so that forward stacked events don't cover the resizer's icon
  5526. props[this.isRTL ? 'marginLeft' : 'marginRight'] = 10 * 2; // 10 is a guesstimate of the icon's width
  5527. }
  5528. return props;
  5529. }
  5530. });
  5531. // Builds an array of segments "levels". The first level will be the leftmost tier of segments if the calendar is
  5532. // left-to-right, or the rightmost if the calendar is right-to-left. Assumes the segments are already ordered by date.
  5533. function buildSlotSegLevels(segs) {
  5534. var levels = [];
  5535. var i, seg;
  5536. var j;
  5537. for (i=0; i<segs.length; i++) {
  5538. seg = segs[i];
  5539. // go through all the levels and stop on the first level where there are no collisions
  5540. for (j=0; j<levels.length; j++) {
  5541. if (!computeSlotSegCollisions(seg, levels[j]).length) {
  5542. break;
  5543. }
  5544. }
  5545. seg.level = j;
  5546. (levels[j] || (levels[j] = [])).push(seg);
  5547. }
  5548. return levels;
  5549. }
  5550. // For every segment, figure out the other segments that are in subsequent
  5551. // levels that also occupy the same vertical space. Accumulate in seg.forwardSegs
  5552. function computeForwardSlotSegs(levels) {
  5553. var i, level;
  5554. var j, seg;
  5555. var k;
  5556. for (i=0; i<levels.length; i++) {
  5557. level = levels[i];
  5558. for (j=0; j<level.length; j++) {
  5559. seg = level[j];
  5560. seg.forwardSegs = [];
  5561. for (k=i+1; k<levels.length; k++) {
  5562. computeSlotSegCollisions(seg, levels[k], seg.forwardSegs);
  5563. }
  5564. }
  5565. }
  5566. }
  5567. // Figure out which path forward (via seg.forwardSegs) results in the longest path until
  5568. // the furthest edge is reached. The number of segments in this path will be seg.forwardPressure
  5569. function computeSlotSegPressures(seg) {
  5570. var forwardSegs = seg.forwardSegs;
  5571. var forwardPressure = 0;
  5572. var i, forwardSeg;
  5573. if (seg.forwardPressure === undefined) { // not already computed
  5574. for (i=0; i<forwardSegs.length; i++) {
  5575. forwardSeg = forwardSegs[i];
  5576. // figure out the child's maximum forward path
  5577. computeSlotSegPressures(forwardSeg);
  5578. // either use the existing maximum, or use the child's forward pressure
  5579. // plus one (for the forwardSeg itself)
  5580. forwardPressure = Math.max(
  5581. forwardPressure,
  5582. 1 + forwardSeg.forwardPressure
  5583. );
  5584. }
  5585. seg.forwardPressure = forwardPressure;
  5586. }
  5587. }
  5588. // Find all the segments in `otherSegs` that vertically collide with `seg`.
  5589. // Append into an optionally-supplied `results` array and return.
  5590. function computeSlotSegCollisions(seg, otherSegs, results) {
  5591. results = results || [];
  5592. for (var i=0; i<otherSegs.length; i++) {
  5593. if (isSlotSegCollision(seg, otherSegs[i])) {
  5594. results.push(otherSegs[i]);
  5595. }
  5596. }
  5597. return results;
  5598. }
  5599. // Do these segments occupy the same vertical space?
  5600. function isSlotSegCollision(seg1, seg2) {
  5601. return seg1.bottom > seg2.top && seg1.top < seg2.bottom;
  5602. }
  5603. ;;
  5604. /* An abstract class from which other views inherit from
  5605. ----------------------------------------------------------------------------------------------------------------------*/
  5606. var View = FC.View = Class.extend({
  5607. type: null, // subclass' view name (string)
  5608. name: null, // deprecated. use `type` instead
  5609. title: null, // the text that will be displayed in the header's title
  5610. calendar: null, // owner Calendar object
  5611. options: null, // hash containing all options. already merged with view-specific-options
  5612. el: null, // the view's containing element. set by Calendar
  5613. displaying: null, // a promise representing the state of rendering. null if no render requested
  5614. isSkeletonRendered: false,
  5615. isEventsRendered: false,
  5616. // range the view is actually displaying (moments)
  5617. start: null,
  5618. end: null, // exclusive
  5619. // range the view is formally responsible for (moments)
  5620. // may be different from start/end. for example, a month view might have 1st-31st, excluding padded dates
  5621. intervalStart: null,
  5622. intervalEnd: null, // exclusive
  5623. intervalDuration: null,
  5624. intervalUnit: null, // name of largest unit being displayed, like "month" or "week"
  5625. isRTL: false,
  5626. isSelected: false, // boolean whether a range of time is user-selected or not
  5627. eventOrderSpecs: null, // criteria for ordering events when they have same date/time
  5628. // subclasses can optionally use a scroll container
  5629. scrollerEl: null, // the element that will most likely scroll when content is too tall
  5630. scrollTop: null, // cached vertical scroll value
  5631. // classNames styled by jqui themes
  5632. widgetHeaderClass: null,
  5633. widgetContentClass: null,
  5634. highlightStateClass: null,
  5635. // for date utils, computed from options
  5636. nextDayThreshold: null,
  5637. isHiddenDayHash: null,
  5638. // document handlers, bound to `this` object
  5639. documentMousedownProxy: null, // TODO: doesn't work with touch
  5640. // now indicator
  5641. isNowIndicatorRendered: null,
  5642. initialNowDate: null, // result first getNow call
  5643. initialNowQueriedMs: null, // ms time the getNow was called
  5644. nowIndicatorTimeoutID: null, // for refresh timing of now indicator
  5645. nowIndicatorIntervalID: null, // "
  5646. constructor: function(calendar, type, options, intervalDuration) {
  5647. this.calendar = calendar;
  5648. this.type = this.name = type; // .name is deprecated
  5649. this.options = options;
  5650. this.intervalDuration = intervalDuration || moment.duration(1, 'day');
  5651. this.nextDayThreshold = moment.duration(this.opt('nextDayThreshold'));
  5652. this.initThemingProps();
  5653. this.initHiddenDays();
  5654. this.isRTL = this.opt('isRTL');
  5655. this.eventOrderSpecs = parseFieldSpecs(this.opt('eventOrder'));
  5656. this.documentMousedownProxy = proxy(this, 'documentMousedown');
  5657. this.initialize();
  5658. },
  5659. // A good place for subclasses to initialize member variables
  5660. initialize: function() {
  5661. // subclasses can implement
  5662. },
  5663. // Retrieves an option with the given name
  5664. opt: function(name) {
  5665. return this.options[name];
  5666. },
  5667. // Triggers handlers that are view-related. Modifies args before passing to calendar.
  5668. trigger: function(name, thisObj) { // arguments beyond thisObj are passed along
  5669. var calendar = this.calendar;
  5670. return calendar.trigger.apply(
  5671. calendar,
  5672. [name, thisObj || this].concat(
  5673. Array.prototype.slice.call(arguments, 2), // arguments beyond thisObj
  5674. [ this ] // always make the last argument a reference to the view. TODO: deprecate
  5675. )
  5676. );
  5677. },
  5678. /* Dates
  5679. ------------------------------------------------------------------------------------------------------------------*/
  5680. // Updates all internal dates to center around the given current unzoned date.
  5681. setDate: function(date) {
  5682. this.setRange(this.computeRange(date));
  5683. },
  5684. // Updates all internal dates for displaying the given unzoned range.
  5685. setRange: function(range) {
  5686. jQuery.extend(this, range); // assigns every property to this object's member variables
  5687. this.updateTitle();
  5688. },
  5689. // Given a single current unzoned date, produce information about what range to display.
  5690. // Subclasses can override. Must return all properties.
  5691. computeRange: function(date) {
  5692. var intervalUnit = computeIntervalUnit(this.intervalDuration);
  5693. var intervalStart = date.clone().startOf(intervalUnit);
  5694. var intervalEnd = intervalStart.clone().add(this.intervalDuration);
  5695. var start, end;
  5696. // normalize the range's time-ambiguity
  5697. if (/year|month|week|day/.test(intervalUnit)) { // whole-days?
  5698. intervalStart.stripTime();
  5699. intervalEnd.stripTime();
  5700. }
  5701. else { // needs to have a time?
  5702. if (!intervalStart.hasTime()) {
  5703. intervalStart = this.calendar.time(0); // give 00:00 time
  5704. }
  5705. if (!intervalEnd.hasTime()) {
  5706. intervalEnd = this.calendar.time(0); // give 00:00 time
  5707. }
  5708. }
  5709. start = intervalStart.clone();
  5710. start = this.skipHiddenDays(start);
  5711. end = intervalEnd.clone();
  5712. end = this.skipHiddenDays(end, -1, true); // exclusively move backwards
  5713. return {
  5714. intervalUnit: intervalUnit,
  5715. intervalStart: intervalStart,
  5716. intervalEnd: intervalEnd,
  5717. start: start,
  5718. end: end
  5719. };
  5720. },
  5721. // Computes the new date when the user hits the prev button, given the current date
  5722. computePrevDate: function(date) {
  5723. return this.massageCurrentDate(
  5724. date.clone().startOf(this.intervalUnit).subtract(this.intervalDuration), -1
  5725. );
  5726. },
  5727. // Computes the new date when the user hits the next button, given the current date
  5728. computeNextDate: function(date) {
  5729. return this.massageCurrentDate(
  5730. date.clone().startOf(this.intervalUnit).add(this.intervalDuration)
  5731. );
  5732. },
  5733. // Given an arbitrarily calculated current date of the calendar, returns a date that is ensured to be completely
  5734. // visible. `direction` is optional and indicates which direction the current date was being
  5735. // incremented or decremented (1 or -1).
  5736. massageCurrentDate: function(date, direction) {
  5737. if (this.intervalDuration.as('days') <= 1) { // if the view displays a single day or smaller
  5738. if (this.isHiddenDay(date)) {
  5739. date = this.skipHiddenDays(date, direction);
  5740. date.startOf('day');
  5741. }
  5742. }
  5743. return date;
  5744. },
  5745. /* Title and Date Formatting
  5746. ------------------------------------------------------------------------------------------------------------------*/
  5747. // Sets the view's title property to the most updated computed value
  5748. updateTitle: function() {
  5749. this.title = this.computeTitle();
  5750. },
  5751. // Computes what the title at the top of the calendar should be for this view
  5752. computeTitle: function() {
  5753. return this.formatRange(
  5754. {
  5755. // in case intervalStart/End has a time, make sure timezone is correct
  5756. start: this.calendar.applyTimezone(this.intervalStart),
  5757. end: this.calendar.applyTimezone(this.intervalEnd)
  5758. },
  5759. this.opt('titleFormat') || this.computeTitleFormat(),
  5760. this.opt('titleRangeSeparator')
  5761. );
  5762. },
  5763. // Generates the format string that should be used to generate the title for the current date range.
  5764. // Attempts to compute the most appropriate format if not explicitly specified with `titleFormat`.
  5765. computeTitleFormat: function() {
  5766. if (this.intervalUnit == 'year') {
  5767. return 'YYYY';
  5768. }
  5769. else if (this.intervalUnit == 'month') {
  5770. return this.opt('monthYearFormat'); // like "September 2014"
  5771. }
  5772. else if (this.intervalDuration.as('days') > 1) {
  5773. return 'll'; // multi-day range. shorter, like "Sep 9 - 10 2014"
  5774. }
  5775. else {
  5776. return 'LL'; // one day. longer, like "September 9 2014"
  5777. }
  5778. },
  5779. // Utility for formatting a range. Accepts a range object, formatting string, and optional separator.
  5780. // Displays all-day ranges naturally, with an inclusive end. Takes the current isRTL into account.
  5781. // The timezones of the dates within `range` will be respected.
  5782. formatRange: function(range, formatStr, separator) {
  5783. var end = range.end;
  5784. if (!end.hasTime()) { // all-day?
  5785. end = end.clone().subtract(1); // convert to inclusive. last ms of previous day
  5786. }
  5787. return formatRange(range.start, end, formatStr, separator, this.opt('isRTL'));
  5788. },
  5789. /* Rendering
  5790. ------------------------------------------------------------------------------------------------------------------*/
  5791. // Sets the container element that the view should render inside of.
  5792. // Does other DOM-related initializations.
  5793. setElement: function(el) {
  5794. this.el = el;
  5795. this.bindGlobalHandlers();
  5796. },
  5797. // Removes the view's container element from the DOM, clearing any content beforehand.
  5798. // Undoes any other DOM-related attachments.
  5799. removeElement: function() {
  5800. this.clear(); // clears all content
  5801. // clean up the skeleton
  5802. if (this.isSkeletonRendered) {
  5803. this.unrenderSkeleton();
  5804. this.isSkeletonRendered = false;
  5805. }
  5806. this.unbindGlobalHandlers();
  5807. this.el.remove();
  5808. // NOTE: don't null-out this.el in case the View was destroyed within an API callback.
  5809. // We don't null-out the View's other jQuery element references upon destroy,
  5810. // so we shouldn't kill this.el either.
  5811. },
  5812. // Does everything necessary to display the view centered around the given unzoned date.
  5813. // Does every type of rendering EXCEPT rendering events.
  5814. // Is asychronous and returns a promise.
  5815. display: function(date) {
  5816. var _this = this;
  5817. var scrollState = null;
  5818. if (this.displaying) {
  5819. scrollState = this.queryScroll();
  5820. }
  5821. this.calendar.freezeContentHeight();
  5822. return this.clear().then(function() { // clear the content first (async)
  5823. return (
  5824. _this.displaying =
  5825. jQuery.when(_this.displayView(date)) // displayView might return a promise
  5826. .then(function() {
  5827. _this.forceScroll(_this.computeInitialScroll(scrollState));
  5828. _this.calendar.unfreezeContentHeight();
  5829. _this.triggerRender();
  5830. })
  5831. );
  5832. });
  5833. },
  5834. // Does everything necessary to clear the content of the view.
  5835. // Clears dates and events. Does not clear the skeleton.
  5836. // Is asychronous and returns a promise.
  5837. clear: function() {
  5838. var _this = this;
  5839. var displaying = this.displaying;
  5840. if (displaying) { // previously displayed, or in the process of being displayed?
  5841. return displaying.then(function() { // wait for the display to finish
  5842. _this.displaying = null;
  5843. _this.clearEvents();
  5844. return _this.clearView(); // might return a promise. chain it
  5845. });
  5846. }
  5847. else {
  5848. return jQuery.when(); // an immediately-resolved promise
  5849. }
  5850. },
  5851. // Displays the view's non-event content, such as date-related content or anything required by events.
  5852. // Renders the view's non-content skeleton if necessary.
  5853. // Can be asynchronous and return a promise.
  5854. displayView: function(date) {
  5855. if (!this.isSkeletonRendered) {
  5856. this.renderSkeleton();
  5857. this.isSkeletonRendered = true;
  5858. }
  5859. if (date) {
  5860. this.setDate(date);
  5861. }
  5862. if (this.render) {
  5863. this.render(); // TODO: deprecate
  5864. }
  5865. this.renderDates();
  5866. this.updateSize();
  5867. this.renderBusinessHours(); // might need coordinates, so should go after updateSize()
  5868. this.startNowIndicator();
  5869. },
  5870. // Unrenders the view content that was rendered in displayView.
  5871. // Can be asynchronous and return a promise.
  5872. clearView: function() {
  5873. this.unselect();
  5874. this.stopNowIndicator();
  5875. this.triggerUnrender();
  5876. this.unrenderBusinessHours();
  5877. this.unrenderDates();
  5878. if (this.destroy) {
  5879. this.destroy(); // TODO: deprecate
  5880. }
  5881. },
  5882. // Renders the basic structure of the view before any content is rendered
  5883. renderSkeleton: function() {
  5884. // subclasses should implement
  5885. },
  5886. // Unrenders the basic structure of the view
  5887. unrenderSkeleton: function() {
  5888. // subclasses should implement
  5889. },
  5890. // Renders the view's date-related content.
  5891. // Assumes setRange has already been called and the skeleton has already been rendered.
  5892. renderDates: function() {
  5893. // subclasses should implement
  5894. },
  5895. // Unrenders the view's date-related content
  5896. unrenderDates: function() {
  5897. // subclasses should override
  5898. },
  5899. // Signals that the view's content has been rendered
  5900. triggerRender: function() {
  5901. this.trigger('viewRender', this, this, this.el);
  5902. },
  5903. // Signals that the view's content is about to be unrendered
  5904. triggerUnrender: function() {
  5905. this.trigger('viewDestroy', this, this, this.el);
  5906. },
  5907. // Binds DOM handlers to elements that reside outside the view container, such as the document
  5908. bindGlobalHandlers: function() {
  5909. jQuery(document).on('mousedown', this.documentMousedownProxy);
  5910. },
  5911. // Unbinds DOM handlers from elements that reside outside the view container
  5912. unbindGlobalHandlers: function() {
  5913. jQuery(document).off('mousedown', this.documentMousedownProxy);
  5914. },
  5915. // Initializes internal variables related to theming
  5916. initThemingProps: function() {
  5917. var tm = this.opt('theme') ? 'ui' : 'fc';
  5918. this.widgetHeaderClass = tm + '-widget-header';
  5919. this.widgetContentClass = tm + '-widget-content';
  5920. this.highlightStateClass = tm + '-state-highlight';
  5921. },
  5922. /* Business Hours
  5923. ------------------------------------------------------------------------------------------------------------------*/
  5924. // Renders business-hours onto the view. Assumes updateSize has already been called.
  5925. renderBusinessHours: function() {
  5926. // subclasses should implement
  5927. },
  5928. // Unrenders previously-rendered business-hours
  5929. unrenderBusinessHours: function() {
  5930. // subclasses should implement
  5931. },
  5932. /* Now Indicator
  5933. ------------------------------------------------------------------------------------------------------------------*/
  5934. // Immediately render the current time indicator and begins re-rendering it at an interval,
  5935. // which is defined by this.getNowIndicatorUnit().
  5936. // TODO: somehow do this for the current whole day's background too
  5937. startNowIndicator: function() {
  5938. var _this = this;
  5939. var unit;
  5940. var update;
  5941. var delay; // ms wait value
  5942. if (this.opt('nowIndicator')) {
  5943. unit = this.getNowIndicatorUnit();
  5944. if (unit) {
  5945. update = proxy(this, 'updateNowIndicator'); // bind to `this`
  5946. this.initialNowDate = this.calendar.getNow();
  5947. this.initialNowQueriedMs = +new Date();
  5948. this.renderNowIndicator(this.initialNowDate);
  5949. this.isNowIndicatorRendered = true;
  5950. // wait until the beginning of the next interval
  5951. delay = this.initialNowDate.clone().startOf(unit).add(1, unit) - this.initialNowDate;
  5952. this.nowIndicatorTimeoutID = setTimeout(function() {
  5953. _this.nowIndicatorTimeoutID = null;
  5954. update();
  5955. delay = +moment.duration(1, unit);
  5956. delay = Math.max(100, delay); // prevent too frequent
  5957. _this.nowIndicatorIntervalID = setInterval(update, delay); // update every interval
  5958. }, delay);
  5959. }
  5960. }
  5961. },
  5962. // rerenders the now indicator, computing the new current time from the amount of time that has passed
  5963. // since the initial getNow call.
  5964. updateNowIndicator: function() {
  5965. if (this.isNowIndicatorRendered) {
  5966. this.unrenderNowIndicator();
  5967. this.renderNowIndicator(
  5968. this.initialNowDate.clone().add(new Date() - this.initialNowQueriedMs) // add ms
  5969. );
  5970. }
  5971. },
  5972. // Immediately unrenders the view's current time indicator and stops any re-rendering timers.
  5973. // Won't cause side effects if indicator isn't rendered.
  5974. stopNowIndicator: function() {
  5975. if (this.isNowIndicatorRendered) {
  5976. if (this.nowIndicatorTimeoutID) {
  5977. clearTimeout(this.nowIndicatorTimeoutID);
  5978. this.nowIndicatorTimeoutID = null;
  5979. }
  5980. if (this.nowIndicatorIntervalID) {
  5981. clearTimeout(this.nowIndicatorIntervalID);
  5982. this.nowIndicatorIntervalID = null;
  5983. }
  5984. this.unrenderNowIndicator();
  5985. this.isNowIndicatorRendered = false;
  5986. }
  5987. },
  5988. // Returns a string unit, like 'second' or 'minute' that defined how often the current time indicator
  5989. // should be refreshed. If something falsy is returned, no time indicator is rendered at all.
  5990. getNowIndicatorUnit: function() {
  5991. // subclasses should implement
  5992. },
  5993. // Renders a current time indicator at the given datetime
  5994. renderNowIndicator: function(date) {
  5995. // subclasses should implement
  5996. },
  5997. // Undoes the rendering actions from renderNowIndicator
  5998. unrenderNowIndicator: function() {
  5999. // subclasses should implement
  6000. },
  6001. /* Dimensions
  6002. ------------------------------------------------------------------------------------------------------------------*/
  6003. // Refreshes anything dependant upon sizing of the container element of the grid
  6004. updateSize: function(isResize) {
  6005. var scrollState;
  6006. if (isResize) {
  6007. scrollState = this.queryScroll();
  6008. }
  6009. this.updateHeight(isResize);
  6010. this.updateWidth(isResize);
  6011. this.updateNowIndicator();
  6012. if (isResize) {
  6013. this.setScroll(scrollState);
  6014. }
  6015. },
  6016. // Refreshes the horizontal dimensions of the calendar
  6017. updateWidth: function(isResize) {
  6018. // subclasses should implement
  6019. },
  6020. // Refreshes the vertical dimensions of the calendar
  6021. updateHeight: function(isResize) {
  6022. var calendar = this.calendar; // we poll the calendar for height information
  6023. this.setHeight(
  6024. calendar.getSuggestedViewHeight(),
  6025. calendar.isHeightAuto()
  6026. );
  6027. },
  6028. // Updates the vertical dimensions of the calendar to the specified height.
  6029. // if `isAuto` is set to true, height becomes merely a suggestion and the view should use its "natural" height.
  6030. setHeight: function(height, isAuto) {
  6031. // subclasses should implement
  6032. },
  6033. /* Scroller
  6034. ------------------------------------------------------------------------------------------------------------------*/
  6035. // Given the total height of the view, return the number of pixels that should be used for the scroller.
  6036. // Utility for subclasses.
  6037. computeScrollerHeight: function(totalHeight) {
  6038. var scrollerEl = this.scrollerEl;
  6039. var both;
  6040. var otherHeight; // cumulative height of everything that is not the scrollerEl in the view (header+borders)
  6041. both = this.el.add(scrollerEl);
  6042. // fuckin IE8/9/10/11 sometimes returns 0 for dimensions. this weird hack was the only thing that worked
  6043. both.css({
  6044. position: 'relative', // cause a reflow, which will force fresh dimension recalculation
  6045. left: -1 // ensure reflow in case the el was already relative. negative is less likely to cause new scroll
  6046. });
  6047. otherHeight = this.el.outerHeight() - scrollerEl.height(); // grab the dimensions
  6048. both.css({ position: '', left: '' }); // undo hack
  6049. return totalHeight - otherHeight;
  6050. },
  6051. // Computes the initial pre-configured scroll state prior to allowing the user to change it.
  6052. // Given the scroll state from the previous rendering. If first time rendering, given null.
  6053. computeInitialScroll: function(previousScrollState) {
  6054. return 0;
  6055. },
  6056. // Retrieves the view's current natural scroll state. Can return an arbitrary format.
  6057. queryScroll: function() {
  6058. if (this.scrollerEl) {
  6059. return this.scrollerEl.scrollTop(); // operates on scrollerEl by default
  6060. }
  6061. },
  6062. // Sets the view's scroll state. Will accept the same format computeInitialScroll and queryScroll produce.
  6063. setScroll: function(scrollState) {
  6064. if (this.scrollerEl) {
  6065. return this.scrollerEl.scrollTop(scrollState); // operates on scrollerEl by default
  6066. }
  6067. },
  6068. // Sets the scroll state, making sure to overcome any predefined scroll value the browser has in mind
  6069. forceScroll: function(scrollState) {
  6070. var _this = this;
  6071. this.setScroll(scrollState);
  6072. setTimeout(function() {
  6073. _this.setScroll(scrollState);
  6074. }, 0);
  6075. },
  6076. /* Event Elements / Segments
  6077. ------------------------------------------------------------------------------------------------------------------*/
  6078. // Does everything necessary to display the given events onto the current view
  6079. displayEvents: function(events) {
  6080. var scrollState = this.queryScroll();
  6081. this.clearEvents();
  6082. this.renderEvents(events);
  6083. this.isEventsRendered = true;
  6084. this.setScroll(scrollState);
  6085. this.triggerEventRender();
  6086. },
  6087. // Does everything necessary to clear the view's currently-rendered events
  6088. clearEvents: function() {
  6089. var scrollState;
  6090. if (this.isEventsRendered) {
  6091. // TODO: optimize: if we know this is part of a displayEvents call, don't queryScroll/setScroll
  6092. scrollState = this.queryScroll();
  6093. this.triggerEventUnrender();
  6094. if (this.destroyEvents) {
  6095. this.destroyEvents(); // TODO: deprecate
  6096. }
  6097. this.unrenderEvents();
  6098. this.setScroll(scrollState);
  6099. this.isEventsRendered = false;
  6100. }
  6101. },
  6102. // Renders the events onto the view.
  6103. renderEvents: function(events) {
  6104. // subclasses should implement
  6105. },
  6106. // Removes event elements from the view.
  6107. unrenderEvents: function() {
  6108. // subclasses should implement
  6109. },
  6110. // Signals that all events have been rendered
  6111. triggerEventRender: function() {
  6112. this.renderedEventSegEach(function(seg) {
  6113. this.trigger('eventAfterRender', seg.event, seg.event, seg.el);
  6114. });
  6115. this.trigger('eventAfterAllRender');
  6116. },
  6117. // Signals that all event elements are about to be removed
  6118. triggerEventUnrender: function() {
  6119. this.renderedEventSegEach(function(seg) {
  6120. this.trigger('eventDestroy', seg.event, seg.event, seg.el);
  6121. });
  6122. },
  6123. // Given an event and the default element used for rendering, returns the element that should actually be used.
  6124. // Basically runs events and elements through the eventRender hook.
  6125. resolveEventEl: function(event, el) {
  6126. var custom = this.trigger('eventRender', event, event, el);
  6127. if (custom === false) { // means don't render at all
  6128. el = null;
  6129. }
  6130. else if (custom && custom !== true) {
  6131. el = jQuery(custom);
  6132. }
  6133. return el;
  6134. },
  6135. // Hides all rendered event segments linked to the given event
  6136. showEvent: function(event) {
  6137. this.renderedEventSegEach(function(seg) {
  6138. seg.el.css('visibility', '');
  6139. }, event);
  6140. },
  6141. // Shows all rendered event segments linked to the given event
  6142. hideEvent: function(event) {
  6143. this.renderedEventSegEach(function(seg) {
  6144. seg.el.css('visibility', 'hidden');
  6145. }, event);
  6146. },
  6147. // Iterates through event segments that have been rendered (have an el). Goes through all by default.
  6148. // If the optional `event` argument is specified, only iterates through segments linked to that event.
  6149. // The `this` value of the callback function will be the view.
  6150. renderedEventSegEach: function(func, event) {
  6151. var segs = this.getEventSegs();
  6152. var i;
  6153. for (i = 0; i < segs.length; i++) {
  6154. if (!event || segs[i].event._id === event._id) {
  6155. if (segs[i].el) {
  6156. func.call(this, segs[i]);
  6157. }
  6158. }
  6159. }
  6160. },
  6161. // Retrieves all the rendered segment objects for the view
  6162. getEventSegs: function() {
  6163. // subclasses must implement
  6164. return [];
  6165. },
  6166. /* Event Drag-n-Drop
  6167. ------------------------------------------------------------------------------------------------------------------*/
  6168. // Computes if the given event is allowed to be dragged by the user
  6169. isEventDraggable: function(event) {
  6170. var source = event.source || {};
  6171. return firstDefined(
  6172. event.startEditable,
  6173. source.startEditable,
  6174. this.opt('eventStartEditable'),
  6175. event.editable,
  6176. source.editable,
  6177. this.opt('editable')
  6178. );
  6179. },
  6180. // Must be called when an event in the view is dropped onto new location.
  6181. // `dropLocation` is an object that contains the new zoned start/end/allDay values for the event.
  6182. reportEventDrop: function(event, dropLocation, largeUnit, el, ev) {
  6183. var calendar = this.calendar;
  6184. var mutateResult = calendar.mutateEvent(event, dropLocation, largeUnit);
  6185. var undoFunc = function() {
  6186. mutateResult.undo();
  6187. calendar.reportEventChange();
  6188. };
  6189. this.triggerEventDrop(event, mutateResult.dateDelta, undoFunc, el, ev);
  6190. calendar.reportEventChange(); // will rerender events
  6191. },
  6192. // Triggers event-drop handlers that have subscribed via the API
  6193. triggerEventDrop: function(event, dateDelta, undoFunc, el, ev) {
  6194. this.trigger('eventDrop', el[0], event, dateDelta, undoFunc, ev, {}); // {} = jqui dummy
  6195. },
  6196. /* External Element Drag-n-Drop
  6197. ------------------------------------------------------------------------------------------------------------------*/
  6198. // Must be called when an external element, via jQuery UI, has been dropped onto the calendar.
  6199. // `meta` is the parsed data that has been embedded into the dragging event.
  6200. // `dropLocation` is an object that contains the new zoned start/end/allDay values for the event.
  6201. reportExternalDrop: function(meta, dropLocation, el, ev, ui) {
  6202. var eventProps = meta.eventProps;
  6203. var eventInput;
  6204. var event;
  6205. // Try to build an event object and render it. TODO: decouple the two
  6206. if (eventProps) {
  6207. eventInput = jQuery.extend({}, eventProps, dropLocation);
  6208. event = this.calendar.renderEvent(eventInput, meta.stick)[0]; // renderEvent returns an array
  6209. }
  6210. this.triggerExternalDrop(event, dropLocation, el, ev, ui);
  6211. },
  6212. // Triggers external-drop handlers that have subscribed via the API
  6213. triggerExternalDrop: function(event, dropLocation, el, ev, ui) {
  6214. // trigger 'drop' regardless of whether element represents an event
  6215. this.trigger('drop', el[0], dropLocation.start, ev, ui);
  6216. if (event) {
  6217. this.trigger('eventReceive', null, event); // signal an external event landed
  6218. }
  6219. },
  6220. /* Drag-n-Drop Rendering (for both events and external elements)
  6221. ------------------------------------------------------------------------------------------------------------------*/
  6222. // Renders a visual indication of a event or external-element drag over the given drop zone.
  6223. // If an external-element, seg will be `null`
  6224. renderDrag: function(dropLocation, seg) {
  6225. // subclasses must implement
  6226. },
  6227. // Unrenders a visual indication of an event or external-element being dragged.
  6228. unrenderDrag: function() {
  6229. // subclasses must implement
  6230. },
  6231. /* Event Resizing
  6232. ------------------------------------------------------------------------------------------------------------------*/
  6233. // Computes if the given event is allowed to be resized from its starting edge
  6234. isEventResizableFromStart: function(event) {
  6235. return this.opt('eventResizableFromStart') && this.isEventResizable(event);
  6236. },
  6237. // Computes if the given event is allowed to be resized from its ending edge
  6238. isEventResizableFromEnd: function(event) {
  6239. return this.isEventResizable(event);
  6240. },
  6241. // Computes if the given event is allowed to be resized by the user at all
  6242. isEventResizable: function(event) {
  6243. var source = event.source || {};
  6244. return firstDefined(
  6245. event.durationEditable,
  6246. source.durationEditable,
  6247. this.opt('eventDurationEditable'),
  6248. event.editable,
  6249. source.editable,
  6250. this.opt('editable')
  6251. );
  6252. },
  6253. // Must be called when an event in the view has been resized to a new length
  6254. reportEventResize: function(event, resizeLocation, largeUnit, el, ev) {
  6255. var calendar = this.calendar;
  6256. var mutateResult = calendar.mutateEvent(event, resizeLocation, largeUnit);
  6257. var undoFunc = function() {
  6258. mutateResult.undo();
  6259. calendar.reportEventChange();
  6260. };
  6261. this.triggerEventResize(event, mutateResult.durationDelta, undoFunc, el, ev);
  6262. calendar.reportEventChange(); // will rerender events
  6263. },
  6264. // Triggers event-resize handlers that have subscribed via the API
  6265. triggerEventResize: function(event, durationDelta, undoFunc, el, ev) {
  6266. this.trigger('eventResize', el[0], event, durationDelta, undoFunc, ev, {}); // {} = jqui dummy
  6267. },
  6268. /* Selection
  6269. ------------------------------------------------------------------------------------------------------------------*/
  6270. // Selects a date span on the view. `start` and `end` are both Moments.
  6271. // `ev` is the native mouse event that begin the interaction.
  6272. select: function(span, ev) {
  6273. this.unselect(ev);
  6274. this.renderSelection(span);
  6275. this.reportSelection(span, ev);
  6276. },
  6277. // Renders a visual indication of the selection
  6278. renderSelection: function(span) {
  6279. // subclasses should implement
  6280. },
  6281. // Called when a new selection is made. Updates internal state and triggers handlers.
  6282. reportSelection: function(span, ev) {
  6283. this.isSelected = true;
  6284. this.triggerSelect(span, ev);
  6285. },
  6286. // Triggers handlers to 'select'
  6287. triggerSelect: function(span, ev) {
  6288. this.trigger(
  6289. 'select',
  6290. null,
  6291. this.calendar.applyTimezone(span.start), // convert to calendar's tz for external API
  6292. this.calendar.applyTimezone(span.end), // "
  6293. ev
  6294. );
  6295. },
  6296. // Undoes a selection. updates in the internal state and triggers handlers.
  6297. // `ev` is the native mouse event that began the interaction.
  6298. unselect: function(ev) {
  6299. if (this.isSelected) {
  6300. this.isSelected = false;
  6301. if (this.destroySelection) {
  6302. this.destroySelection(); // TODO: deprecate
  6303. }
  6304. this.unrenderSelection();
  6305. this.trigger('unselect', null, ev);
  6306. }
  6307. },
  6308. // Unrenders a visual indication of selection
  6309. unrenderSelection: function() {
  6310. // subclasses should implement
  6311. },
  6312. // Handler for unselecting when the user clicks something and the 'unselectAuto' setting is on
  6313. documentMousedown: function(ev) {
  6314. var ignore;
  6315. // is there a selection, and has the user made a proper left click?
  6316. if (this.isSelected && this.opt('unselectAuto') && isPrimaryMouseButton(ev)) {
  6317. // only unselect if the clicked element is not identical to or inside of an 'unselectCancel' element
  6318. ignore = this.opt('unselectCancel');
  6319. if (!ignore || !jQuery(ev.target).closest(ignore).length) {
  6320. this.unselect(ev);
  6321. }
  6322. }
  6323. },
  6324. /* Day Click
  6325. ------------------------------------------------------------------------------------------------------------------*/
  6326. // Triggers handlers to 'dayClick'
  6327. // Span has start/end of the clicked area. Only the start is useful.
  6328. triggerDayClick: function(span, dayEl, ev) {
  6329. this.trigger(
  6330. 'dayClick',
  6331. dayEl,
  6332. this.calendar.applyTimezone(span.start), // convert to calendar's timezone for external API
  6333. ev
  6334. );
  6335. },
  6336. /* Date Utils
  6337. ------------------------------------------------------------------------------------------------------------------*/
  6338. // Initializes internal variables related to calculating hidden days-of-week
  6339. initHiddenDays: function() {
  6340. var hiddenDays = this.opt('hiddenDays') || []; // array of day-of-week indices that are hidden
  6341. var isHiddenDayHash = []; // is the day-of-week hidden? (hash with day-of-week-index -> bool)
  6342. var dayCnt = 0;
  6343. var i;
  6344. if (this.opt('weekends') === false) {
  6345. hiddenDays.push(0, 6); // 0=sunday, 6=saturday
  6346. }
  6347. for (i = 0; i < 7; i++) {
  6348. if (
  6349. !(isHiddenDayHash[i] = jQuery.inArray(i, hiddenDays) !== -1)
  6350. ) {
  6351. dayCnt++;
  6352. }
  6353. }
  6354. if (!dayCnt) {
  6355. throw 'invalid hiddenDays'; // all days were hidden? bad.
  6356. }
  6357. this.isHiddenDayHash = isHiddenDayHash;
  6358. },
  6359. // Is the current day hidden?
  6360. // `day` is a day-of-week index (0-6), or a Moment
  6361. isHiddenDay: function(day) {
  6362. if (moment.isMoment(day)) {
  6363. day = day.day();
  6364. }
  6365. return this.isHiddenDayHash[day];
  6366. },
  6367. // Incrementing the current day until it is no longer a hidden day, returning a copy.
  6368. // If the initial value of `date` is not a hidden day, don't do anything.
  6369. // Pass `isExclusive` as `true` if you are dealing with an end date.
  6370. // `inc` defaults to `1` (increment one day forward each time)
  6371. skipHiddenDays: function(date, inc, isExclusive) {
  6372. var out = date.clone();
  6373. inc = inc || 1;
  6374. while (
  6375. this.isHiddenDayHash[(out.day() + (isExclusive ? inc : 0) + 7) % 7]
  6376. ) {
  6377. out.add(inc, 'days');
  6378. }
  6379. return out;
  6380. },
  6381. // Returns the date range of the full days the given range visually appears to occupy.
  6382. // Returns a new range object.
  6383. computeDayRange: function(range) {
  6384. var startDay = range.start.clone().stripTime(); // the beginning of the day the range starts
  6385. var end = range.end;
  6386. var endDay = null;
  6387. var endTimeMS;
  6388. if (end) {
  6389. endDay = end.clone().stripTime(); // the beginning of the day the range exclusively ends
  6390. endTimeMS = +end.time(); // # of milliseconds into `endDay`
  6391. // If the end time is actually inclusively part of the next day and is equal to or
  6392. // beyond the next day threshold, adjust the end to be the exclusive end of `endDay`.
  6393. // Otherwise, leaving it as inclusive will cause it to exclude `endDay`.
  6394. if (endTimeMS && endTimeMS >= this.nextDayThreshold) {
  6395. endDay.add(1, 'days');
  6396. }
  6397. }
  6398. // If no end was specified, or if it is within `startDay` but not past nextDayThreshold,
  6399. // assign the default duration of one day.
  6400. if (!end || endDay <= startDay) {
  6401. endDay = startDay.clone().add(1, 'days');
  6402. }
  6403. return { start: startDay, end: endDay };
  6404. },
  6405. // Does the given event visually appear to occupy more than one day?
  6406. isMultiDayEvent: function(event) {
  6407. var range = this.computeDayRange(event); // event is range-ish
  6408. return range.end.diff(range.start, 'days') > 1;
  6409. }
  6410. });
  6411. ;;
  6412. var Calendar = FC.Calendar = Class.extend({
  6413. dirDefaults: null, // option defaults related to LTR or RTL
  6414. langDefaults: null, // option defaults related to current locale
  6415. overrides: null, // option overrides given to the fullCalendar constructor
  6416. options: null, // all defaults combined with overrides
  6417. viewSpecCache: null, // cache of view definitions
  6418. view: null, // current View object
  6419. header: null,
  6420. loadingLevel: 0, // number of simultaneous loading tasks
  6421. // a lot of this class' OOP logic is scoped within this constructor function,
  6422. // but in the future, write individual methods on the prototype.
  6423. constructor: Calendar_constructor,
  6424. // Subclasses can override this for initialization logic after the constructor has been called
  6425. initialize: function() {
  6426. },
  6427. // Initializes `this.options` and other important options-related objects
  6428. initOptions: function(overrides) {
  6429. var lang, langDefaults;
  6430. var isRTL, dirDefaults;
  6431. // converts legacy options into non-legacy ones.
  6432. // in the future, when this is removed, don't use `overrides` reference. make a copy.
  6433. overrides = massageOverrides(overrides);
  6434. lang = overrides.lang;
  6435. langDefaults = langOptionHash[lang];
  6436. if (!langDefaults) {
  6437. lang = Calendar.defaults.lang;
  6438. langDefaults = langOptionHash[lang] || {};
  6439. }
  6440. isRTL = firstDefined(
  6441. overrides.isRTL,
  6442. langDefaults.isRTL,
  6443. Calendar.defaults.isRTL
  6444. );
  6445. dirDefaults = isRTL ? Calendar.rtlDefaults : {};
  6446. this.dirDefaults = dirDefaults;
  6447. this.langDefaults = langDefaults;
  6448. this.overrides = overrides;
  6449. this.options = mergeOptions([ // merge defaults and overrides. lowest to highest precedence
  6450. Calendar.defaults, // global defaults
  6451. dirDefaults,
  6452. langDefaults,
  6453. overrides
  6454. ]);
  6455. populateInstanceComputableOptions(this.options);
  6456. this.viewSpecCache = {}; // somewhat unrelated
  6457. },
  6458. // Gets information about how to create a view. Will use a cache.
  6459. getViewSpec: function(viewType) {
  6460. var cache = this.viewSpecCache;
  6461. return cache[viewType] || (cache[viewType] = this.buildViewSpec(viewType));
  6462. },
  6463. // Given a duration singular unit, like "week" or "day", finds a matching view spec.
  6464. // Preference is given to views that have corresponding buttons.
  6465. getUnitViewSpec: function(unit) {
  6466. var viewTypes;
  6467. var i;
  6468. var spec;
  6469. if (jQuery.inArray(unit, intervalUnits) != -1) {
  6470. // put views that have buttons first. there will be duplicates, but oh well
  6471. viewTypes = this.header.getViewsWithButtons();
  6472. jQuery.each(FC.views, function(viewType) { // all views
  6473. viewTypes.push(viewType);
  6474. });
  6475. for (i = 0; i < viewTypes.length; i++) {
  6476. spec = this.getViewSpec(viewTypes[i]);
  6477. if (spec) {
  6478. if (spec.singleUnit == unit) {
  6479. return spec;
  6480. }
  6481. }
  6482. }
  6483. }
  6484. },
  6485. // Builds an object with information on how to create a given view
  6486. buildViewSpec: function(requestedViewType) {
  6487. var viewOverrides = this.overrides.views || {};
  6488. var specChain = []; // for the view. lowest to highest priority
  6489. var defaultsChain = []; // for the view. lowest to highest priority
  6490. var overridesChain = []; // for the view. lowest to highest priority
  6491. var viewType = requestedViewType;
  6492. var spec; // for the view
  6493. var overrides; // for the view
  6494. var duration;
  6495. var unit;
  6496. // iterate from the specific view definition to a more general one until we hit an actual View class
  6497. while (viewType) {
  6498. spec = fcViews[viewType];
  6499. overrides = viewOverrides[viewType];
  6500. viewType = null; // clear. might repopulate for another iteration
  6501. if (typeof spec === 'function') { // TODO: deprecate
  6502. spec = { 'class': spec };
  6503. }
  6504. if (spec) {
  6505. specChain.unshift(spec);
  6506. defaultsChain.unshift(spec.defaults || {});
  6507. duration = duration || spec.duration;
  6508. viewType = viewType || spec.type;
  6509. }
  6510. if (overrides) {
  6511. overridesChain.unshift(overrides); // view-specific option hashes have options at zero-level
  6512. duration = duration || overrides.duration;
  6513. viewType = viewType || overrides.type;
  6514. }
  6515. }
  6516. spec = mergeProps(specChain);
  6517. spec.type = requestedViewType;
  6518. if (!spec['class']) {
  6519. return false;
  6520. }
  6521. if (duration) {
  6522. duration = moment.duration(duration);
  6523. if (duration.valueOf()) { // valid?
  6524. spec.duration = duration;
  6525. unit = computeIntervalUnit(duration);
  6526. // view is a single-unit duration, like "week" or "day"
  6527. // incorporate options for this. lowest priority
  6528. if (duration.as(unit) === 1) {
  6529. spec.singleUnit = unit;
  6530. overridesChain.unshift(viewOverrides[unit] || {});
  6531. }
  6532. }
  6533. }
  6534. spec.defaults = mergeOptions(defaultsChain);
  6535. spec.overrides = mergeOptions(overridesChain);
  6536. this.buildViewSpecOptions(spec);
  6537. this.buildViewSpecButtonText(spec, requestedViewType);
  6538. return spec;
  6539. },
  6540. // Builds and assigns a view spec's options object from its already-assigned defaults and overrides
  6541. buildViewSpecOptions: function(spec) {
  6542. spec.options = mergeOptions([ // lowest to highest priority
  6543. Calendar.defaults, // global defaults
  6544. spec.defaults, // view's defaults (from ViewSubclass.defaults)
  6545. this.dirDefaults,
  6546. this.langDefaults, // locale and dir take precedence over view's defaults!
  6547. this.overrides, // calendar's overrides (options given to constructor)
  6548. spec.overrides // view's overrides (view-specific options)
  6549. ]);
  6550. populateInstanceComputableOptions(spec.options);
  6551. },
  6552. // Computes and assigns a view spec's buttonText-related options
  6553. buildViewSpecButtonText: function(spec, requestedViewType) {
  6554. // given an options object with a possible `buttonText` hash, lookup the buttonText for the
  6555. // requested view, falling back to a generic unit entry like "week" or "day"
  6556. function queryButtonText(options) {
  6557. var buttonText = options.buttonText || {};
  6558. return buttonText[requestedViewType] ||
  6559. (spec.singleUnit ? buttonText[spec.singleUnit] : null);
  6560. }
  6561. // highest to lowest priority
  6562. spec.buttonTextOverride =
  6563. queryButtonText(this.overrides) || // constructor-specified buttonText lookup hash takes precedence
  6564. spec.overrides.buttonText; // `buttonText` for view-specific options is a string
  6565. // highest to lowest priority. mirrors buildViewSpecOptions
  6566. spec.buttonTextDefault =
  6567. queryButtonText(this.langDefaults) ||
  6568. queryButtonText(this.dirDefaults) ||
  6569. spec.defaults.buttonText || // a single string. from ViewSubclass.defaults
  6570. queryButtonText(Calendar.defaults) ||
  6571. (spec.duration ? this.humanizeDuration(spec.duration) : null) || // like "3 days"
  6572. requestedViewType; // fall back to given view name
  6573. },
  6574. // Given a view name for a custom view or a standard view, creates a ready-to-go View object
  6575. instantiateView: function(viewType) {
  6576. var spec = this.getViewSpec(viewType);
  6577. return new spec['class'](this, viewType, spec.options, spec.duration);
  6578. },
  6579. // Returns a boolean about whether the view is okay to instantiate at some point
  6580. isValidViewType: function(viewType) {
  6581. return Boolean(this.getViewSpec(viewType));
  6582. },
  6583. // Should be called when any type of async data fetching begins
  6584. pushLoading: function() {
  6585. if (!(this.loadingLevel++)) {
  6586. this.trigger('loading', null, true, this.view);
  6587. }
  6588. },
  6589. // Should be called when any type of async data fetching completes
  6590. popLoading: function() {
  6591. if (!(--this.loadingLevel)) {
  6592. this.trigger('loading', null, false, this.view);
  6593. }
  6594. },
  6595. // Given arguments to the select method in the API, returns a span (unzoned start/end and other info)
  6596. buildSelectSpan: function(zonedStartInput, zonedEndInput) {
  6597. var start = this.moment(zonedStartInput).stripZone();
  6598. var end;
  6599. if (zonedEndInput) {
  6600. end = this.moment(zonedEndInput).stripZone();
  6601. }
  6602. else if (start.hasTime()) {
  6603. end = start.clone().add(this.defaultTimedEventDuration);
  6604. }
  6605. else {
  6606. end = start.clone().add(this.defaultAllDayEventDuration);
  6607. }
  6608. return { start: start, end: end };
  6609. }
  6610. });
  6611. Calendar.mixin(Emitter);
  6612. function Calendar_constructor(element, overrides) {
  6613. var t = this;
  6614. t.initOptions(overrides || {});
  6615. var options = this.options;
  6616. // Exports
  6617. // -----------------------------------------------------------------------------------
  6618. t.render = render;
  6619. t.destroy = destroy;
  6620. t.refetchEvents = refetchEvents;
  6621. t.reportEvents = reportEvents;
  6622. t.reportEventChange = reportEventChange;
  6623. t.rerenderEvents = renderEvents; // `renderEvents` serves as a rerender. an API method
  6624. t.changeView = renderView; // `renderView` will switch to another view
  6625. t.select = select;
  6626. t.unselect = unselect;
  6627. t.prev = prev;
  6628. t.next = next;
  6629. t.prevYear = prevYear;
  6630. t.nextYear = nextYear;
  6631. t.today = today;
  6632. t.gotoDate = gotoDate;
  6633. t.incrementDate = incrementDate;
  6634. t.zoomTo = zoomTo;
  6635. t.getDate = getDate;
  6636. t.getCalendar = getCalendar;
  6637. t.getView = getView;
  6638. t.option = option;
  6639. t.trigger = trigger;
  6640. // Language-data Internals
  6641. // -----------------------------------------------------------------------------------
  6642. // Apply overrides to the current language's data
  6643. var localeData = createObject( // make a cheap copy
  6644. getMomentLocaleData(options.lang) // will fall back to en
  6645. );
  6646. if (options.monthNames) {
  6647. localeData._months = options.monthNames;
  6648. }
  6649. if (options.monthNamesShort) {
  6650. localeData._monthsShort = options.monthNamesShort;
  6651. }
  6652. if (options.dayNames) {
  6653. localeData._weekdays = options.dayNames;
  6654. }
  6655. if (options.dayNamesShort) {
  6656. localeData._weekdaysShort = options.dayNamesShort;
  6657. }
  6658. if (options.firstDay != null) {
  6659. var _week = createObject(localeData._week); // _week: { dow: # }
  6660. _week.dow = options.firstDay;
  6661. localeData._week = _week;
  6662. }
  6663. // assign a normalized value, to be used by our .week() moment extension
  6664. localeData._fullCalendar_weekCalc = (function(weekCalc) {
  6665. if (typeof weekCalc === 'function') {
  6666. return weekCalc;
  6667. }
  6668. else if (weekCalc === 'local') {
  6669. return weekCalc;
  6670. }
  6671. else if (weekCalc === 'iso' || weekCalc === 'ISO') {
  6672. return 'ISO';
  6673. }
  6674. })(options.weekNumberCalculation);
  6675. // Calendar-specific Date Utilities
  6676. // -----------------------------------------------------------------------------------
  6677. t.defaultAllDayEventDuration = moment.duration(options.defaultAllDayEventDuration);
  6678. t.defaultTimedEventDuration = moment.duration(options.defaultTimedEventDuration);
  6679. // Builds a moment using the settings of the current calendar: timezone and language.
  6680. // Accepts anything the vanilla moment() constructor accepts.
  6681. t.moment = function() {
  6682. var mom;
  6683. if (options.timezone === 'local') {
  6684. mom = FC.moment.apply(null, arguments);
  6685. // Force the moment to be local, because FC.moment doesn't guarantee it.
  6686. if (mom.hasTime()) { // don't give ambiguously-timed moments a local zone
  6687. mom.local();
  6688. }
  6689. }
  6690. else if (options.timezone === 'UTC') {
  6691. mom = FC.moment.utc.apply(null, arguments); // process as UTC
  6692. }
  6693. else {
  6694. mom = FC.moment.parseZone.apply(null, arguments); // let the input decide the zone
  6695. }
  6696. if ('_locale' in mom) { // moment 2.8 and above
  6697. mom._locale = localeData;
  6698. }
  6699. else { // pre-moment-2.8
  6700. mom._lang = localeData;
  6701. }
  6702. return mom;
  6703. };
  6704. // Returns a boolean about whether or not the calendar knows how to calculate
  6705. // the timezone offset of arbitrary dates in the current timezone.
  6706. t.getIsAmbigTimezone = function() {
  6707. return options.timezone !== 'local' && options.timezone !== 'UTC';
  6708. };
  6709. // Returns a copy of the given date in the current timezone. Has no effect on dates without times.
  6710. t.applyTimezone = function(date) {
  6711. if (!date.hasTime()) {
  6712. return date.clone();
  6713. }
  6714. var zonedDate = t.moment(date.toArray());
  6715. var timeAdjust = date.time() - zonedDate.time();
  6716. var adjustedZonedDate;
  6717. // Safari sometimes has problems with this coersion when near DST. Adjust if necessary. (bug #2396)
  6718. if (timeAdjust) { // is the time result different than expected?
  6719. adjustedZonedDate = zonedDate.clone().add(timeAdjust); // add milliseconds
  6720. if (date.time() - adjustedZonedDate.time() === 0) { // does it match perfectly now?
  6721. zonedDate = adjustedZonedDate;
  6722. }
  6723. }
  6724. return zonedDate;
  6725. };
  6726. // Returns a moment for the current date, as defined by the client's computer or from the `now` option.
  6727. // Will return an moment with an ambiguous timezone.
  6728. t.getNow = function() {
  6729. var now = options.now;
  6730. if (typeof now === 'function') {
  6731. now = now();
  6732. }
  6733. return t.moment(now).stripZone();
  6734. };
  6735. // Get an event's normalized end date. If not present, calculate it from the defaults.
  6736. t.getEventEnd = function(event) {
  6737. if (event.end) {
  6738. return event.end.clone();
  6739. }
  6740. else {
  6741. return t.getDefaultEventEnd(event.allDay, event.start);
  6742. }
  6743. };
  6744. // Given an event's allDay status and start date, return what its fallback end date should be.
  6745. // TODO: rename to computeDefaultEventEnd
  6746. t.getDefaultEventEnd = function(allDay, zonedStart) {
  6747. var end = zonedStart.clone();
  6748. if (allDay) {
  6749. end.stripTime().add(t.defaultAllDayEventDuration);
  6750. }
  6751. else {
  6752. end.add(t.defaultTimedEventDuration);
  6753. }
  6754. if (t.getIsAmbigTimezone()) {
  6755. end.stripZone(); // we don't know what the tzo should be
  6756. }
  6757. return end;
  6758. };
  6759. // Produces a human-readable string for the given duration.
  6760. // Side-effect: changes the locale of the given duration.
  6761. t.humanizeDuration = function(duration) {
  6762. return (duration.locale || duration.lang).call(duration, options.lang) // works moment-pre-2.8
  6763. .humanize();
  6764. };
  6765. // Imports
  6766. // -----------------------------------------------------------------------------------
  6767. EventManager.call(t, options);
  6768. var isFetchNeeded = t.isFetchNeeded;
  6769. var fetchEvents = t.fetchEvents;
  6770. // Locals
  6771. // -----------------------------------------------------------------------------------
  6772. var _element = element[0];
  6773. var header;
  6774. var headerElement;
  6775. var content;
  6776. var tm; // for making theme classes
  6777. var currentView; // NOTE: keep this in sync with this.view
  6778. var viewsByType = {}; // holds all instantiated view instances, current or not
  6779. var suggestedViewHeight;
  6780. var windowResizeProxy; // wraps the windowResize function
  6781. var ignoreWindowResize = 0;
  6782. var events = [];
  6783. var date; // unzoned
  6784. // Main Rendering
  6785. // -----------------------------------------------------------------------------------
  6786. // compute the initial ambig-timezone date
  6787. if (options.defaultDate != null) {
  6788. date = t.moment(options.defaultDate).stripZone();
  6789. }
  6790. else {
  6791. date = t.getNow(); // getNow already returns unzoned
  6792. }
  6793. function render() {
  6794. if (!content) {
  6795. initialRender();
  6796. }
  6797. else if (elementVisible()) {
  6798. // mainly for the public API
  6799. calcSize();
  6800. renderView();
  6801. }
  6802. }
  6803. function initialRender() {
  6804. tm = options.theme ? 'ui' : 'fc';
  6805. element.addClass('fc');
  6806. if (options.isRTL) {
  6807. element.addClass('fc-rtl');
  6808. }
  6809. else {
  6810. element.addClass('fc-ltr');
  6811. }
  6812. if (options.theme) {
  6813. element.addClass('ui-widget');
  6814. }
  6815. else {
  6816. element.addClass('fc-unthemed');
  6817. }
  6818. content = jQuery("<div class='fc-view-container'/>").prependTo(element);
  6819. header = t.header = new Header(t, options);
  6820. headerElement = header.render();
  6821. if (headerElement) {
  6822. element.prepend(headerElement);
  6823. }
  6824. renderView(options.defaultView);
  6825. if (options.handleWindowResize) {
  6826. windowResizeProxy = debounce(windowResize, options.windowResizeDelay); // prevents rapid calls
  6827. jQuery(window).resize(windowResizeProxy);
  6828. }
  6829. }
  6830. function destroy() {
  6831. if (currentView) {
  6832. currentView.removeElement();
  6833. // NOTE: don't null-out currentView/t.view in case API methods are called after destroy.
  6834. // It is still the "current" view, just not rendered.
  6835. }
  6836. header.removeElement();
  6837. content.remove();
  6838. element.removeClass('fc fc-ltr fc-rtl fc-unthemed ui-widget');
  6839. if (windowResizeProxy) {
  6840. jQuery(window).unbind('resize', windowResizeProxy);
  6841. }
  6842. }
  6843. function elementVisible() {
  6844. return element.is(':visible');
  6845. }
  6846. // View Rendering
  6847. // -----------------------------------------------------------------------------------
  6848. // Renders a view because of a date change, view-type change, or for the first time.
  6849. // If not given a viewType, keep the current view but render different dates.
  6850. function renderView(viewType) {
  6851. ignoreWindowResize++;
  6852. // if viewType is changing, remove the old view's rendering
  6853. if (currentView && viewType && currentView.type !== viewType) {
  6854. header.deactivateButton(currentView.type);
  6855. freezeContentHeight(); // prevent a scroll jump when view element is removed
  6856. currentView.removeElement();
  6857. currentView = t.view = null;
  6858. }
  6859. // if viewType changed, or the view was never created, create a fresh view
  6860. if (!currentView && viewType) {
  6861. currentView = t.view =
  6862. viewsByType[viewType] ||
  6863. (viewsByType[viewType] = t.instantiateView(viewType));
  6864. currentView.setElement(
  6865. jQuery("<div class='fc-view fc-" + viewType + "-view' />").appendTo(content)
  6866. );
  6867. header.activateButton(viewType);
  6868. }
  6869. if (currentView) {
  6870. // in case the view should render a period of time that is completely hidden
  6871. date = currentView.massageCurrentDate(date);
  6872. // render or rerender the view
  6873. if (
  6874. !currentView.displaying ||
  6875. !date.isWithin(currentView.intervalStart, currentView.intervalEnd) // implicit date window change
  6876. ) {
  6877. if (elementVisible()) {
  6878. currentView.display(date); // will call freezeContentHeight
  6879. unfreezeContentHeight(); // immediately unfreeze regardless of whether display is async
  6880. // need to do this after View::render, so dates are calculated
  6881. updateHeaderTitle();
  6882. updateTodayButton();
  6883. getAndRenderEvents();
  6884. }
  6885. }
  6886. }
  6887. unfreezeContentHeight(); // undo any lone freezeContentHeight calls
  6888. ignoreWindowResize--;
  6889. }
  6890. // Resizing
  6891. // -----------------------------------------------------------------------------------
  6892. t.getSuggestedViewHeight = function() {
  6893. if (suggestedViewHeight === undefined) {
  6894. calcSize();
  6895. }
  6896. return suggestedViewHeight;
  6897. };
  6898. t.isHeightAuto = function() {
  6899. return options.contentHeight === 'auto' || options.height === 'auto';
  6900. };
  6901. function updateSize(shouldRecalc) {
  6902. if (elementVisible()) {
  6903. if (shouldRecalc) {
  6904. _calcSize();
  6905. }
  6906. ignoreWindowResize++;
  6907. currentView.updateSize(true); // isResize=true. will poll getSuggestedViewHeight() and isHeightAuto()
  6908. ignoreWindowResize--;
  6909. return true; // signal success
  6910. }
  6911. }
  6912. function calcSize() {
  6913. if (elementVisible()) {
  6914. _calcSize();
  6915. }
  6916. }
  6917. function _calcSize() { // assumes elementVisible
  6918. if (typeof options.contentHeight === 'number') { // exists and not 'auto'
  6919. suggestedViewHeight = options.contentHeight;
  6920. }
  6921. else if (typeof options.height === 'number') { // exists and not 'auto'
  6922. suggestedViewHeight = options.height - (headerElement ? headerElement.outerHeight(true) : 0);
  6923. }
  6924. else {
  6925. suggestedViewHeight = Math.round(content.width() / Math.max(options.aspectRatio, .5));
  6926. }
  6927. }
  6928. function windowResize(ev) {
  6929. if (
  6930. !ignoreWindowResize &&
  6931. ev.target === window && // so we don't process jqui "resize" events that have bubbled up
  6932. currentView.start // view has already been rendered
  6933. ) {
  6934. if (updateSize(true)) {
  6935. currentView.trigger('windowResize', _element);
  6936. }
  6937. }
  6938. }
  6939. /* Event Fetching/Rendering
  6940. -----------------------------------------------------------------------------*/
  6941. // TODO: going forward, most of this stuff should be directly handled by the view
  6942. function refetchEvents() { // can be called as an API method
  6943. destroyEvents(); // so that events are cleared before user starts waiting for AJAX
  6944. fetchAndRenderEvents();
  6945. }
  6946. function renderEvents() { // destroys old events if previously rendered
  6947. if (elementVisible()) {
  6948. freezeContentHeight();
  6949. currentView.displayEvents(events);
  6950. unfreezeContentHeight();
  6951. }
  6952. }
  6953. function destroyEvents() {
  6954. freezeContentHeight();
  6955. currentView.clearEvents();
  6956. unfreezeContentHeight();
  6957. }
  6958. function getAndRenderEvents() {
  6959. if (!options.lazyFetching || isFetchNeeded(currentView.start, currentView.end)) {
  6960. fetchAndRenderEvents();
  6961. }
  6962. else {
  6963. renderEvents();
  6964. }
  6965. }
  6966. function fetchAndRenderEvents() {
  6967. fetchEvents(currentView.start, currentView.end);
  6968. // ... will call reportEvents
  6969. // ... which will call renderEvents
  6970. }
  6971. // called when event data arrives
  6972. function reportEvents(_events) {
  6973. events = _events;
  6974. renderEvents();
  6975. }
  6976. // called when a single event's data has been changed
  6977. function reportEventChange() {
  6978. renderEvents();
  6979. }
  6980. /* Header Updating
  6981. -----------------------------------------------------------------------------*/
  6982. function updateHeaderTitle() {
  6983. header.updateTitle(currentView.title);
  6984. }
  6985. function updateTodayButton() {
  6986. var now = t.getNow();
  6987. if (now.isWithin(currentView.intervalStart, currentView.intervalEnd)) {
  6988. header.disableButton('today');
  6989. }
  6990. else {
  6991. header.enableButton('today');
  6992. }
  6993. }
  6994. /* Selection
  6995. -----------------------------------------------------------------------------*/
  6996. // this public method receives start/end dates in any format, with any timezone
  6997. function select(zonedStartInput, zonedEndInput) {
  6998. currentView.select(
  6999. t.buildSelectSpan.apply(t, arguments)
  7000. );
  7001. }
  7002. function unselect() { // safe to be called before renderView
  7003. if (currentView) {
  7004. currentView.unselect();
  7005. }
  7006. }
  7007. /* Date
  7008. -----------------------------------------------------------------------------*/
  7009. function prev() {
  7010. date = currentView.computePrevDate(date);
  7011. renderView();
  7012. }
  7013. function next() {
  7014. date = currentView.computeNextDate(date);
  7015. renderView();
  7016. }
  7017. function prevYear() {
  7018. date.add(-1, 'years');
  7019. renderView();
  7020. }
  7021. function nextYear() {
  7022. date.add(1, 'years');
  7023. renderView();
  7024. }
  7025. function today() {
  7026. date = t.getNow();
  7027. renderView();
  7028. }
  7029. function gotoDate(zonedDateInput) {
  7030. date = t.moment(zonedDateInput).stripZone();
  7031. renderView();
  7032. }
  7033. function incrementDate(delta) {
  7034. date.add(moment.duration(delta));
  7035. renderView();
  7036. }
  7037. // Forces navigation to a view for the given date.
  7038. // `viewType` can be a specific view name or a generic one like "week" or "day".
  7039. function zoomTo(newDate, viewType) {
  7040. var spec;
  7041. viewType = viewType || 'day'; // day is default zoom
  7042. spec = t.getViewSpec(viewType) || t.getUnitViewSpec(viewType);
  7043. date = newDate.clone();
  7044. renderView(spec ? spec.type : null);
  7045. }
  7046. // for external API
  7047. function getDate() {
  7048. return t.applyTimezone(date); // infuse the calendar's timezone
  7049. }
  7050. /* Height "Freezing"
  7051. -----------------------------------------------------------------------------*/
  7052. // TODO: move this into the view
  7053. t.freezeContentHeight = freezeContentHeight;
  7054. t.unfreezeContentHeight = unfreezeContentHeight;
  7055. function freezeContentHeight() {
  7056. content.css({
  7057. width: '100%',
  7058. height: content.height(),
  7059. overflow: 'hidden'
  7060. });
  7061. }
  7062. function unfreezeContentHeight() {
  7063. content.css({
  7064. width: '',
  7065. height: '',
  7066. overflow: ''
  7067. });
  7068. }
  7069. /* Misc
  7070. -----------------------------------------------------------------------------*/
  7071. function getCalendar() {
  7072. return t;
  7073. }
  7074. function getView() {
  7075. return currentView;
  7076. }
  7077. function option(name, value) {
  7078. if (value === undefined) {
  7079. return options[name];
  7080. }
  7081. if (name == 'height' || name == 'contentHeight' || name == 'aspectRatio') {
  7082. options[name] = value;
  7083. updateSize(true); // true = allow recalculation of height
  7084. }
  7085. }
  7086. function trigger(name, thisObj) { // overrides the Emitter's trigger method :(
  7087. var args = Array.prototype.slice.call(arguments, 2);
  7088. thisObj = thisObj || _element;
  7089. this.triggerWith(name, thisObj, args); // Emitter's method
  7090. if (options[name]) {
  7091. return options[name].apply(thisObj, args);
  7092. }
  7093. }
  7094. t.initialize();
  7095. }
  7096. ;;
  7097. Calendar.defaults = {
  7098. titleRangeSeparator: ' \u2014 ', // emphasized dash
  7099. monthYearFormat: 'MMMM YYYY', // required for en. other languages rely on datepicker computable option
  7100. defaultTimedEventDuration: '02:00:00',
  7101. defaultAllDayEventDuration: { days: 1 },
  7102. forceEventDuration: false,
  7103. nextDayThreshold: '09:00:00', // 9am
  7104. // display
  7105. defaultView: 'month',
  7106. aspectRatio: 1.35,
  7107. header: {
  7108. left: 'title',
  7109. center: '',
  7110. right: 'today prev,next'
  7111. },
  7112. weekends: true,
  7113. weekNumbers: false,
  7114. weekNumberTitle: 'W',
  7115. weekNumberCalculation: 'local',
  7116. //editable: false,
  7117. //nowIndicator: false,
  7118. scrollTime: '06:00:00',
  7119. // event ajax
  7120. lazyFetching: true,
  7121. startParam: 'start',
  7122. endParam: 'end',
  7123. timezoneParam: 'timezone',
  7124. timezone: false,
  7125. //allDayDefault: undefined,
  7126. // locale
  7127. isRTL: false,
  7128. buttonText: {
  7129. prev: "prev",
  7130. next: "next",
  7131. prevYear: "prev year",
  7132. nextYear: "next year",
  7133. year: 'year', // TODO: locale files need to specify this
  7134. today: 'today',
  7135. month: 'month',
  7136. week: 'week',
  7137. day: 'day'
  7138. },
  7139. buttonIcons: {
  7140. prev: 'left-single-arrow',
  7141. next: 'right-single-arrow',
  7142. prevYear: 'left-double-arrow',
  7143. nextYear: 'right-double-arrow'
  7144. },
  7145. // jquery-ui theming
  7146. theme: false,
  7147. themeButtonIcons: {
  7148. prev: 'circle-triangle-w',
  7149. next: 'circle-triangle-e',
  7150. prevYear: 'seek-prev',
  7151. nextYear: 'seek-next'
  7152. },
  7153. //eventResizableFromStart: false,
  7154. dragOpacity: .75,
  7155. dragRevertDuration: 500,
  7156. dragScroll: true,
  7157. //selectable: false,
  7158. unselectAuto: true,
  7159. dropAccept: '*',
  7160. eventOrder: 'title',
  7161. eventLimit: false,
  7162. eventLimitText: 'more',
  7163. eventLimitClick: 'popover',
  7164. dayPopoverFormat: 'LL',
  7165. handleWindowResize: true,
  7166. windowResizeDelay: 200 // milliseconds before an updateSize happens
  7167. };
  7168. Calendar.englishDefaults = { // used by lang.js
  7169. dayPopoverFormat: 'dddd, MMMM D'
  7170. };
  7171. Calendar.rtlDefaults = { // right-to-left defaults
  7172. header: { // TODO: smarter solution (first/center/last ?)
  7173. left: 'next,prev today',
  7174. center: '',
  7175. right: 'title'
  7176. },
  7177. buttonIcons: {
  7178. prev: 'right-single-arrow',
  7179. next: 'left-single-arrow',
  7180. prevYear: 'right-double-arrow',
  7181. nextYear: 'left-double-arrow'
  7182. },
  7183. themeButtonIcons: {
  7184. prev: 'circle-triangle-e',
  7185. next: 'circle-triangle-w',
  7186. nextYear: 'seek-prev',
  7187. prevYear: 'seek-next'
  7188. }
  7189. };
  7190. ;;
  7191. var langOptionHash = FC.langs = {}; // initialize and expose
  7192. // TODO: document the structure and ordering of a FullCalendar lang file
  7193. // TODO: rename everything "lang" to "locale", like what the moment project did
  7194. // Initialize jQuery UI datepicker translations while using some of the translations
  7195. // Will set this as the default language for datepicker.
  7196. FC.datepickerLang = function(langCode, dpLangCode, dpOptions) {
  7197. // get the FullCalendar internal option hash for this language. create if necessary
  7198. var fcOptions = langOptionHash[langCode] || (langOptionHash[langCode] = {});
  7199. // transfer some simple options from datepicker to fc
  7200. fcOptions.isRTL = dpOptions.isRTL;
  7201. fcOptions.weekNumberTitle = dpOptions.weekHeader;
  7202. // compute some more complex options from datepicker
  7203. jQuery.each(dpComputableOptions, function(name, func) {
  7204. fcOptions[name] = func(dpOptions);
  7205. });
  7206. // is jQuery UI Datepicker is on the page?
  7207. if (jQuery.datepicker) {
  7208. // Register the language data.
  7209. // FullCalendar and MomentJS use language codes like "pt-br" but Datepicker
  7210. // does it like "pt-BR" or if it doesn't have the language, maybe just "pt".
  7211. // Make an alias so the language can be referenced either way.
  7212. jQuery.datepicker.regional[dpLangCode] =
  7213. jQuery.datepicker.regional[langCode] = // alias
  7214. dpOptions;
  7215. // Alias 'en' to the default language data. Do this every time.
  7216. jQuery.datepicker.regional.en = jQuery.datepicker.regional[''];
  7217. // Set as Datepicker's global defaults.
  7218. jQuery.datepicker.setDefaults(dpOptions);
  7219. }
  7220. };
  7221. // Sets FullCalendar-specific translations. Will set the language as the global default.
  7222. FC.lang = function(langCode, newFcOptions) {
  7223. var fcOptions;
  7224. var momOptions;
  7225. // get the FullCalendar internal option hash for this language. create if necessary
  7226. fcOptions = langOptionHash[langCode] || (langOptionHash[langCode] = {});
  7227. // provided new options for this language? merge them in
  7228. if (newFcOptions) {
  7229. fcOptions = langOptionHash[langCode] = mergeOptions([ fcOptions, newFcOptions ]);
  7230. }
  7231. // compute language options that weren't defined.
  7232. // always do this. newFcOptions can be undefined when initializing from i18n file,
  7233. // so no way to tell if this is an initialization or a default-setting.
  7234. momOptions = getMomentLocaleData(langCode); // will fall back to en
  7235. jQuery.each(momComputableOptions, function(name, func) {
  7236. if (fcOptions[name] == null) {
  7237. fcOptions[name] = func(momOptions, fcOptions);
  7238. }
  7239. });
  7240. // set it as the default language for FullCalendar
  7241. Calendar.defaults.lang = langCode;
  7242. };
  7243. // NOTE: can't guarantee any of these computations will run because not every language has datepicker
  7244. // configs, so make sure there are English fallbacks for these in the defaults file.
  7245. var dpComputableOptions = {
  7246. buttonText: function(dpOptions) {
  7247. return {
  7248. // the translations sometimes wrongly contain HTML entities
  7249. prev: stripHtmlEntities(dpOptions.prevText),
  7250. next: stripHtmlEntities(dpOptions.nextText),
  7251. today: stripHtmlEntities(dpOptions.currentText)
  7252. };
  7253. },
  7254. // Produces format strings like "MMMM YYYY" -> "September 2014"
  7255. monthYearFormat: function(dpOptions) {
  7256. return dpOptions.showMonthAfterYear ?
  7257. 'YYYY[' + dpOptions.yearSuffix + '] MMMM' :
  7258. 'MMMM YYYY[' + dpOptions.yearSuffix + ']';
  7259. }
  7260. };
  7261. var momComputableOptions = {
  7262. // Produces format strings like "ddd M/D" -> "Fri 9/15"
  7263. dayOfMonthFormat: function(momOptions, fcOptions) {
  7264. var format = momOptions.longDateFormat('l'); // for the format like "M/D/YYYY"
  7265. // strip the year off the edge, as well as other misc non-whitespace chars
  7266. format = format.replace(/^Y+[^\w\s]*|[^\w\s]*Y+$/g, '');
  7267. if (fcOptions.isRTL) {
  7268. format += ' ddd'; // for RTL, add day-of-week to end
  7269. }
  7270. else {
  7271. format = 'ddd ' + format; // for LTR, add day-of-week to beginning
  7272. }
  7273. return format;
  7274. },
  7275. // Produces format strings like "h:mma" -> "6:00pm"
  7276. mediumTimeFormat: function(momOptions) { // can't be called `timeFormat` because collides with option
  7277. return momOptions.longDateFormat('LT')
  7278. .replace(/\s*a$/i, 'a'); // convert AM/PM/am/pm to lowercase. remove any spaces beforehand
  7279. },
  7280. // Produces format strings like "h(:mm)a" -> "6pm" / "6:30pm"
  7281. smallTimeFormat: function(momOptions) {
  7282. return momOptions.longDateFormat('LT')
  7283. .replace(':mm', '(:mm)')
  7284. .replace(/(\Wmm)$/, '($1)') // like above, but for foreign langs
  7285. .replace(/\s*a$/i, 'a'); // convert AM/PM/am/pm to lowercase. remove any spaces beforehand
  7286. },
  7287. // Produces format strings like "h(:mm)t" -> "6p" / "6:30p"
  7288. extraSmallTimeFormat: function(momOptions) {
  7289. return momOptions.longDateFormat('LT')
  7290. .replace(':mm', '(:mm)')
  7291. .replace(/(\Wmm)$/, '($1)') // like above, but for foreign langs
  7292. .replace(/\s*a$/i, 't'); // convert to AM/PM/am/pm to lowercase one-letter. remove any spaces beforehand
  7293. },
  7294. // Produces format strings like "ha" / "H" -> "6pm" / "18"
  7295. hourFormat: function(momOptions) {
  7296. return momOptions.longDateFormat('LT')
  7297. .replace(':mm', '')
  7298. .replace(/(\Wmm)$/, '') // like above, but for foreign langs
  7299. .replace(/\s*a$/i, 'a'); // convert AM/PM/am/pm to lowercase. remove any spaces beforehand
  7300. },
  7301. // Produces format strings like "h:mm" -> "6:30" (with no AM/PM)
  7302. noMeridiemTimeFormat: function(momOptions) {
  7303. return momOptions.longDateFormat('LT')
  7304. .replace(/\s*a$/i, ''); // remove trailing AM/PM
  7305. }
  7306. };
  7307. // options that should be computed off live calendar options (considers override options)
  7308. // TODO: best place for this? related to lang?
  7309. // TODO: flipping text based on isRTL is a bad idea because the CSS `direction` might want to handle it
  7310. var instanceComputableOptions = {
  7311. // Produces format strings for results like "Mo 16"
  7312. smallDayDateFormat: function(options) {
  7313. return options.isRTL ?
  7314. 'D dd' :
  7315. 'dd D';
  7316. },
  7317. // Produces format strings for results like "Wk 5"
  7318. weekFormat: function(options) {
  7319. return options.isRTL ?
  7320. 'w[ ' + options.weekNumberTitle + ']' :
  7321. '[' + options.weekNumberTitle + ' ]w';
  7322. },
  7323. // Produces format strings for results like "Wk5"
  7324. smallWeekFormat: function(options) {
  7325. return options.isRTL ?
  7326. 'w[' + options.weekNumberTitle + ']' :
  7327. '[' + options.weekNumberTitle + ']w';
  7328. }
  7329. };
  7330. function populateInstanceComputableOptions(options) {
  7331. jQuery.each(instanceComputableOptions, function(name, func) {
  7332. if (options[name] == null) {
  7333. options[name] = func(options);
  7334. }
  7335. });
  7336. }
  7337. // Returns moment's internal locale data. If doesn't exist, returns English.
  7338. // Works with moment-pre-2.8
  7339. function getMomentLocaleData(langCode) {
  7340. var func = moment.localeData || moment.langData;
  7341. return func.call(moment, langCode) ||
  7342. func.call(moment, 'en'); // the newer localData could return null, so fall back to en
  7343. }
  7344. // Initialize English by forcing computation of moment-derived options.
  7345. // Also, sets it as the default.
  7346. FC.lang('en', Calendar.englishDefaults);
  7347. ;;
  7348. /* Top toolbar area with buttons and title
  7349. ----------------------------------------------------------------------------------------------------------------------*/
  7350. // TODO: rename all header-related things to "toolbar"
  7351. function Header(calendar, options) {
  7352. var t = this;
  7353. // exports
  7354. t.render = render;
  7355. t.removeElement = removeElement;
  7356. t.updateTitle = updateTitle;
  7357. t.activateButton = activateButton;
  7358. t.deactivateButton = deactivateButton;
  7359. t.disableButton = disableButton;
  7360. t.enableButton = enableButton;
  7361. t.getViewsWithButtons = getViewsWithButtons;
  7362. // locals
  7363. var el = jQuery();
  7364. var viewsWithButtons = [];
  7365. var tm;
  7366. function render() {
  7367. var sections = options.header;
  7368. tm = options.theme ? 'ui' : 'fc';
  7369. if (sections) {
  7370. el = jQuery("<div class='fc-toolbar'/>")
  7371. .append(renderSection('left'))
  7372. .append(renderSection('right'))
  7373. .append(renderSection('center'))
  7374. .append('<div class="fc-clear"/>');
  7375. return el;
  7376. }
  7377. }
  7378. function removeElement() {
  7379. el.remove();
  7380. el = jQuery();
  7381. }
  7382. function renderSection(position) {
  7383. var sectionEl = jQuery('<div class="fc-' + position + '"/>');
  7384. var buttonStr = options.header[position];
  7385. if (buttonStr) {
  7386. jQuery.each(buttonStr.split(' '), function(i) {
  7387. var groupChildren = jQuery();
  7388. var isOnlyButtons = true;
  7389. var groupEl;
  7390. jQuery.each(this.split(','), function(j, buttonName) {
  7391. var customButtonProps;
  7392. var viewSpec;
  7393. var buttonClick;
  7394. var overrideText; // text explicitly set by calendar's constructor options. overcomes icons
  7395. var defaultText;
  7396. var themeIcon;
  7397. var normalIcon;
  7398. var innerHtml;
  7399. var classes;
  7400. var button; // the element
  7401. if (buttonName == 'title') {
  7402. groupChildren = groupChildren.add(jQuery('<h2>&nbsp;</h2>')); // we always want it to take up height
  7403. isOnlyButtons = false;
  7404. }
  7405. else {
  7406. if ((customButtonProps = (calendar.options.customButtons || {})[buttonName])) {
  7407. buttonClick = function(ev) {
  7408. if (customButtonProps.click) {
  7409. customButtonProps.click.call(button[0], ev);
  7410. }
  7411. };
  7412. overrideText = ''; // icons will override text
  7413. defaultText = customButtonProps.text;
  7414. }
  7415. else if ((viewSpec = calendar.getViewSpec(buttonName))) {
  7416. buttonClick = function() {
  7417. calendar.changeView(buttonName);
  7418. };
  7419. viewsWithButtons.push(buttonName);
  7420. overrideText = viewSpec.buttonTextOverride;
  7421. defaultText = viewSpec.buttonTextDefault;
  7422. }
  7423. else if (calendar[buttonName]) { // a calendar method
  7424. buttonClick = function() {
  7425. calendar[buttonName]();
  7426. };
  7427. overrideText = (calendar.overrides.buttonText || {})[buttonName];
  7428. defaultText = options.buttonText[buttonName]; // everything else is considered default
  7429. }
  7430. if (buttonClick) {
  7431. themeIcon =
  7432. customButtonProps ?
  7433. customButtonProps.themeIcon :
  7434. options.themeButtonIcons[buttonName];
  7435. normalIcon =
  7436. customButtonProps ?
  7437. customButtonProps.icon :
  7438. options.buttonIcons[buttonName];
  7439. if (overrideText) {
  7440. innerHtml = htmlEscape(overrideText);
  7441. }
  7442. else if (themeIcon && options.theme) {
  7443. innerHtml = "<span class='ui-icon ui-icon-" + themeIcon + "'></span>";
  7444. }
  7445. else if (normalIcon && !options.theme) {
  7446. innerHtml = "<span class='fc-icon fc-icon-" + normalIcon + "'></span>";
  7447. }
  7448. else {
  7449. innerHtml = htmlEscape(defaultText);
  7450. }
  7451. classes = [
  7452. 'fc-' + buttonName + '-button',
  7453. tm + '-button',
  7454. tm + '-state-default'
  7455. ];
  7456. button = jQuery( // type="button" so that it doesn't submit a form
  7457. '<button type="button" class="' + classes.join(' ') + '">' +
  7458. innerHtml +
  7459. '</button>'
  7460. )
  7461. .click(function(ev) {
  7462. // don't process clicks for disabled buttons
  7463. if (!button.hasClass(tm + '-state-disabled')) {
  7464. buttonClick(ev);
  7465. // after the click action, if the button becomes the "active" tab, or disabled,
  7466. // it should never have a hover class, so remove it now.
  7467. if (
  7468. button.hasClass(tm + '-state-active') ||
  7469. button.hasClass(tm + '-state-disabled')
  7470. ) {
  7471. button.removeClass(tm + '-state-hover');
  7472. }
  7473. }
  7474. })
  7475. .mousedown(function() {
  7476. // the *down* effect (mouse pressed in).
  7477. // only on buttons that are not the "active" tab, or disabled
  7478. button
  7479. .not('.' + tm + '-state-active')
  7480. .not('.' + tm + '-state-disabled')
  7481. .addClass(tm + '-state-down');
  7482. })
  7483. .mouseup(function() {
  7484. // undo the *down* effect
  7485. button.removeClass(tm + '-state-down');
  7486. })
  7487. .hover(
  7488. function() {
  7489. // the *hover* effect.
  7490. // only on buttons that are not the "active" tab, or disabled
  7491. button
  7492. .not('.' + tm + '-state-active')
  7493. .not('.' + tm + '-state-disabled')
  7494. .addClass(tm + '-state-hover');
  7495. },
  7496. function() {
  7497. // undo the *hover* effect
  7498. button
  7499. .removeClass(tm + '-state-hover')
  7500. .removeClass(tm + '-state-down'); // if mouseleave happens before mouseup
  7501. }
  7502. );
  7503. groupChildren = groupChildren.add(button);
  7504. }
  7505. }
  7506. });
  7507. if (isOnlyButtons) {
  7508. groupChildren
  7509. .first().addClass(tm + '-corner-left').end()
  7510. .last().addClass(tm + '-corner-right').end();
  7511. }
  7512. if (groupChildren.length > 1) {
  7513. groupEl = jQuery('<div/>');
  7514. if (isOnlyButtons) {
  7515. groupEl.addClass('fc-button-group');
  7516. }
  7517. groupEl.append(groupChildren);
  7518. sectionEl.append(groupEl);
  7519. }
  7520. else {
  7521. sectionEl.append(groupChildren); // 1 or 0 children
  7522. }
  7523. });
  7524. }
  7525. return sectionEl;
  7526. }
  7527. function updateTitle(text) {
  7528. el.find('h2').text(text);
  7529. }
  7530. function activateButton(buttonName) {
  7531. el.find('.fc-' + buttonName + '-button')
  7532. .addClass(tm + '-state-active');
  7533. }
  7534. function deactivateButton(buttonName) {
  7535. el.find('.fc-' + buttonName + '-button')
  7536. .removeClass(tm + '-state-active');
  7537. }
  7538. function disableButton(buttonName) {
  7539. el.find('.fc-' + buttonName + '-button')
  7540. .attr('disabled', 'disabled')
  7541. .addClass(tm + '-state-disabled');
  7542. }
  7543. function enableButton(buttonName) {
  7544. el.find('.fc-' + buttonName + '-button')
  7545. .removeAttr('disabled')
  7546. .removeClass(tm + '-state-disabled');
  7547. }
  7548. function getViewsWithButtons() {
  7549. return viewsWithButtons;
  7550. }
  7551. }
  7552. ;;
  7553. FC.sourceNormalizers = [];
  7554. FC.sourceFetchers = [];
  7555. var ajaxDefaults = {
  7556. dataType: 'json',
  7557. cache: false
  7558. };
  7559. var eventGUID = 1;
  7560. function EventManager(options) { // assumed to be a calendar
  7561. var t = this;
  7562. // exports
  7563. t.isFetchNeeded = isFetchNeeded;
  7564. t.fetchEvents = fetchEvents;
  7565. t.addEventSource = addEventSource;
  7566. t.removeEventSource = removeEventSource;
  7567. t.updateEvent = updateEvent;
  7568. t.renderEvent = renderEvent;
  7569. t.removeEvents = removeEvents;
  7570. t.clientEvents = clientEvents;
  7571. t.mutateEvent = mutateEvent;
  7572. t.normalizeEventDates = normalizeEventDates;
  7573. t.normalizeEventTimes = normalizeEventTimes;
  7574. // imports
  7575. var reportEvents = t.reportEvents;
  7576. // locals
  7577. var stickySource = { events: [] };
  7578. var sources = [ stickySource ];
  7579. var rangeStart, rangeEnd;
  7580. var currentFetchID = 0;
  7581. var pendingSourceCnt = 0;
  7582. var cache = []; // holds events that have already been expanded
  7583. jQuery.each(
  7584. (options.events ? [ options.events ] : []).concat(options.eventSources || []),
  7585. function(i, sourceInput) {
  7586. var source = buildEventSource(sourceInput);
  7587. if (source) {
  7588. sources.push(source);
  7589. }
  7590. }
  7591. );
  7592. /* Fetching
  7593. -----------------------------------------------------------------------------*/
  7594. // start and end are assumed to be unzoned
  7595. function isFetchNeeded(start, end) {
  7596. return !rangeStart || // nothing has been fetched yet?
  7597. start < rangeStart || end > rangeEnd; // is part of the new range outside of the old range?
  7598. }
  7599. function fetchEvents(start, end) {
  7600. rangeStart = start;
  7601. rangeEnd = end;
  7602. cache = [];
  7603. var fetchID = ++currentFetchID;
  7604. var len = sources.length;
  7605. pendingSourceCnt = len;
  7606. for (var i=0; i<len; i++) {
  7607. fetchEventSource(sources[i], fetchID);
  7608. }
  7609. }
  7610. function fetchEventSource(source, fetchID) {
  7611. _fetchEventSource(source, function(eventInputs) {
  7612. var isArraySource = jQuery.isArray(source.events);
  7613. var i, eventInput;
  7614. var abstractEvent;
  7615. if (fetchID == currentFetchID) {
  7616. if (eventInputs) {
  7617. for (i = 0; i < eventInputs.length; i++) {
  7618. eventInput = eventInputs[i];
  7619. if (isArraySource) { // array sources have already been convert to Event Objects
  7620. abstractEvent = eventInput;
  7621. }
  7622. else {
  7623. abstractEvent = buildEventFromInput(eventInput, source);
  7624. }
  7625. if (abstractEvent) { // not false (an invalid event)
  7626. cache.push.apply(
  7627. cache,
  7628. expandEvent(abstractEvent) // add individual expanded events to the cache
  7629. );
  7630. }
  7631. }
  7632. }
  7633. pendingSourceCnt--;
  7634. if (!pendingSourceCnt) {
  7635. reportEvents(cache);
  7636. }
  7637. }
  7638. });
  7639. }
  7640. function _fetchEventSource(source, callback) {
  7641. var i;
  7642. var fetchers = FC.sourceFetchers;
  7643. var res;
  7644. for (i=0; i<fetchers.length; i++) {
  7645. res = fetchers[i].call(
  7646. t, // this, the Calendar object
  7647. source,
  7648. rangeStart.clone(),
  7649. rangeEnd.clone(),
  7650. options.timezone,
  7651. callback
  7652. );
  7653. if (res === true) {
  7654. // the fetcher is in charge. made its own async request
  7655. return;
  7656. }
  7657. else if (typeof res == 'object') {
  7658. // the fetcher returned a new source. process it
  7659. _fetchEventSource(res, callback);
  7660. return;
  7661. }
  7662. }
  7663. var events = source.events;
  7664. if (events) {
  7665. if (jQuery.isFunction(events)) {
  7666. t.pushLoading();
  7667. events.call(
  7668. t, // this, the Calendar object
  7669. rangeStart.clone(),
  7670. rangeEnd.clone(),
  7671. options.timezone,
  7672. function(events) {
  7673. callback(events);
  7674. t.popLoading();
  7675. }
  7676. );
  7677. }
  7678. else if (jQuery.isArray(events)) {
  7679. callback(events);
  7680. }
  7681. else {
  7682. callback();
  7683. }
  7684. }else{
  7685. var url = source.url;
  7686. if (url) {
  7687. var success = source.success;
  7688. var error = source.error;
  7689. var complete = source.complete;
  7690. // retrieve any outbound GET/POST jQuery.ajax data from the options
  7691. var customData;
  7692. if (jQuery.isFunction(source.data)) {
  7693. // supplied as a function that returns a key/value object
  7694. customData = source.data();
  7695. }
  7696. else {
  7697. // supplied as a straight key/value object
  7698. customData = source.data;
  7699. }
  7700. // use a copy of the custom data so we can modify the parameters
  7701. // and not affect the passed-in object.
  7702. var data = jQuery.extend({}, customData || {});
  7703. var startParam = firstDefined(source.startParam, options.startParam);
  7704. var endParam = firstDefined(source.endParam, options.endParam);
  7705. var timezoneParam = firstDefined(source.timezoneParam, options.timezoneParam);
  7706. if (startParam) {
  7707. data[startParam] = rangeStart.format();
  7708. }
  7709. if (endParam) {
  7710. data[endParam] = rangeEnd.format();
  7711. }
  7712. if (options.timezone && options.timezone != 'local') {
  7713. data[timezoneParam] = options.timezone;
  7714. }
  7715. t.pushLoading();
  7716. jQuery.ajax(jQuery.extend({}, ajaxDefaults, source, {
  7717. data: data,
  7718. success: function(events) {
  7719. events = events || [];
  7720. var res = applyAll(success, this, arguments);
  7721. if (jQuery.isArray(res)) {
  7722. events = res;
  7723. }
  7724. callback(events);
  7725. },
  7726. error: function() {
  7727. applyAll(error, this, arguments);
  7728. callback();
  7729. },
  7730. complete: function() {
  7731. applyAll(complete, this, arguments);
  7732. t.popLoading();
  7733. }
  7734. }));
  7735. }else{
  7736. callback();
  7737. }
  7738. }
  7739. }
  7740. /* Sources
  7741. -----------------------------------------------------------------------------*/
  7742. function addEventSource(sourceInput) {
  7743. var source = buildEventSource(sourceInput);
  7744. if (source) {
  7745. sources.push(source);
  7746. pendingSourceCnt++;
  7747. fetchEventSource(source, currentFetchID); // will eventually call reportEvents
  7748. }
  7749. }
  7750. function buildEventSource(sourceInput) { // will return undefined if invalid source
  7751. var normalizers = FC.sourceNormalizers;
  7752. var source;
  7753. var i;
  7754. if (jQuery.isFunction(sourceInput) || jQuery.isArray(sourceInput)) {
  7755. source = { events: sourceInput };
  7756. }
  7757. else if (typeof sourceInput === 'string') {
  7758. source = { url: sourceInput };
  7759. }
  7760. else if (typeof sourceInput === 'object') {
  7761. source = jQuery.extend({}, sourceInput); // shallow copy
  7762. }
  7763. if (source) {
  7764. // TODO: repeat code, same code for event classNames
  7765. if (source.className) {
  7766. if (typeof source.className === 'string') {
  7767. source.className = source.className.split(/\s+/);
  7768. }
  7769. // otherwise, assumed to be an array
  7770. }
  7771. else {
  7772. source.className = [];
  7773. }
  7774. // for array sources, we convert to standard Event Objects up front
  7775. if (jQuery.isArray(source.events)) {
  7776. source.origArray = source.events; // for removeEventSource
  7777. source.events = jQuery.map(source.events, function(eventInput) {
  7778. return buildEventFromInput(eventInput, source);
  7779. });
  7780. }
  7781. for (i=0; i<normalizers.length; i++) {
  7782. normalizers[i].call(t, source);
  7783. }
  7784. return source;
  7785. }
  7786. }
  7787. function removeEventSource(source) {
  7788. sources = jQuery.grep(sources, function(src) {
  7789. return !isSourcesEqual(src, source);
  7790. });
  7791. // remove all client events from that source
  7792. cache = jQuery.grep(cache, function(e) {
  7793. return !isSourcesEqual(e.source, source);
  7794. });
  7795. reportEvents(cache);
  7796. }
  7797. function isSourcesEqual(source1, source2) {
  7798. return source1 && source2 && getSourcePrimitive(source1) == getSourcePrimitive(source2);
  7799. }
  7800. function getSourcePrimitive(source) {
  7801. return (
  7802. (typeof source === 'object') ? // a normalized event source?
  7803. (source.origArray || source.googleCalendarId || source.url || source.events) : // get the primitive
  7804. null
  7805. ) ||
  7806. source; // the given argument *is* the primitive
  7807. }
  7808. /* Manipulation
  7809. -----------------------------------------------------------------------------*/
  7810. // Only ever called from the externally-facing API
  7811. function updateEvent(event) {
  7812. // massage start/end values, even if date string values
  7813. event.start = t.moment(event.start);
  7814. if (event.end) {
  7815. event.end = t.moment(event.end);
  7816. }
  7817. else {
  7818. event.end = null;
  7819. }
  7820. mutateEvent(event, getMiscEventProps(event)); // will handle start/end/allDay normalization
  7821. reportEvents(cache); // reports event modifications (so we can redraw)
  7822. }
  7823. // Returns a hash of misc event properties that should be copied over to related events.
  7824. function getMiscEventProps(event) {
  7825. var props = {};
  7826. jQuery.each(event, function(name, val) {
  7827. if (isMiscEventPropName(name)) {
  7828. if (val !== undefined && isAtomic(val)) { // a defined non-object
  7829. props[name] = val;
  7830. }
  7831. }
  7832. });
  7833. return props;
  7834. }
  7835. // non-date-related, non-id-related, non-secret
  7836. function isMiscEventPropName(name) {
  7837. return !/^_|^(id|allDay|start|end)$/.test(name);
  7838. }
  7839. // returns the expanded events that were created
  7840. function renderEvent(eventInput, stick) {
  7841. var abstractEvent = buildEventFromInput(eventInput);
  7842. var events;
  7843. var i, event;
  7844. if (abstractEvent) { // not false (a valid input)
  7845. events = expandEvent(abstractEvent);
  7846. for (i = 0; i < events.length; i++) {
  7847. event = events[i];
  7848. if (!event.source) {
  7849. if (stick) {
  7850. stickySource.events.push(event);
  7851. event.source = stickySource;
  7852. }
  7853. cache.push(event);
  7854. }
  7855. }
  7856. reportEvents(cache);
  7857. return events;
  7858. }
  7859. return [];
  7860. }
  7861. function removeEvents(filter) {
  7862. var eventID;
  7863. var i;
  7864. if (filter == null) { // null or undefined. remove all events
  7865. filter = function() { return true; }; // will always match
  7866. }
  7867. else if (!jQuery.isFunction(filter)) { // an event ID
  7868. eventID = filter + '';
  7869. filter = function(event) {
  7870. return event._id == eventID;
  7871. };
  7872. }
  7873. // Purge event(s) from our local cache
  7874. cache = jQuery.grep(cache, filter, true); // inverse=true
  7875. // Remove events from array sources.
  7876. // This works because they have been converted to official Event Objects up front.
  7877. // (and as a result, event._id has been calculated).
  7878. for (i=0; i<sources.length; i++) {
  7879. if (jQuery.isArray(sources[i].events)) {
  7880. sources[i].events = jQuery.grep(sources[i].events, filter, true);
  7881. }
  7882. }
  7883. reportEvents(cache);
  7884. }
  7885. function clientEvents(filter) {
  7886. if (jQuery.isFunction(filter)) {
  7887. return jQuery.grep(cache, filter);
  7888. }
  7889. else if (filter != null) { // not null, not undefined. an event ID
  7890. filter += '';
  7891. return jQuery.grep(cache, function(e) {
  7892. return e._id == filter;
  7893. });
  7894. }
  7895. return cache; // else, return all
  7896. }
  7897. /* Event Normalization
  7898. -----------------------------------------------------------------------------*/
  7899. // Given a raw object with key/value properties, returns an "abstract" Event object.
  7900. // An "abstract" event is an event that, if recurring, will not have been expanded yet.
  7901. // Will return `false` when input is invalid.
  7902. // `source` is optional
  7903. function buildEventFromInput(input, source) {
  7904. var out = {};
  7905. var start, end;
  7906. var allDay;
  7907. if (options.eventDataTransform) {
  7908. input = options.eventDataTransform(input);
  7909. }
  7910. if (source && source.eventDataTransform) {
  7911. input = source.eventDataTransform(input);
  7912. }
  7913. // Copy all properties over to the resulting object.
  7914. // The special-case properties will be copied over afterwards.
  7915. jQuery.extend(out, input);
  7916. if (source) {
  7917. out.source = source;
  7918. }
  7919. out._id = input._id || (input.id === undefined ? '_fc' + eventGUID++ : input.id + '');
  7920. if (input.className) {
  7921. if (typeof input.className == 'string') {
  7922. out.className = input.className.split(/\s+/);
  7923. }
  7924. else { // assumed to be an array
  7925. out.className = input.className;
  7926. }
  7927. }
  7928. else {
  7929. out.className = [];
  7930. }
  7931. start = input.start || input.date; // "date" is an alias for "start"
  7932. end = input.end;
  7933. // parse as a time (Duration) if applicable
  7934. if (isTimeString(start)) {
  7935. start = moment.duration(start);
  7936. }
  7937. if (isTimeString(end)) {
  7938. end = moment.duration(end);
  7939. }
  7940. if (input.dow || moment.isDuration(start) || moment.isDuration(end)) {
  7941. // the event is "abstract" (recurring) so don't calculate exact start/end dates just yet
  7942. out.start = start ? moment.duration(start) : null; // will be a Duration or null
  7943. out.end = end ? moment.duration(end) : null; // will be a Duration or null
  7944. out._recurring = true; // our internal marker
  7945. }
  7946. else {
  7947. if (start) {
  7948. start = t.moment(start);
  7949. if (!start.isValid()) {
  7950. return false;
  7951. }
  7952. }
  7953. if (end) {
  7954. end = t.moment(end);
  7955. if (!end.isValid()) {
  7956. end = null; // let defaults take over
  7957. }
  7958. }
  7959. allDay = input.allDay;
  7960. if (allDay === undefined) { // still undefined? fallback to default
  7961. allDay = firstDefined(
  7962. source ? source.allDayDefault : undefined,
  7963. options.allDayDefault
  7964. );
  7965. // still undefined? normalizeEventDates will calculate it
  7966. }
  7967. assignDatesToEvent(start, end, allDay, out);
  7968. }
  7969. return out;
  7970. }
  7971. // Normalizes and assigns the given dates to the given partially-formed event object.
  7972. // NOTE: mutates the given start/end moments. does not make a copy.
  7973. function assignDatesToEvent(start, end, allDay, event) {
  7974. event.start = start;
  7975. event.end = end;
  7976. event.allDay = allDay;
  7977. normalizeEventDates(event);
  7978. backupEventDates(event);
  7979. }
  7980. // Ensures proper values for allDay/start/end. Accepts an Event object, or a plain object with event-ish properties.
  7981. // NOTE: Will modify the given object.
  7982. function normalizeEventDates(eventProps) {
  7983. normalizeEventTimes(eventProps);
  7984. if (eventProps.end && !eventProps.end.isAfter(eventProps.start)) {
  7985. eventProps.end = null;
  7986. }
  7987. if (!eventProps.end) {
  7988. if (options.forceEventDuration) {
  7989. eventProps.end = t.getDefaultEventEnd(eventProps.allDay, eventProps.start);
  7990. }
  7991. else {
  7992. eventProps.end = null;
  7993. }
  7994. }
  7995. }
  7996. // Ensures the allDay property exists and the timeliness of the start/end dates are consistent
  7997. function normalizeEventTimes(eventProps) {
  7998. if (eventProps.allDay == null) {
  7999. eventProps.allDay = !(eventProps.start.hasTime() || (eventProps.end && eventProps.end.hasTime()));
  8000. }
  8001. if (eventProps.allDay) {
  8002. eventProps.start.stripTime();
  8003. if (eventProps.end) {
  8004. // TODO: consider nextDayThreshold here? If so, will require a lot of testing and adjustment
  8005. eventProps.end.stripTime();
  8006. }
  8007. }
  8008. else {
  8009. if (!eventProps.start.hasTime()) {
  8010. eventProps.start = t.applyTimezone(eventProps.start.time(0)); // will assign a 00:00 time
  8011. }
  8012. if (eventProps.end && !eventProps.end.hasTime()) {
  8013. eventProps.end = t.applyTimezone(eventProps.end.time(0)); // will assign a 00:00 time
  8014. }
  8015. }
  8016. }
  8017. // If the given event is a recurring event, break it down into an array of individual instances.
  8018. // If not a recurring event, return an array with the single original event.
  8019. // If given a falsy input (probably because of a failed buildEventFromInput call), returns an empty array.
  8020. // HACK: can override the recurring window by providing custom rangeStart/rangeEnd (for businessHours).
  8021. function expandEvent(abstractEvent, _rangeStart, _rangeEnd) {
  8022. var events = [];
  8023. var dowHash;
  8024. var dow;
  8025. var i;
  8026. var date;
  8027. var startTime, endTime;
  8028. var start, end;
  8029. var event;
  8030. _rangeStart = _rangeStart || rangeStart;
  8031. _rangeEnd = _rangeEnd || rangeEnd;
  8032. if (abstractEvent) {
  8033. if (abstractEvent._recurring) {
  8034. // make a boolean hash as to whether the event occurs on each day-of-week
  8035. if ((dow = abstractEvent.dow)) {
  8036. dowHash = {};
  8037. for (i = 0; i < dow.length; i++) {
  8038. dowHash[dow[i]] = true;
  8039. }
  8040. }
  8041. // iterate through every day in the current range
  8042. date = _rangeStart.clone().stripTime(); // holds the date of the current day
  8043. while (date.isBefore(_rangeEnd)) {
  8044. if (!dowHash || dowHash[date.day()]) { // if everyday, or this particular day-of-week
  8045. startTime = abstractEvent.start; // the stored start and end properties are times (Durations)
  8046. endTime = abstractEvent.end; // "
  8047. start = date.clone();
  8048. end = null;
  8049. if (startTime) {
  8050. start = start.time(startTime);
  8051. }
  8052. if (endTime) {
  8053. end = date.clone().time(endTime);
  8054. }
  8055. event = jQuery.extend({}, abstractEvent); // make a copy of the original
  8056. assignDatesToEvent(
  8057. start, end,
  8058. !startTime && !endTime, // allDay?
  8059. event
  8060. );
  8061. events.push(event);
  8062. }
  8063. date.add(1, 'days');
  8064. }
  8065. }
  8066. else {
  8067. events.push(abstractEvent); // return the original event. will be a one-item array
  8068. }
  8069. }
  8070. return events;
  8071. }
  8072. /* Event Modification Math
  8073. -----------------------------------------------------------------------------------------*/
  8074. // Modifies an event and all related events by applying the given properties.
  8075. // Special date-diffing logic is used for manipulation of dates.
  8076. // If `props` does not contain start/end dates, the updated values are assumed to be the event's current start/end.
  8077. // All date comparisons are done against the event's pristine _start and _end dates.
  8078. // Returns an object with delta information and a function to undo all operations.
  8079. // For making computations in a granularity greater than day/time, specify largeUnit.
  8080. // NOTE: The given `newProps` might be mutated for normalization purposes.
  8081. function mutateEvent(event, newProps, largeUnit) {
  8082. var miscProps = {};
  8083. var oldProps;
  8084. var clearEnd;
  8085. var startDelta;
  8086. var endDelta;
  8087. var durationDelta;
  8088. var undoFunc;
  8089. // diffs the dates in the appropriate way, returning a duration
  8090. function diffDates(date1, date0) { // date1 - date0
  8091. if (largeUnit) {
  8092. return diffByUnit(date1, date0, largeUnit);
  8093. }
  8094. else if (newProps.allDay) {
  8095. return diffDay(date1, date0);
  8096. }
  8097. else {
  8098. return diffDayTime(date1, date0);
  8099. }
  8100. }
  8101. newProps = newProps || {};
  8102. // normalize new date-related properties
  8103. if (!newProps.start) {
  8104. newProps.start = event.start.clone();
  8105. }
  8106. if (newProps.end === undefined) {
  8107. newProps.end = event.end ? event.end.clone() : null;
  8108. }
  8109. if (newProps.allDay == null) { // is null or undefined?
  8110. newProps.allDay = event.allDay;
  8111. }
  8112. normalizeEventDates(newProps);
  8113. // create normalized versions of the original props to compare against
  8114. // need a real end value, for diffing
  8115. oldProps = {
  8116. start: event._start.clone(),
  8117. end: event._end ? event._end.clone() : t.getDefaultEventEnd(event._allDay, event._start),
  8118. allDay: newProps.allDay // normalize the dates in the same regard as the new properties
  8119. };
  8120. normalizeEventDates(oldProps);
  8121. // need to clear the end date if explicitly changed to null
  8122. clearEnd = event._end !== null && newProps.end === null;
  8123. // compute the delta for moving the start date
  8124. startDelta = diffDates(newProps.start, oldProps.start);
  8125. // compute the delta for moving the end date
  8126. if (newProps.end) {
  8127. endDelta = diffDates(newProps.end, oldProps.end);
  8128. durationDelta = endDelta.subtract(startDelta);
  8129. }
  8130. else {
  8131. durationDelta = null;
  8132. }
  8133. // gather all non-date-related properties
  8134. jQuery.each(newProps, function(name, val) {
  8135. if (isMiscEventPropName(name)) {
  8136. if (val !== undefined) {
  8137. miscProps[name] = val;
  8138. }
  8139. }
  8140. });
  8141. // apply the operations to the event and all related events
  8142. undoFunc = mutateEvents(
  8143. clientEvents(event._id), // get events with this ID
  8144. clearEnd,
  8145. newProps.allDay,
  8146. startDelta,
  8147. durationDelta,
  8148. miscProps
  8149. );
  8150. return {
  8151. dateDelta: startDelta,
  8152. durationDelta: durationDelta,
  8153. undo: undoFunc
  8154. };
  8155. }
  8156. // Modifies an array of events in the following ways (operations are in order):
  8157. // - clear the event's `end`
  8158. // - convert the event to allDay
  8159. // - add `dateDelta` to the start and end
  8160. // - add `durationDelta` to the event's duration
  8161. // - assign `miscProps` to the event
  8162. //
  8163. // Returns a function that can be called to undo all the operations.
  8164. //
  8165. // TODO: don't use so many closures. possible memory issues when lots of events with same ID.
  8166. //
  8167. function mutateEvents(events, clearEnd, allDay, dateDelta, durationDelta, miscProps) {
  8168. var isAmbigTimezone = t.getIsAmbigTimezone();
  8169. var undoFunctions = [];
  8170. // normalize zero-length deltas to be null
  8171. if (dateDelta && !dateDelta.valueOf()) { dateDelta = null; }
  8172. if (durationDelta && !durationDelta.valueOf()) { durationDelta = null; }
  8173. jQuery.each(events, function(i, event) {
  8174. var oldProps;
  8175. var newProps;
  8176. // build an object holding all the old values, both date-related and misc.
  8177. // for the undo function.
  8178. oldProps = {
  8179. start: event.start.clone(),
  8180. end: event.end ? event.end.clone() : null,
  8181. allDay: event.allDay
  8182. };
  8183. jQuery.each(miscProps, function(name) {
  8184. oldProps[name] = event[name];
  8185. });
  8186. // new date-related properties. work off the original date snapshot.
  8187. // ok to use references because they will be thrown away when backupEventDates is called.
  8188. newProps = {
  8189. start: event._start,
  8190. end: event._end,
  8191. allDay: allDay // normalize the dates in the same regard as the new properties
  8192. };
  8193. normalizeEventDates(newProps); // massages start/end/allDay
  8194. // strip or ensure the end date
  8195. if (clearEnd) {
  8196. newProps.end = null;
  8197. }
  8198. else if (durationDelta && !newProps.end) { // the duration translation requires an end date
  8199. newProps.end = t.getDefaultEventEnd(newProps.allDay, newProps.start);
  8200. }
  8201. if (dateDelta) {
  8202. newProps.start.add(dateDelta);
  8203. if (newProps.end) {
  8204. newProps.end.add(dateDelta);
  8205. }
  8206. }
  8207. if (durationDelta) {
  8208. newProps.end.add(durationDelta); // end already ensured above
  8209. }
  8210. // if the dates have changed, and we know it is impossible to recompute the
  8211. // timezone offsets, strip the zone.
  8212. if (
  8213. isAmbigTimezone &&
  8214. !newProps.allDay &&
  8215. (dateDelta || durationDelta)
  8216. ) {
  8217. newProps.start.stripZone();
  8218. if (newProps.end) {
  8219. newProps.end.stripZone();
  8220. }
  8221. }
  8222. jQuery.extend(event, miscProps, newProps); // copy over misc props, then date-related props
  8223. backupEventDates(event); // regenerate internal _start/_end/_allDay
  8224. undoFunctions.push(function() {
  8225. jQuery.extend(event, oldProps);
  8226. backupEventDates(event); // regenerate internal _start/_end/_allDay
  8227. });
  8228. });
  8229. return function() {
  8230. for (var i = 0; i < undoFunctions.length; i++) {
  8231. undoFunctions[i]();
  8232. }
  8233. };
  8234. }
  8235. /* Business Hours
  8236. -----------------------------------------------------------------------------------------*/
  8237. t.getBusinessHoursEvents = getBusinessHoursEvents;
  8238. // Returns an array of events as to when the business hours occur in the given view.
  8239. // Abuse of our event system :(
  8240. function getBusinessHoursEvents(wholeDay) {
  8241. var optionVal = options.businessHours;
  8242. var defaultVal = {
  8243. className: 'fc-nonbusiness',
  8244. start: '09:00',
  8245. end: '17:00',
  8246. dow: [ 1, 2, 3, 4, 5 ], // monday - friday
  8247. rendering: 'inverse-background'
  8248. };
  8249. var view = t.getView();
  8250. var eventInput;
  8251. if (optionVal) { // `true` (which means "use the defaults") or an override object
  8252. eventInput = jQuery.extend(
  8253. {}, // copy to a new object in either case
  8254. defaultVal,
  8255. typeof optionVal === 'object' ? optionVal : {} // override the defaults
  8256. );
  8257. }
  8258. if (eventInput) {
  8259. // if a whole-day series is requested, clear the start/end times
  8260. if (wholeDay) {
  8261. eventInput.start = null;
  8262. eventInput.end = null;
  8263. }
  8264. return expandEvent(
  8265. buildEventFromInput(eventInput),
  8266. view.start,
  8267. view.end
  8268. );
  8269. }
  8270. return [];
  8271. }
  8272. /* Overlapping / Constraining
  8273. -----------------------------------------------------------------------------------------*/
  8274. t.isEventSpanAllowed = isEventSpanAllowed;
  8275. t.isExternalSpanAllowed = isExternalSpanAllowed;
  8276. t.isSelectionSpanAllowed = isSelectionSpanAllowed;
  8277. // Determines if the given event can be relocated to the given span (unzoned start/end with other misc data)
  8278. function isEventSpanAllowed(span, event) {
  8279. var source = event.source || {};
  8280. var constraint = firstDefined(
  8281. event.constraint,
  8282. source.constraint,
  8283. options.eventConstraint
  8284. );
  8285. var overlap = firstDefined(
  8286. event.overlap,
  8287. source.overlap,
  8288. options.eventOverlap
  8289. );
  8290. return isSpanAllowed(span, constraint, overlap, event);
  8291. }
  8292. // Determines if an external event can be relocated to the given span (unzoned start/end with other misc data)
  8293. function isExternalSpanAllowed(eventSpan, eventLocation, eventProps) {
  8294. var eventInput;
  8295. var event;
  8296. // note: very similar logic is in View's reportExternalDrop
  8297. if (eventProps) {
  8298. eventInput = jQuery.extend({}, eventProps, eventLocation);
  8299. event = expandEvent(buildEventFromInput(eventInput))[0];
  8300. }
  8301. if (event) {
  8302. return isEventSpanAllowed(eventSpan, event);
  8303. }
  8304. else { // treat it as a selection
  8305. return isSelectionSpanAllowed(eventSpan);
  8306. }
  8307. }
  8308. // Determines the given span (unzoned start/end with other misc data) can be selected.
  8309. function isSelectionSpanAllowed(span) {
  8310. return isSpanAllowed(span, options.selectConstraint, options.selectOverlap);
  8311. }
  8312. // Returns true if the given span (caused by an event drop/resize or a selection) is allowed to exist
  8313. // according to the constraint/overlap settings.
  8314. // `event` is not required if checking a selection.
  8315. function isSpanAllowed(span, constraint, overlap, event) {
  8316. var constraintEvents;
  8317. var anyContainment;
  8318. var peerEvents;
  8319. var i, peerEvent;
  8320. var peerOverlap;
  8321. // the range must be fully contained by at least one of produced constraint events
  8322. if (constraint != null) {
  8323. // not treated as an event! intermediate data structure
  8324. // TODO: use ranges in the future
  8325. constraintEvents = constraintToEvents(constraint);
  8326. anyContainment = false;
  8327. for (i = 0; i < constraintEvents.length; i++) {
  8328. if (eventContainsRange(constraintEvents[i], span)) {
  8329. anyContainment = true;
  8330. break;
  8331. }
  8332. }
  8333. if (!anyContainment) {
  8334. return false;
  8335. }
  8336. }
  8337. peerEvents = t.getPeerEvents(span, event);
  8338. for (i = 0; i < peerEvents.length; i++) {
  8339. peerEvent = peerEvents[i];
  8340. // there needs to be an actual intersection before disallowing anything
  8341. if (eventIntersectsRange(peerEvent, span)) {
  8342. // evaluate overlap for the given range and short-circuit if necessary
  8343. if (overlap === false) {
  8344. return false;
  8345. }
  8346. // if the event's overlap is a test function, pass the peer event in question as the first param
  8347. else if (typeof overlap === 'function' && !overlap(peerEvent, event)) {
  8348. return false;
  8349. }
  8350. // if we are computing if the given range is allowable for an event, consider the other event's
  8351. // EventObject-specific or Source-specific `overlap` property
  8352. if (event) {
  8353. peerOverlap = firstDefined(
  8354. peerEvent.overlap,
  8355. (peerEvent.source || {}).overlap
  8356. // we already considered the global `eventOverlap`
  8357. );
  8358. if (peerOverlap === false) {
  8359. return false;
  8360. }
  8361. // if the peer event's overlap is a test function, pass the subject event as the first param
  8362. if (typeof peerOverlap === 'function' && !peerOverlap(event, peerEvent)) {
  8363. return false;
  8364. }
  8365. }
  8366. }
  8367. }
  8368. return true;
  8369. }
  8370. // Given an event input from the API, produces an array of event objects. Possible event inputs:
  8371. // 'businessHours'
  8372. // An event ID (number or string)
  8373. // An object with specific start/end dates or a recurring event (like what businessHours accepts)
  8374. function constraintToEvents(constraintInput) {
  8375. if (constraintInput === 'businessHours') {
  8376. return getBusinessHoursEvents();
  8377. }
  8378. if (typeof constraintInput === 'object') {
  8379. return expandEvent(buildEventFromInput(constraintInput));
  8380. }
  8381. return clientEvents(constraintInput); // probably an ID
  8382. }
  8383. // Does the event's date range fully contain the given range?
  8384. // start/end already assumed to have stripped zones :(
  8385. function eventContainsRange(event, range) {
  8386. var eventStart = event.start.clone().stripZone();
  8387. var eventEnd = t.getEventEnd(event).stripZone();
  8388. return range.start >= eventStart && range.end <= eventEnd;
  8389. }
  8390. // Does the event's date range intersect with the given range?
  8391. // start/end already assumed to have stripped zones :(
  8392. function eventIntersectsRange(event, range) {
  8393. var eventStart = event.start.clone().stripZone();
  8394. var eventEnd = t.getEventEnd(event).stripZone();
  8395. return range.start < eventEnd && range.end > eventStart;
  8396. }
  8397. t.getEventCache = function() {
  8398. return cache;
  8399. };
  8400. }
  8401. // Returns a list of events that the given event should be compared against when being considered for a move to
  8402. // the specified span. Attached to the Calendar's prototype because EventManager is a mixin for a Calendar.
  8403. Calendar.prototype.getPeerEvents = function(span, event) {
  8404. var cache = this.getEventCache();
  8405. var peerEvents = [];
  8406. var i, otherEvent;
  8407. for (i = 0; i < cache.length; i++) {
  8408. otherEvent = cache[i];
  8409. if (
  8410. !event ||
  8411. event._id !== otherEvent._id // don't compare the event to itself or other related [repeating] events
  8412. ) {
  8413. peerEvents.push(otherEvent);
  8414. }
  8415. }
  8416. return peerEvents;
  8417. };
  8418. // updates the "backup" properties, which are preserved in order to compute diffs later on.
  8419. function backupEventDates(event) {
  8420. event._allDay = event.allDay;
  8421. event._start = event.start.clone();
  8422. event._end = event.end ? event.end.clone() : null;
  8423. }
  8424. ;;
  8425. /* An abstract class for the "basic" views, as well as month view. Renders one or more rows of day cells.
  8426. ----------------------------------------------------------------------------------------------------------------------*/
  8427. // It is a manager for a DayGrid subcomponent, which does most of the heavy lifting.
  8428. // It is responsible for managing width/height.
  8429. var BasicView = FC.BasicView = View.extend({
  8430. dayGridClass: DayGrid, // class the dayGrid will be instantiated from (overridable by subclasses)
  8431. dayGrid: null, // the main subcomponent that does most of the heavy lifting
  8432. dayNumbersVisible: false, // display day numbers on each day cell?
  8433. weekNumbersVisible: false, // display week numbers along the side?
  8434. weekNumberWidth: null, // width of all the week-number cells running down the side
  8435. headContainerEl: null, // div that hold's the dayGrid's rendered date header
  8436. headRowEl: null, // the fake row element of the day-of-week header
  8437. initialize: function() {
  8438. this.dayGrid = this.instantiateDayGrid();
  8439. },
  8440. // Generates the DayGrid object this view needs. Draws from this.dayGridClass
  8441. instantiateDayGrid: function() {
  8442. // generate a subclass on the fly with BasicView-specific behavior
  8443. // TODO: cache this subclass
  8444. var subclass = this.dayGridClass.extend(basicDayGridMethods);
  8445. return new subclass(this);
  8446. },
  8447. // Sets the display range and computes all necessary dates
  8448. setRange: function(range) {
  8449. View.prototype.setRange.call(this, range); // call the super-method
  8450. this.dayGrid.breakOnWeeks = /year|month|week/.test(this.intervalUnit); // do before setRange
  8451. this.dayGrid.setRange(range);
  8452. },
  8453. // Compute the value to feed into setRange. Overrides superclass.
  8454. computeRange: function(date) {
  8455. var range = View.prototype.computeRange.call(this, date); // get value from the super-method
  8456. // year and month views should be aligned with weeks. this is already done for week
  8457. if (/year|month/.test(range.intervalUnit)) {
  8458. range.start.startOf('week');
  8459. range.start = this.skipHiddenDays(range.start);
  8460. // make end-of-week if not already
  8461. if (range.end.weekday()) {
  8462. range.end.add(1, 'week').startOf('week');
  8463. range.end = this.skipHiddenDays(range.end, -1, true); // exclusively move backwards
  8464. }
  8465. }
  8466. return range;
  8467. },
  8468. // Renders the view into `this.el`, which should already be assigned
  8469. renderDates: function() {
  8470. this.dayNumbersVisible = this.dayGrid.rowCnt > 1; // TODO: make grid responsible
  8471. this.weekNumbersVisible = this.opt('weekNumbers');
  8472. this.dayGrid.numbersVisible = this.dayNumbersVisible || this.weekNumbersVisible;
  8473. this.el.addClass('fc-basic-view').html(this.renderSkeletonHtml());
  8474. this.renderHead();
  8475. this.scrollerEl = this.el.find('.fc-day-grid-container');
  8476. this.dayGrid.setElement(this.el.find('.fc-day-grid'));
  8477. this.dayGrid.renderDates(this.hasRigidRows());
  8478. },
  8479. // render the day-of-week headers
  8480. renderHead: function() {
  8481. this.headContainerEl =
  8482. this.el.find('.fc-head-container')
  8483. .html(this.dayGrid.renderHeadHtml());
  8484. this.headRowEl = this.headContainerEl.find('.fc-row');
  8485. },
  8486. // Unrenders the content of the view. Since we haven't separated skeleton rendering from date rendering,
  8487. // always completely kill the dayGrid's rendering.
  8488. unrenderDates: function() {
  8489. this.dayGrid.unrenderDates();
  8490. this.dayGrid.removeElement();
  8491. },
  8492. renderBusinessHours: function() {
  8493. this.dayGrid.renderBusinessHours();
  8494. },
  8495. // Builds the HTML skeleton for the view.
  8496. // The day-grid component will render inside of a container defined by this HTML.
  8497. renderSkeletonHtml: function() {
  8498. return '' +
  8499. '<table>' +
  8500. '<thead class="fc-head">' +
  8501. '<tr>' +
  8502. '<td class="fc-head-container ' + this.widgetHeaderClass + '"></td>' +
  8503. '</tr>' +
  8504. '</thead>' +
  8505. '<tbody class="fc-body">' +
  8506. '<tr>' +
  8507. '<td class="' + this.widgetContentClass + '">' +
  8508. '<div class="fc-day-grid-container">' +
  8509. '<div class="fc-day-grid"/>' +
  8510. '</div>' +
  8511. '</td>' +
  8512. '</tr>' +
  8513. '</tbody>' +
  8514. '</table>';
  8515. },
  8516. // Generates an HTML attribute string for setting the width of the week number column, if it is known
  8517. weekNumberStyleAttr: function() {
  8518. if (this.weekNumberWidth !== null) {
  8519. return 'style="width:' + this.weekNumberWidth + 'px"';
  8520. }
  8521. return '';
  8522. },
  8523. // Determines whether each row should have a constant height
  8524. hasRigidRows: function() {
  8525. var eventLimit = this.opt('eventLimit');
  8526. return eventLimit && typeof eventLimit !== 'number';
  8527. },
  8528. /* Dimensions
  8529. ------------------------------------------------------------------------------------------------------------------*/
  8530. // Refreshes the horizontal dimensions of the view
  8531. updateWidth: function() {
  8532. if (this.weekNumbersVisible) {
  8533. // Make sure all week number cells running down the side have the same width.
  8534. // Record the width for cells created later.
  8535. this.weekNumberWidth = matchCellWidths(
  8536. this.el.find('.fc-week-number')
  8537. );
  8538. }
  8539. },
  8540. // Adjusts the vertical dimensions of the view to the specified values
  8541. setHeight: function(totalHeight, isAuto) {
  8542. var eventLimit = this.opt('eventLimit');
  8543. var scrollerHeight;
  8544. // reset all heights to be natural
  8545. unsetScroller(this.scrollerEl);
  8546. uncompensateScroll(this.headRowEl);
  8547. this.dayGrid.removeSegPopover(); // kill the "more" popover if displayed
  8548. // is the event limit a constant level number?
  8549. if (eventLimit && typeof eventLimit === 'number') {
  8550. this.dayGrid.limitRows(eventLimit); // limit the levels first so the height can redistribute after
  8551. }
  8552. scrollerHeight = this.computeScrollerHeight(totalHeight);
  8553. this.setGridHeight(scrollerHeight, isAuto);
  8554. // is the event limit dynamically calculated?
  8555. if (eventLimit && typeof eventLimit !== 'number') {
  8556. this.dayGrid.limitRows(eventLimit); // limit the levels after the grid's row heights have been set
  8557. }
  8558. if (!isAuto && setPotentialScroller(this.scrollerEl, scrollerHeight)) { // using scrollbars?
  8559. compensateScroll(this.headRowEl, getScrollbarWidths(this.scrollerEl));
  8560. // doing the scrollbar compensation might have created text overflow which created more height. redo
  8561. scrollerHeight = this.computeScrollerHeight(totalHeight);
  8562. this.scrollerEl.height(scrollerHeight);
  8563. }
  8564. },
  8565. // Sets the height of just the DayGrid component in this view
  8566. setGridHeight: function(height, isAuto) {
  8567. if (isAuto) {
  8568. undistributeHeight(this.dayGrid.rowEls); // let the rows be their natural height with no expanding
  8569. }
  8570. else {
  8571. distributeHeight(this.dayGrid.rowEls, height, true); // true = compensate for height-hogging rows
  8572. }
  8573. },
  8574. /* Hit Areas
  8575. ------------------------------------------------------------------------------------------------------------------*/
  8576. // forward all hit-related method calls to dayGrid
  8577. prepareHits: function() {
  8578. this.dayGrid.prepareHits();
  8579. },
  8580. releaseHits: function() {
  8581. this.dayGrid.releaseHits();
  8582. },
  8583. queryHit: function(left, top) {
  8584. return this.dayGrid.queryHit(left, top);
  8585. },
  8586. getHitSpan: function(hit) {
  8587. return this.dayGrid.getHitSpan(hit);
  8588. },
  8589. getHitEl: function(hit) {
  8590. return this.dayGrid.getHitEl(hit);
  8591. },
  8592. /* Events
  8593. ------------------------------------------------------------------------------------------------------------------*/
  8594. // Renders the given events onto the view and populates the segments array
  8595. renderEvents: function(events) {
  8596. this.dayGrid.renderEvents(events);
  8597. this.updateHeight(); // must compensate for events that overflow the row
  8598. },
  8599. // Retrieves all segment objects that are rendered in the view
  8600. getEventSegs: function() {
  8601. return this.dayGrid.getEventSegs();
  8602. },
  8603. // Unrenders all event elements and clears internal segment data
  8604. unrenderEvents: function() {
  8605. this.dayGrid.unrenderEvents();
  8606. // we DON'T need to call updateHeight() because:
  8607. // A) a renderEvents() call always happens after this, which will eventually call updateHeight()
  8608. // B) in IE8, this causes a flash whenever events are rerendered
  8609. },
  8610. /* Dragging (for both events and external elements)
  8611. ------------------------------------------------------------------------------------------------------------------*/
  8612. // A returned value of `true` signals that a mock "helper" event has been rendered.
  8613. renderDrag: function(dropLocation, seg) {
  8614. return this.dayGrid.renderDrag(dropLocation, seg);
  8615. },
  8616. unrenderDrag: function() {
  8617. this.dayGrid.unrenderDrag();
  8618. },
  8619. /* Selection
  8620. ------------------------------------------------------------------------------------------------------------------*/
  8621. // Renders a visual indication of a selection
  8622. renderSelection: function(span) {
  8623. this.dayGrid.renderSelection(span);
  8624. },
  8625. // Unrenders a visual indications of a selection
  8626. unrenderSelection: function() {
  8627. this.dayGrid.unrenderSelection();
  8628. }
  8629. });
  8630. // Methods that will customize the rendering behavior of the BasicView's dayGrid
  8631. var basicDayGridMethods = {
  8632. // Generates the HTML that will go before the day-of week header cells
  8633. renderHeadIntroHtml: function() {
  8634. var view = this.view;
  8635. if (view.weekNumbersVisible) {
  8636. return '' +
  8637. '<th class="fc-week-number ' + view.widgetHeaderClass + '" ' + view.weekNumberStyleAttr() + '>' +
  8638. '<span>' + // needed for matchCellWidths
  8639. htmlEscape(view.opt('weekNumberTitle')) +
  8640. '</span>' +
  8641. '</th>';
  8642. }
  8643. return '';
  8644. },
  8645. // Generates the HTML that will go before content-skeleton cells that display the day/week numbers
  8646. renderNumberIntroHtml: function(row) {
  8647. var view = this.view;
  8648. if (view.weekNumbersVisible) {
  8649. return '' +
  8650. '<td class="fc-week-number" ' + view.weekNumberStyleAttr() + '>' +
  8651. '<span>' + // needed for matchCellWidths
  8652. this.getCellDate(row, 0).format('w') +
  8653. '</span>' +
  8654. '</td>';
  8655. }
  8656. return '';
  8657. },
  8658. // Generates the HTML that goes before the day bg cells for each day-row
  8659. renderBgIntroHtml: function() {
  8660. var view = this.view;
  8661. if (view.weekNumbersVisible) {
  8662. return '<td class="fc-week-number ' + view.widgetContentClass + '" ' +
  8663. view.weekNumberStyleAttr() + '></td>';
  8664. }
  8665. return '';
  8666. },
  8667. // Generates the HTML that goes before every other type of row generated by DayGrid.
  8668. // Affects helper-skeleton and highlight-skeleton rows.
  8669. renderIntroHtml: function() {
  8670. var view = this.view;
  8671. if (view.weekNumbersVisible) {
  8672. return '<td class="fc-week-number" ' + view.weekNumberStyleAttr() + '></td>';
  8673. }
  8674. return '';
  8675. }
  8676. };
  8677. ;;
  8678. /* A month view with day cells running in rows (one-per-week) and columns
  8679. ----------------------------------------------------------------------------------------------------------------------*/
  8680. var MonthView = FC.MonthView = BasicView.extend({
  8681. // Produces information about what range to display
  8682. computeRange: function(date) {
  8683. var range = BasicView.prototype.computeRange.call(this, date); // get value from super-method
  8684. var rowCnt;
  8685. // ensure 6 weeks
  8686. if (this.isFixedWeeks()) {
  8687. rowCnt = Math.ceil(range.end.diff(range.start, 'weeks', true)); // could be partial weeks due to hiddenDays
  8688. range.end.add(6 - rowCnt, 'weeks');
  8689. }
  8690. return range;
  8691. },
  8692. // Overrides the default BasicView behavior to have special multi-week auto-height logic
  8693. setGridHeight: function(height, isAuto) {
  8694. isAuto = isAuto || this.opt('weekMode') === 'variable'; // LEGACY: weekMode is deprecated
  8695. // if auto, make the height of each row the height that it would be if there were 6 weeks
  8696. if (isAuto) {
  8697. height *= this.rowCnt / 6;
  8698. }
  8699. distributeHeight(this.dayGrid.rowEls, height, !isAuto); // if auto, don't compensate for height-hogging rows
  8700. },
  8701. isFixedWeeks: function() {
  8702. var weekMode = this.opt('weekMode'); // LEGACY: weekMode is deprecated
  8703. if (weekMode) {
  8704. return weekMode === 'fixed'; // if any other type of weekMode, assume NOT fixed
  8705. }
  8706. return this.opt('fixedWeekCount');
  8707. }
  8708. });
  8709. ;;
  8710. fcViews.basic = {
  8711. 'class': BasicView
  8712. };
  8713. fcViews.basicDay = {
  8714. type: 'basic',
  8715. duration: { days: 1 }
  8716. };
  8717. fcViews.basicWeek = {
  8718. type: 'basic',
  8719. duration: { weeks: 1 }
  8720. };
  8721. fcViews.month = {
  8722. 'class': MonthView,
  8723. duration: { months: 1 }, // important for prev/next
  8724. defaults: {
  8725. fixedWeekCount: true
  8726. }
  8727. };
  8728. ;;
  8729. /* An abstract class for all agenda-related views. Displays one more columns with time slots running vertically.
  8730. ----------------------------------------------------------------------------------------------------------------------*/
  8731. // Is a manager for the TimeGrid subcomponent and possibly the DayGrid subcomponent (if allDaySlot is on).
  8732. // Responsible for managing width/height.
  8733. var AgendaView = FC.AgendaView = View.extend({
  8734. timeGridClass: TimeGrid, // class used to instantiate the timeGrid. subclasses can override
  8735. timeGrid: null, // the main time-grid subcomponent of this view
  8736. dayGridClass: DayGrid, // class used to instantiate the dayGrid. subclasses can override
  8737. dayGrid: null, // the "all-day" subcomponent. if all-day is turned off, this will be null
  8738. axisWidth: null, // the width of the time axis running down the side
  8739. headContainerEl: null, // div that hold's the timeGrid's rendered date header
  8740. noScrollRowEls: null, // set of fake row elements that must compensate when scrollerEl has scrollbars
  8741. // when the time-grid isn't tall enough to occupy the given height, we render an <hr> underneath
  8742. bottomRuleEl: null,
  8743. bottomRuleHeight: null,
  8744. initialize: function() {
  8745. this.timeGrid = this.instantiateTimeGrid();
  8746. if (this.opt('allDaySlot')) { // should we display the "all-day" area?
  8747. this.dayGrid = this.instantiateDayGrid(); // the all-day subcomponent of this view
  8748. }
  8749. },
  8750. // Instantiates the TimeGrid object this view needs. Draws from this.timeGridClass
  8751. instantiateTimeGrid: function() {
  8752. var subclass = this.timeGridClass.extend(agendaTimeGridMethods);
  8753. return new subclass(this);
  8754. },
  8755. // Instantiates the DayGrid object this view might need. Draws from this.dayGridClass
  8756. instantiateDayGrid: function() {
  8757. var subclass = this.dayGridClass.extend(agendaDayGridMethods);
  8758. return new subclass(this);
  8759. },
  8760. /* Rendering
  8761. ------------------------------------------------------------------------------------------------------------------*/
  8762. // Sets the display range and computes all necessary dates
  8763. setRange: function(range) {
  8764. View.prototype.setRange.call(this, range); // call the super-method
  8765. this.timeGrid.setRange(range);
  8766. if (this.dayGrid) {
  8767. this.dayGrid.setRange(range);
  8768. }
  8769. },
  8770. // Renders the view into `this.el`, which has already been assigned
  8771. renderDates: function() {
  8772. this.el.addClass('fc-agenda-view').html(this.renderSkeletonHtml());
  8773. this.renderHead();
  8774. // the element that wraps the time-grid that will probably scroll
  8775. this.scrollerEl = this.el.find('.fc-time-grid-container');
  8776. this.timeGrid.setElement(this.el.find('.fc-time-grid'));
  8777. this.timeGrid.renderDates();
  8778. // the <hr> that sometimes displays under the time-grid
  8779. this.bottomRuleEl = jQuery('<hr class="fc-divider ' + this.widgetHeaderClass + '"/>')
  8780. .appendTo(this.timeGrid.el); // inject it into the time-grid
  8781. if (this.dayGrid) {
  8782. this.dayGrid.setElement(this.el.find('.fc-day-grid'));
  8783. this.dayGrid.renderDates();
  8784. // have the day-grid extend it's coordinate area over the <hr> dividing the two grids
  8785. this.dayGrid.bottomCoordPadding = this.dayGrid.el.next('hr').outerHeight();
  8786. }
  8787. this.noScrollRowEls = this.el.find('.fc-row:not(.fc-scroller *)'); // fake rows not within the scroller
  8788. },
  8789. // render the day-of-week headers
  8790. renderHead: function() {
  8791. this.headContainerEl =
  8792. this.el.find('.fc-head-container')
  8793. .html(this.timeGrid.renderHeadHtml());
  8794. },
  8795. // Unrenders the content of the view. Since we haven't separated skeleton rendering from date rendering,
  8796. // always completely kill each grid's rendering.
  8797. unrenderDates: function() {
  8798. this.timeGrid.unrenderDates();
  8799. this.timeGrid.removeElement();
  8800. if (this.dayGrid) {
  8801. this.dayGrid.unrenderDates();
  8802. this.dayGrid.removeElement();
  8803. }
  8804. },
  8805. // Builds the HTML skeleton for the view.
  8806. // The day-grid and time-grid components will render inside containers defined by this HTML.
  8807. renderSkeletonHtml: function() {
  8808. return '' +
  8809. '<table>' +
  8810. '<thead class="fc-head">' +
  8811. '<tr>' +
  8812. '<td class="fc-head-container ' + this.widgetHeaderClass + '"></td>' +
  8813. '</tr>' +
  8814. '</thead>' +
  8815. '<tbody class="fc-body">' +
  8816. '<tr>' +
  8817. '<td class="' + this.widgetContentClass + '">' +
  8818. (this.dayGrid ?
  8819. '<div class="fc-day-grid"/>' +
  8820. '<hr class="fc-divider ' + this.widgetHeaderClass + '"/>' :
  8821. ''
  8822. ) +
  8823. '<div class="fc-time-grid-container">' +
  8824. '<div class="fc-time-grid"/>' +
  8825. '</div>' +
  8826. '</td>' +
  8827. '</tr>' +
  8828. '</tbody>' +
  8829. '</table>';
  8830. },
  8831. // Generates an HTML attribute string for setting the width of the axis, if it is known
  8832. axisStyleAttr: function() {
  8833. if (this.axisWidth !== null) {
  8834. return 'style="width:' + this.axisWidth + 'px"';
  8835. }
  8836. return '';
  8837. },
  8838. /* Business Hours
  8839. ------------------------------------------------------------------------------------------------------------------*/
  8840. renderBusinessHours: function() {
  8841. this.timeGrid.renderBusinessHours();
  8842. if (this.dayGrid) {
  8843. this.dayGrid.renderBusinessHours();
  8844. }
  8845. },
  8846. unrenderBusinessHours: function() {
  8847. this.timeGrid.unrenderBusinessHours();
  8848. if (this.dayGrid) {
  8849. this.dayGrid.unrenderBusinessHours();
  8850. }
  8851. },
  8852. /* Now Indicator
  8853. ------------------------------------------------------------------------------------------------------------------*/
  8854. getNowIndicatorUnit: function() {
  8855. return this.timeGrid.getNowIndicatorUnit();
  8856. },
  8857. renderNowIndicator: function(date) {
  8858. this.timeGrid.renderNowIndicator(date);
  8859. },
  8860. unrenderNowIndicator: function() {
  8861. this.timeGrid.unrenderNowIndicator();
  8862. },
  8863. /* Dimensions
  8864. ------------------------------------------------------------------------------------------------------------------*/
  8865. updateSize: function(isResize) {
  8866. this.timeGrid.updateSize(isResize);
  8867. View.prototype.updateSize.call(this, isResize); // call the super-method
  8868. },
  8869. // Refreshes the horizontal dimensions of the view
  8870. updateWidth: function() {
  8871. // make all axis cells line up, and record the width so newly created axis cells will have it
  8872. this.axisWidth = matchCellWidths(this.el.find('.fc-axis'));
  8873. },
  8874. // Adjusts the vertical dimensions of the view to the specified values
  8875. setHeight: function(totalHeight, isAuto) {
  8876. var eventLimit;
  8877. var scrollerHeight;
  8878. if (this.bottomRuleHeight === null) {
  8879. // calculate the height of the rule the very first time
  8880. this.bottomRuleHeight = this.bottomRuleEl.outerHeight();
  8881. }
  8882. this.bottomRuleEl.hide(); // .show() will be called later if this <hr> is necessary
  8883. // reset all dimensions back to the original state
  8884. this.scrollerEl.css('overflow', '');
  8885. unsetScroller(this.scrollerEl);
  8886. uncompensateScroll(this.noScrollRowEls);
  8887. // limit number of events in the all-day area
  8888. if (this.dayGrid) {
  8889. this.dayGrid.removeSegPopover(); // kill the "more" popover if displayed
  8890. eventLimit = this.opt('eventLimit');
  8891. if (eventLimit && typeof eventLimit !== 'number') {
  8892. eventLimit = AGENDA_ALL_DAY_EVENT_LIMIT; // make sure "auto" goes to a real number
  8893. }
  8894. if (eventLimit) {
  8895. this.dayGrid.limitRows(eventLimit);
  8896. }
  8897. }
  8898. if (!isAuto) { // should we force dimensions of the scroll container, or let the contents be natural height?
  8899. scrollerHeight = this.computeScrollerHeight(totalHeight);
  8900. if (setPotentialScroller(this.scrollerEl, scrollerHeight)) { // using scrollbars?
  8901. // make the all-day and header rows lines up
  8902. compensateScroll(this.noScrollRowEls, getScrollbarWidths(this.scrollerEl));
  8903. // the scrollbar compensation might have changed text flow, which might affect height, so recalculate
  8904. // and reapply the desired height to the scroller.
  8905. scrollerHeight = this.computeScrollerHeight(totalHeight);
  8906. this.scrollerEl.height(scrollerHeight);
  8907. }
  8908. else { // no scrollbars
  8909. // still, force a height and display the bottom rule (marks the end of day)
  8910. this.scrollerEl.height(scrollerHeight).css('overflow', 'hidden'); // in case <hr> goes outside
  8911. this.bottomRuleEl.show();
  8912. }
  8913. }
  8914. },
  8915. // Computes the initial pre-configured scroll state prior to allowing the user to change it
  8916. computeInitialScroll: function() {
  8917. var scrollTime = moment.duration(this.opt('scrollTime'));
  8918. var top = this.timeGrid.computeTimeTop(scrollTime);
  8919. // zoom can give weird floating-point values. rather scroll a little bit further
  8920. top = Math.ceil(top);
  8921. if (top) {
  8922. top++; // to overcome top border that slots beyond the first have. looks better
  8923. }
  8924. return top;
  8925. },
  8926. /* Hit Areas
  8927. ------------------------------------------------------------------------------------------------------------------*/
  8928. // forward all hit-related method calls to the grids (dayGrid might not be defined)
  8929. prepareHits: function() {
  8930. this.timeGrid.prepareHits();
  8931. if (this.dayGrid) {
  8932. this.dayGrid.prepareHits();
  8933. }
  8934. },
  8935. releaseHits: function() {
  8936. this.timeGrid.releaseHits();
  8937. if (this.dayGrid) {
  8938. this.dayGrid.releaseHits();
  8939. }
  8940. },
  8941. queryHit: function(left, top) {
  8942. var hit = this.timeGrid.queryHit(left, top);
  8943. if (!hit && this.dayGrid) {
  8944. hit = this.dayGrid.queryHit(left, top);
  8945. }
  8946. return hit;
  8947. },
  8948. getHitSpan: function(hit) {
  8949. // TODO: hit.component is set as a hack to identify where the hit came from
  8950. return hit.component.getHitSpan(hit);
  8951. },
  8952. getHitEl: function(hit) {
  8953. // TODO: hit.component is set as a hack to identify where the hit came from
  8954. return hit.component.getHitEl(hit);
  8955. },
  8956. /* Events
  8957. ------------------------------------------------------------------------------------------------------------------*/
  8958. // Renders events onto the view and populates the View's segment array
  8959. renderEvents: function(events) {
  8960. var dayEvents = [];
  8961. var timedEvents = [];
  8962. var daySegs = [];
  8963. var timedSegs;
  8964. var i;
  8965. // separate the events into all-day and timed
  8966. for (i = 0; i < events.length; i++) {
  8967. if (events[i].allDay) {
  8968. dayEvents.push(events[i]);
  8969. }
  8970. else {
  8971. timedEvents.push(events[i]);
  8972. }
  8973. }
  8974. // render the events in the subcomponents
  8975. timedSegs = this.timeGrid.renderEvents(timedEvents);
  8976. if (this.dayGrid) {
  8977. daySegs = this.dayGrid.renderEvents(dayEvents);
  8978. }
  8979. // the all-day area is flexible and might have a lot of events, so shift the height
  8980. this.updateHeight();
  8981. },
  8982. // Retrieves all segment objects that are rendered in the view
  8983. getEventSegs: function() {
  8984. return this.timeGrid.getEventSegs().concat(
  8985. this.dayGrid ? this.dayGrid.getEventSegs() : []
  8986. );
  8987. },
  8988. // Unrenders all event elements and clears internal segment data
  8989. unrenderEvents: function() {
  8990. // unrender the events in the subcomponents
  8991. this.timeGrid.unrenderEvents();
  8992. if (this.dayGrid) {
  8993. this.dayGrid.unrenderEvents();
  8994. }
  8995. // we DON'T need to call updateHeight() because:
  8996. // A) a renderEvents() call always happens after this, which will eventually call updateHeight()
  8997. // B) in IE8, this causes a flash whenever events are rerendered
  8998. },
  8999. /* Dragging (for events and external elements)
  9000. ------------------------------------------------------------------------------------------------------------------*/
  9001. // A returned value of `true` signals that a mock "helper" event has been rendered.
  9002. renderDrag: function(dropLocation, seg) {
  9003. if (dropLocation.start.hasTime()) {
  9004. return this.timeGrid.renderDrag(dropLocation, seg);
  9005. }
  9006. else if (this.dayGrid) {
  9007. return this.dayGrid.renderDrag(dropLocation, seg);
  9008. }
  9009. },
  9010. unrenderDrag: function() {
  9011. this.timeGrid.unrenderDrag();
  9012. if (this.dayGrid) {
  9013. this.dayGrid.unrenderDrag();
  9014. }
  9015. },
  9016. /* Selection
  9017. ------------------------------------------------------------------------------------------------------------------*/
  9018. // Renders a visual indication of a selection
  9019. renderSelection: function(span) {
  9020. if (span.start.hasTime() || span.end.hasTime()) {
  9021. this.timeGrid.renderSelection(span);
  9022. }
  9023. else if (this.dayGrid) {
  9024. this.dayGrid.renderSelection(span);
  9025. }
  9026. },
  9027. // Unrenders a visual indications of a selection
  9028. unrenderSelection: function() {
  9029. this.timeGrid.unrenderSelection();
  9030. if (this.dayGrid) {
  9031. this.dayGrid.unrenderSelection();
  9032. }
  9033. }
  9034. });
  9035. // Methods that will customize the rendering behavior of the AgendaView's timeGrid
  9036. // TODO: move into TimeGrid
  9037. var agendaTimeGridMethods = {
  9038. // Generates the HTML that will go before the day-of week header cells
  9039. renderHeadIntroHtml: function() {
  9040. var view = this.view;
  9041. var weekText;
  9042. if (view.opt('weekNumbers')) {
  9043. weekText = this.start.format(view.opt('smallWeekFormat'));
  9044. return '' +
  9045. '<th class="fc-axis fc-week-number ' + view.widgetHeaderClass + '" ' + view.axisStyleAttr() + '>' +
  9046. '<span>' + // needed for matchCellWidths
  9047. htmlEscape(weekText) +
  9048. '</span>' +
  9049. '</th>';
  9050. }
  9051. else {
  9052. return '<th class="fc-axis ' + view.widgetHeaderClass + '" ' + view.axisStyleAttr() + '></th>';
  9053. }
  9054. },
  9055. // Generates the HTML that goes before the bg of the TimeGrid slot area. Long vertical column.
  9056. renderBgIntroHtml: function() {
  9057. var view = this.view;
  9058. return '<td class="fc-axis ' + view.widgetContentClass + '" ' + view.axisStyleAttr() + '></td>';
  9059. },
  9060. // Generates the HTML that goes before all other types of cells.
  9061. // Affects content-skeleton, helper-skeleton, highlight-skeleton for both the time-grid and day-grid.
  9062. renderIntroHtml: function() {
  9063. var view = this.view;
  9064. return '<td class="fc-axis" ' + view.axisStyleAttr() + '></td>';
  9065. }
  9066. };
  9067. // Methods that will customize the rendering behavior of the AgendaView's dayGrid
  9068. var agendaDayGridMethods = {
  9069. // Generates the HTML that goes before the all-day cells
  9070. renderBgIntroHtml: function() {
  9071. var view = this.view;
  9072. return '' +
  9073. '<td class="fc-axis ' + view.widgetContentClass + '" ' + view.axisStyleAttr() + '>' +
  9074. '<span>' + // needed for matchCellWidths
  9075. (view.opt('allDayHtml') || htmlEscape(view.opt('allDayText'))) +
  9076. '</span>' +
  9077. '</td>';
  9078. },
  9079. // Generates the HTML that goes before all other types of cells.
  9080. // Affects content-skeleton, helper-skeleton, highlight-skeleton for both the time-grid and day-grid.
  9081. renderIntroHtml: function() {
  9082. var view = this.view;
  9083. return '<td class="fc-axis" ' + view.axisStyleAttr() + '></td>';
  9084. }
  9085. };
  9086. ;;
  9087. var AGENDA_ALL_DAY_EVENT_LIMIT = 5;
  9088. // potential nice values for the slot-duration and interval-duration
  9089. // from largest to smallest
  9090. var AGENDA_STOCK_SUB_DURATIONS = [
  9091. { hours: 1 },
  9092. { minutes: 30 },
  9093. { minutes: 15 },
  9094. { seconds: 30 },
  9095. { seconds: 15 }
  9096. ];
  9097. fcViews.agenda = {
  9098. 'class': AgendaView,
  9099. defaults: {
  9100. allDaySlot: true,
  9101. allDayText: 'all-day',
  9102. slotDuration: '00:30:00',
  9103. minTime: '00:00:00',
  9104. maxTime: '24:00:00',
  9105. slotEventOverlap: true // a bad name. confused with overlap/constraint system
  9106. }
  9107. };
  9108. fcViews.agendaDay = {
  9109. type: 'agenda',
  9110. duration: { days: 1 }
  9111. };
  9112. fcViews.agendaWeek = {
  9113. type: 'agenda',
  9114. duration: { weeks: 1 }
  9115. };
  9116. ;;
  9117. return FC; // export for Node/CommonJS
  9118. });