clndr.js 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580
  1. /**
  2. * ~ CLNDR v1.4.0 ~
  3. * ==============================================
  4. * https://github.com/kylestetz/CLNDR
  5. * ==============================================
  6. * Created by kyle stetz (github.com/kylestetz)
  7. * & available under the MIT license
  8. * http://opensource.org/licenses/mit-license.php
  9. * ==============================================
  10. *
  11. * This is the fully-commented development version of CLNDR.
  12. * For the production version, check out clndr.min.js
  13. * at https://github.com/kylestetz/CLNDR
  14. *
  15. * This work is based on the
  16. * jQuery lightweight plugin boilerplate
  17. * Original author: @ajpiano
  18. * Further changes, comments: @addyosmani
  19. * Licensed under the MIT license
  20. */
  21. (function (factory) {
  22. // Multiple loading methods are supported depending on
  23. // what is available globally. While moment is loaded
  24. // here, the instance can be passed in at config time.
  25. if (typeof define === 'function' && define.amd) {
  26. // AMD. Register as an anonymous module.
  27. define(['jquery', 'moment'], factory);
  28. } else if (typeof exports === 'object') {
  29. // Node/CommonJS
  30. factory(require('jquery'), require('moment'));
  31. } else {
  32. // Browser globals
  33. factory(jQuery, moment);
  34. }
  35. }(function ($, moment) {
  36. // Namespace
  37. var pluginName = 'clndr';
  38. // This is the default calendar template. This can be overridden.
  39. var clndrTemplate =
  40. "<div class='clndr-controls'>" +
  41. "<div class='clndr-control-button'>" +
  42. "<span class='clndr-previous-button'>previous</span>" +
  43. "</div>" +
  44. "<div class='month'><%= month %> <%= year %></div>" +
  45. "<div class='clndr-control-button rightalign'>" +
  46. "<span class='clndr-next-button'>next</span>" +
  47. "</div>" +
  48. "</div>" +
  49. "<table class='clndr-table' border='0' cellspacing='0' cellpadding='0'>" +
  50. "<thead>" +
  51. "<tr class='header-days'>" +
  52. "<% for(var i = 0; i < daysOfTheWeek.length; i++) { %>" +
  53. "<td class='header-day'><%= daysOfTheWeek[i] %></td>" +
  54. "<% } %>" +
  55. "</tr>" +
  56. "</thead>" +
  57. "<tbody>" +
  58. "<% for(var i = 0; i < numberOfRows; i++){ %>" +
  59. "<tr>" +
  60. "<% for(var j = 0; j < 7; j++){ %>" +
  61. "<% var d = j + i * 7; %>" +
  62. "<td class='<%= days[d].classes %>'>" +
  63. "<div class='day-contents'><%= days[d].day %></div>" +
  64. "</td>" +
  65. "<% } %>" +
  66. "</tr>" +
  67. "<% } %>" +
  68. "</tbody>" +
  69. "</table>";
  70. // Defaults used throughout the application, see docs.
  71. var defaults = {
  72. events: [],
  73. ready: null,
  74. extras: null,
  75. render: null,
  76. moment: null,
  77. weekOffset: 0,
  78. constraints: null,
  79. forceSixRows: null,
  80. selectedDate: null,
  81. doneRendering: null,
  82. daysOfTheWeek: null,
  83. multiDayEvents: null,
  84. startWithMonth: null,
  85. dateParameter: 'date',
  86. template: clndrTemplate,
  87. showAdjacentMonths: true,
  88. trackSelectedDate: true,
  89. adjacentDaysChangeMonth: false,
  90. ignoreInactiveDaysInSelection: null,
  91. lengthOfTime: {
  92. days: null,
  93. interval: 1,
  94. months: null
  95. },
  96. clickEvents: {
  97. click: null,
  98. today: null,
  99. nextYear: null,
  100. nextMonth: null,
  101. nextInterval: null,
  102. previousYear: null,
  103. onYearChange: null,
  104. previousMonth: null,
  105. onMonthChange: null,
  106. previousInterval: null,
  107. onIntervalChange: null
  108. },
  109. targets: {
  110. day: 'day',
  111. empty: 'empty',
  112. nextButton: 'clndr-next-button',
  113. todayButton: 'clndr-today-button',
  114. previousButton: 'clndr-previous-button',
  115. nextYearButton: 'clndr-next-year-button',
  116. previousYearButton: 'clndr-previous-year-button'
  117. },
  118. classes: {
  119. past: "past",
  120. today: "today",
  121. event: "event",
  122. inactive: "inactive",
  123. selected: "selected",
  124. lastMonth: "last-month",
  125. nextMonth: "next-month",
  126. adjacentMonth: "adjacent-month"
  127. },
  128. };
  129. /**
  130. * The actual plugin constructor.
  131. * Parses the events and lengthOfTime options to build a calendar of day
  132. * objects containing event information from the events array.
  133. */
  134. function Clndr(element, options) {
  135. this.element = element;
  136. // Merge the default options with user-provided options
  137. this.options = $.extend(true, {}, defaults, options);
  138. // Check if moment was passed in as a dependency
  139. if (this.options.moment) {
  140. moment = this.options.moment;
  141. }
  142. // Boolean values used to log if any contraints are met
  143. this.constraints = {
  144. next: true,
  145. today: true,
  146. previous: true,
  147. nextYear: true,
  148. previousYear: true
  149. };
  150. // If there are events, we should run them through our
  151. // addMomentObjectToEvents function which will add a date object that
  152. // we can use to make life easier. This is only necessarywhen events
  153. // are provided on instantiation, since our setEvents function uses
  154. // addMomentObjectToEvents.
  155. if (this.options.events.length) {
  156. if (this.options.multiDayEvents) {
  157. this.options.events =
  158. this.addMultiDayMomentObjectsToEvents(this.options.events);
  159. } else {
  160. this.options.events =
  161. this.addMomentObjectToEvents(this.options.events);
  162. }
  163. }
  164. // This used to be a place where we'd figure out the current month,
  165. // but since we want to open up support for arbitrary lengths of time
  166. // we're going to store the current range in addition to the current
  167. // month.
  168. if (this.options.lengthOfTime.months || this.options.lengthOfTime.days) {
  169. // We want to establish intervalStart and intervalEnd, which will
  170. // keep track of our boundaries. Let's look at the possibilities...
  171. if (this.options.lengthOfTime.months) {
  172. // Gonna go right ahead and annihilate any chance for bugs here
  173. this.options.lengthOfTime.days = null;
  174. // The length is specified in months. Is there a start date?
  175. if (this.options.lengthOfTime.startDate) {
  176. this.intervalStart =
  177. moment(this.options.lengthOfTime.startDate)
  178. .startOf('month');
  179. } else if (this.options.startWithMonth) {
  180. this.intervalStart =
  181. moment(this.options.startWithMonth)
  182. .startOf('month');
  183. } else {
  184. this.intervalStart = moment().startOf('month');
  185. }
  186. // Subtract a day so that we are at the end of the interval. We
  187. // always want intervalEnd to be inclusive.
  188. this.intervalEnd = moment(this.intervalStart)
  189. .add(this.options.lengthOfTime.months, 'months')
  190. .subtract(1, 'days');
  191. this.month = this.intervalStart.clone();
  192. } else if (this.options.lengthOfTime.days) {
  193. // The length is specified in days. Start date?
  194. if (this.options.lengthOfTime.startDate) {
  195. this.intervalStart =
  196. moment(this.options.lengthOfTime.startDate)
  197. .startOf('day');
  198. } else {
  199. this.intervalStart = moment().weekday(0).startOf('day');
  200. }
  201. this.intervalEnd = moment(this.intervalStart)
  202. .add(this.options.lengthOfTime.days - 1, 'days')
  203. .endOf('day');
  204. this.month = this.intervalStart.clone();
  205. }
  206. // No length of time specified so we're going to default into using the
  207. // current month as the time period.
  208. } else {
  209. this.month = moment().startOf('month');
  210. this.intervalStart = moment(this.month);
  211. this.intervalEnd = moment(this.month).endOf('month');
  212. }
  213. if (this.options.startWithMonth) {
  214. this.month = moment(this.options.startWithMonth).startOf('month');
  215. this.intervalStart = moment(this.month);
  216. this.intervalEnd = moment(this.month).endOf('month');
  217. }
  218. // If we've got constraints set, make sure the interval is within them.
  219. if (this.options.constraints) {
  220. // First check if the start date exists & is later than now.
  221. if (this.options.constraints.startDate) {
  222. var startMoment = moment(this.options.constraints.startDate);
  223. if (this.intervalStart.isBefore(startMoment, 'month')) {
  224. // Try to preserve the date by moving only the month...
  225. this.intervalStart
  226. .set('month', startMoment.month())
  227. .set('year', startMoment.year());
  228. this.month
  229. .set('month', startMoment.month())
  230. .set('year', startMoment.year());
  231. }
  232. }
  233. // Make sure the intervalEnd is before the endDate
  234. if (this.options.constraints.endDate) {
  235. var endMoment = moment(this.options.constraints.endDate);
  236. if (this.intervalEnd.isAfter(endMoment, 'month')) {
  237. this.intervalEnd
  238. .set('month', endMoment.month())
  239. .set('year', endMoment.year());
  240. this.month
  241. .set('month', endMoment.month())
  242. .set('year', endMoment.year());
  243. }
  244. }
  245. }
  246. this._defaults = defaults;
  247. this._name = pluginName;
  248. // Some first-time initialization -> day of the week offset, template
  249. // compiling, making and storing some elements we'll need later, and
  250. // event handling for the controller.
  251. this.init();
  252. }
  253. /**
  254. * Calendar initialization.
  255. * Sets up the days of the week, the rendering function, binds all of the
  256. * events to the rendered calendar, and then stores the node locally.
  257. */
  258. Clndr.prototype.init = function () {
  259. // Create the days of the week using moment's current language setting
  260. this.daysOfTheWeek = this.options.daysOfTheWeek || [];
  261. if (!this.options.daysOfTheWeek) {
  262. this.daysOfTheWeek = [];
  263. for (var i = 0; i < 7; i++) {
  264. this.daysOfTheWeek.push(
  265. moment().weekday(i).format('dd').charAt(0));
  266. }
  267. }
  268. // Shuffle the week if there's an offset
  269. if (this.options.weekOffset) {
  270. this.daysOfTheWeek = this.shiftWeekdayLabels(this.options.weekOffset);
  271. }
  272. // Quick and dirty test to make sure rendering is possible.
  273. if (!$.isFunction(this.options.render)) {
  274. this.options.render = null;
  275. if (typeof _ === 'undefined') {
  276. throw new Error(
  277. "Underscore was not found. Please include underscore.js " +
  278. "OR provide a custom render function.");
  279. } else {
  280. // We're just going ahead and using underscore here if no
  281. // render method has been supplied.
  282. this.compiledClndrTemplate = _.template(this.options.template);
  283. }
  284. }
  285. // Create the parent element that will hold the plugin and save it
  286. // for later
  287. $(this.element).html("<div class='clndr'></div>");
  288. this.calendarContainer = $('.clndr', this.element);
  289. // Attach event handlers for clicks on buttons/cells
  290. this.bindEvents();
  291. // Do a normal render of the calendar template
  292. this.render();
  293. // If a ready callback has been provided, call it.
  294. if (this.options.ready) {
  295. this.options.ready.apply(this, []);
  296. }
  297. };
  298. Clndr.prototype.shiftWeekdayLabels = function (offset) {
  299. var days = this.daysOfTheWeek;
  300. for (var i = 0; i < offset; i++) {
  301. days.push(days.shift());
  302. }
  303. return days;
  304. };
  305. /**
  306. * This is where the magic happens. Given a starting date and ending date,
  307. * an array of calendarDay objects is constructed that contains appropriate
  308. * events and classes depending on the circumstance.
  309. */
  310. Clndr.prototype.createDaysObject = function (startDate, endDate) {
  311. // This array will hold numbers for the entire grid (even the blank
  312. // spaces).
  313. var daysArray = [],
  314. date = startDate.clone(),
  315. lengthOfInterval = endDate.diff(startDate, 'days'),
  316. startOfLastMonth, endOfLastMonth, startOfNextMonth,
  317. endOfNextMonth, diff, dateIterator;
  318. // This is a helper object so that days can resolve their classes
  319. // correctly. Don't use it for anything please.
  320. this._currentIntervalStart = startDate.clone();
  321. // Filter the events list (if it exists) to events that are happening
  322. // last month, this month and next month (within the current grid view).
  323. this.eventsLastMonth = [];
  324. this.eventsNextMonth = [];
  325. this.eventsThisInterval = [];
  326. // Event parsing
  327. if (this.options.events.length) {
  328. // Here are the only two cases where we don't get an event in our
  329. // interval:
  330. // startDate | endDate | e.start | e.end
  331. // e.start | e.end | startDate | endDate
  332. this.eventsThisInterval = $(this.options.events).filter(
  333. function () {
  334. var afterEnd = this._clndrStartDateObject.isAfter(endDate),
  335. beforeStart = this._clndrEndDateObject.isBefore(startDate);
  336. if (beforeStart || afterEnd) {
  337. return false;
  338. } else {
  339. return true;
  340. }
  341. }).toArray();
  342. if (this.options.showAdjacentMonths) {
  343. startOfLastMonth = startDate.clone()
  344. .subtract(1, 'months')
  345. .startOf('month');
  346. endOfLastMonth = startOfLastMonth.clone().endOf('month');
  347. startOfNextMonth = endDate.clone()
  348. .add(1, 'months')
  349. .startOf('month');
  350. endOfNextMonth = startOfNextMonth.clone().endOf('month');
  351. this.eventsLastMonth = $(this.options.events).filter(
  352. function () {
  353. var beforeStart = this._clndrEndDateObject
  354. .isBefore(startOfLastMonth);
  355. var afterEnd = this._clndrStartDateObject
  356. .isAfter(endOfLastMonth);
  357. if (beforeStart || afterEnd) {
  358. return false;
  359. } else {
  360. return true;
  361. }
  362. }).toArray();
  363. this.eventsNextMonth = $(this.options.events).filter(
  364. function () {
  365. var beforeStart = this._clndrEndDateObject
  366. .isBefore(startOfNextMonth);
  367. var afterEnd = this._clndrStartDateObject
  368. .isAfter(endOfNextMonth);
  369. if (beforeStart || afterEnd) {
  370. return false;
  371. } else {
  372. return true;
  373. }
  374. }).toArray();
  375. }
  376. }
  377. // If diff is greater than 0, we'll have to fill in last days of the
  378. // previous month to account for the empty boxes in the grid. We also
  379. // need to take into account the weekOffset parameter. None of this
  380. // needs to happen if the interval is being specified in days rather
  381. // than months.
  382. if (!this.options.lengthOfTime.days) {
  383. diff = date.weekday() - this.options.weekOffset;
  384. if (diff < 0) {
  385. diff += 7;
  386. }
  387. if (this.options.showAdjacentMonths) {
  388. for (var i = 0; i < diff; i++) {
  389. var day = moment([
  390. startDate.year(),
  391. startDate.month(),
  392. i - diff + 1
  393. ]);
  394. daysArray.push(
  395. this.createDayObject(
  396. day,
  397. this.eventsLastMonth
  398. ));
  399. }
  400. } else {
  401. for (var i = 0; i < diff; i++) {
  402. daysArray.push(
  403. this.calendarDay({
  404. classes: this.options.targets.empty +
  405. " " + this.options.classes.lastMonth
  406. }));
  407. }
  408. }
  409. }
  410. // Now we push all of the days in the interval
  411. dateIterator = startDate.clone();
  412. while (dateIterator.isBefore(endDate) || dateIterator.isSame(endDate, 'day')) {
  413. daysArray.push(
  414. this.createDayObject(
  415. dateIterator.clone(),
  416. this.eventsThisInterval
  417. ));
  418. dateIterator.add(1, 'days');
  419. }
  420. // ...and if there are any trailing blank boxes, fill those in with the
  421. // next month first days. Again, we can ignore this if the interval is
  422. // specified in days.
  423. if (!this.options.lengthOfTime.days) {
  424. while (daysArray.length % 7 !== 0) {
  425. if (this.options.showAdjacentMonths) {
  426. daysArray.push(
  427. this.createDayObject(
  428. dateIterator.clone(),
  429. this.eventsNextMonth
  430. ));
  431. } else {
  432. daysArray.push(
  433. this.calendarDay({
  434. classes: this.options.targets.empty + " " +
  435. this.options.classes.nextMonth
  436. }));
  437. }
  438. dateIterator.add(1, 'days');
  439. }
  440. }
  441. // If we want to force six rows of calendar, now's our Last Chance to
  442. // add another row. If the 42 seems explicit it's because we're
  443. // creating a 7-row grid and 6 rows of 7 is always 42!
  444. if (this.options.forceSixRows && daysArray.length !== 42) {
  445. while (daysArray.length < 42) {
  446. if (this.options.showAdjacentMonths) {
  447. daysArray.push(
  448. this.createDayObject(
  449. dateIterator.clone(),
  450. this.eventsNextMonth
  451. ));
  452. dateIterator.add(1, 'days');
  453. } else {
  454. daysArray.push(
  455. this.calendarDay({
  456. classes: this.options.targets.empty + " " +
  457. this.options.classes.nextMonth
  458. }));
  459. }
  460. }
  461. }
  462. return daysArray;
  463. };
  464. Clndr.prototype.createDayObject = function (day, monthEvents) {
  465. var j = 0,
  466. self = this,
  467. now = moment(),
  468. eventsToday = [],
  469. extraClasses = "",
  470. properties = {
  471. isToday: false,
  472. isInactive: false,
  473. isAdjacentMonth: false
  474. },
  475. startMoment, endMoment, selectedMoment;
  476. // Validate moment date
  477. if (!day.isValid() && day.hasOwnProperty('_d') && day._d != undefined) {
  478. day = moment(day._d);
  479. }
  480. for (j; j < monthEvents.length; j++) {
  481. // Keep in mind that the events here already passed the month/year
  482. // test. Now all we have to compare is the moment.date(), which
  483. // returns the day of the month.
  484. var start = monthEvents[j]._clndrStartDateObject,
  485. end = monthEvents[j]._clndrEndDateObject;
  486. // If today is the same day as start or is after the start, and
  487. // if today is the same day as the end or before the end ...
  488. // woohoo semantics!
  489. if ((day.isSame(start, 'day') || day.isAfter(start, 'day'))
  490. && (day.isSame(end, 'day') || day.isBefore(end, 'day'))) {
  491. eventsToday.push(monthEvents[j]);
  492. }
  493. }
  494. if (now.format("YYYY-MM-DD") == day.format("YYYY-MM-DD")) {
  495. extraClasses += (" " + this.options.classes.today);
  496. properties.isToday = true;
  497. }
  498. if (day.isBefore(now, 'day')) {
  499. extraClasses += (" " + this.options.classes.past);
  500. }
  501. if (eventsToday.length) {
  502. extraClasses += (" " + this.options.classes.event);
  503. }
  504. if (!this.options.lengthOfTime.days) {
  505. if (this._currentIntervalStart.month() > day.month()) {
  506. extraClasses += (" " + this.options.classes.adjacentMonth);
  507. properties.isAdjacentMonth = true;
  508. this._currentIntervalStart.year() === day.year()
  509. ? extraClasses += (" " + this.options.classes.lastMonth)
  510. : extraClasses += (" " + this.options.classes.nextMonth);
  511. } else if (this._currentIntervalStart.month() < day.month()) {
  512. extraClasses += (" " + this.options.classes.adjacentMonth);
  513. properties.isAdjacentMonth = true;
  514. this._currentIntervalStart.year() === day.year()
  515. ? extraClasses += (" " + this.options.classes.nextMonth)
  516. : extraClasses += (" " + this.options.classes.lastMonth);
  517. }
  518. }
  519. // If there are constraints, we need to add the inactive class to the
  520. // days outside of them
  521. if (this.options.constraints) {
  522. endMoment = moment(this.options.constraints.endDate);
  523. startMoment = moment(this.options.constraints.startDate);
  524. if (this.options.constraints.startDate && day.isBefore(startMoment)) {
  525. extraClasses += (" " + this.options.classes.inactive);
  526. properties.isInactive = true;
  527. }
  528. if (this.options.constraints.endDate && day.isAfter(endMoment)) {
  529. extraClasses += (" " + this.options.classes.inactive);
  530. properties.isInactive = true;
  531. }
  532. }
  533. // Validate moment date
  534. if (!day.isValid() && day.hasOwnProperty('_d') && day._d != undefined) {
  535. day = moment(day._d);
  536. }
  537. // Check whether the day is "selected"
  538. selectedMoment = moment(this.options.selectedDate);
  539. if (this.options.selectedDate && day.isSame(selectedMoment, 'day')) {
  540. extraClasses += (" " + this.options.classes.selected);
  541. }
  542. // We're moving away from using IDs in favor of classes, since when
  543. // using multiple calendars on a page we are technically violating the
  544. // uniqueness of IDs.
  545. extraClasses += " calendar-day-" + day.format("YYYY-MM-DD");
  546. // Day of week
  547. extraClasses += " calendar-dow-" + day.weekday();
  548. return this.calendarDay({
  549. date: day,
  550. day: day.date(),
  551. events: eventsToday,
  552. properties: properties,
  553. classes: this.options.targets.day + extraClasses
  554. });
  555. };
  556. Clndr.prototype.render = function () {
  557. // Get rid of the previous set of calendar parts. This should handle garbage
  558. // collection according to jQuery's docs:
  559. // http://api.jquery.com/empty/
  560. // To avoid memory leaks, jQuery removes other constructs such as
  561. // data and event handlers from the child elements before removing
  562. // the elements themselves.
  563. var data = {},
  564. end = null,
  565. start = null,
  566. oneYearFromEnd = this.intervalEnd.clone().add(1, 'years'),
  567. oneYearAgo = this.intervalStart.clone().subtract(1, 'years'),
  568. days, months, currentMonth, eventsThisInterval,
  569. numberOfRows;
  570. this.calendarContainer.empty();
  571. if (this.options.lengthOfTime.days) {
  572. days = this.createDaysObject(
  573. this.intervalStart.clone(),
  574. this.intervalEnd.clone());
  575. data = {
  576. days: days,
  577. months: [],
  578. year: null,
  579. month: null,
  580. eventsLastMonth: [],
  581. eventsNextMonth: [],
  582. eventsThisMonth: [],
  583. extras: this.options.extras,
  584. daysOfTheWeek: this.daysOfTheWeek,
  585. intervalEnd: this.intervalEnd.clone(),
  586. numberOfRows: Math.ceil(days.length / 7),
  587. intervalStart: this.intervalStart.clone(),
  588. eventsThisInterval: this.eventsThisInterval
  589. };
  590. } else if (this.options.lengthOfTime.months) {
  591. months = [];
  592. numberOfRows = 0;
  593. eventsThisInterval = [];
  594. for (i = 0; i < this.options.lengthOfTime.months; i++) {
  595. var currentIntervalStart = this.intervalStart
  596. .clone()
  597. .add(i, 'months');
  598. var currentIntervalEnd = currentIntervalStart
  599. .clone()
  600. .endOf('month');
  601. var days = this.createDaysObject(
  602. currentIntervalStart,
  603. currentIntervalEnd);
  604. // Save events processed for each month into a master array of
  605. // events for this interval
  606. eventsThisInterval.push(this.eventsThisInterval);
  607. months.push({
  608. days: days,
  609. month: currentIntervalStart
  610. });
  611. }
  612. // Get the total number of rows across all months
  613. for (i in months) {
  614. numberOfRows += Math.ceil(months[i].days.length / 7);
  615. }
  616. data = {
  617. days: [],
  618. year: null,
  619. month: null,
  620. months: months,
  621. eventsThisMonth: [],
  622. numberOfRows: numberOfRows,
  623. extras: this.options.extras,
  624. intervalEnd: this.intervalEnd,
  625. intervalStart: this.intervalStart,
  626. daysOfTheWeek: this.daysOfTheWeek,
  627. eventsLastMonth: this.eventsLastMonth,
  628. eventsNextMonth: this.eventsNextMonth,
  629. eventsThisInterval: eventsThisInterval,
  630. };
  631. } else {
  632. // Get an array of days and blank spaces
  633. days = this.createDaysObject(
  634. this.month.clone().startOf('month'),
  635. this.month.clone().endOf('month'));
  636. // This is to prevent a scope/naming issue between this.month and
  637. // data.month
  638. currentMonth = this.month;
  639. data = {
  640. days: days,
  641. months: [],
  642. intervalEnd: null,
  643. intervalStart: null,
  644. year: this.month.year(),
  645. eventsThisInterval: null,
  646. extras: this.options.extras,
  647. month: this.month.format('MMMM'),
  648. daysOfTheWeek: this.daysOfTheWeek,
  649. eventsLastMonth: this.eventsLastMonth,
  650. eventsNextMonth: this.eventsNextMonth,
  651. numberOfRows: Math.ceil(days.length / 7),
  652. eventsThisMonth: this.eventsThisInterval
  653. };
  654. }
  655. // Render the calendar with the data above & bind events to its
  656. // elements
  657. if (!this.options.render) {
  658. this.calendarContainer.html(
  659. this.compiledClndrTemplate(data));
  660. } else {
  661. this.calendarContainer.html(
  662. this.options.render.apply(this, [data]));
  663. }
  664. // If there are constraints, we need to add the 'inactive' class to
  665. // the controls.
  666. if (this.options.constraints) {
  667. // In the interest of clarity we're just going to remove all
  668. // inactive classes and re-apply them each render.
  669. for (var target in this.options.targets) {
  670. if (target != this.options.targets.day) {
  671. this.element.find('.' + this.options.targets[target])
  672. .toggleClass(
  673. this.options.classes.inactive,
  674. false);
  675. }
  676. }
  677. // Just like the classes we'll set this internal state to true and
  678. // handle the disabling below.
  679. for (var i in this.constraints) {
  680. this.constraints[i] = true;
  681. }
  682. if (this.options.constraints.startDate) {
  683. start = moment(this.options.constraints.startDate);
  684. }
  685. if (this.options.constraints.endDate) {
  686. end = moment(this.options.constraints.endDate);
  687. }
  688. // Deal with the month controls first. Do we have room to go back?
  689. if (start
  690. && (start.isAfter(this.intervalStart)
  691. || start.isSame(this.intervalStart, 'day'))) {
  692. this.element.find('.' + this.options.targets.previousButton)
  693. .toggleClass(this.options.classes.inactive, true);
  694. this.constraints.previous = !this.constraints.previous;
  695. }
  696. // Do we have room to go forward?
  697. if (end
  698. && (end.isBefore(this.intervalEnd)
  699. || end.isSame(this.intervalEnd, 'day'))) {
  700. this.element.find('.' + this.options.targets.nextButton)
  701. .toggleClass(this.options.classes.inactive, true);
  702. this.constraints.next = !this.constraints.next;
  703. }
  704. // What's last year looking like?
  705. if (start && start.isAfter(oneYearAgo)) {
  706. this.element.find('.' + this.options.targets.previousYearButton)
  707. .toggleClass(this.options.classes.inactive, true);
  708. this.constraints.previousYear = !this.constraints.previousYear;
  709. }
  710. // How about next year?
  711. if (end && end.isBefore(oneYearFromEnd)) {
  712. this.element.find('.' + this.options.targets.nextYearButton)
  713. .toggleClass(this.options.classes.inactive, true);
  714. this.constraints.nextYear = !this.constraints.nextYear;
  715. }
  716. // Today? We could put this in init(), but we want to support the
  717. // user changing the constraints on a living instance.
  718. if ((start && start.isAfter(moment(), 'month'))
  719. || (end && end.isBefore(moment(), 'month'))) {
  720. this.element.find('.' + this.options.targets.today)
  721. .toggleClass(this.options.classes.inactive, true);
  722. this.constraints.today = !this.constraints.today;
  723. }
  724. }
  725. if (this.options.doneRendering) {
  726. this.options.doneRendering.apply(this, []);
  727. }
  728. };
  729. Clndr.prototype.bindEvents = function () {
  730. var self = this,
  731. $container = $(this.element),
  732. targets = this.options.targets,
  733. classes = self.options.classes,
  734. eventType = (this.options.useTouchEvents === true)
  735. ? 'touchstart'
  736. : 'click',
  737. eventName = eventType + '.clndr';
  738. // Make sure we don't already have events
  739. $container
  740. .off(eventName, '.' + targets.day)
  741. .off(eventName, '.' + targets.empty)
  742. .off(eventName, '.' + targets.nextButton)
  743. .off(eventName, '.' + targets.todayButton)
  744. .off(eventName, '.' + targets.previousButton)
  745. .off(eventName, '.' + targets.nextYearButton)
  746. .off(eventName, '.' + targets.previousYearButton);
  747. // Target the day elements and give them click events
  748. $container.on(eventName, '.' + targets.day, function (event) {
  749. var $currentTarget = $(event.currentTarget),
  750. target;
  751. if (self.options.clickEvents.click) {
  752. target = self.buildTargetObject(event.currentTarget, true);
  753. self.options.clickEvents.click.apply(self, [target]);
  754. }
  755. // If adjacentDaysChangeMonth is on, we need to change the
  756. // month here.
  757. if (self.options.adjacentDaysChangeMonth) {
  758. if ($currentTarget.is('.' + classes.lastMonth)) {
  759. self.backActionWithContext(self);
  760. } else if ($currentTarget.is('.' + classes.nextMonth)) {
  761. self.forwardActionWithContext(self);
  762. }
  763. }
  764. // if trackSelectedDate is on, we need to handle click on a new day
  765. if (self.options.trackSelectedDate) {
  766. if (self.options.ignoreInactiveDaysInSelection
  767. && $currentTarget.hasClass(classes.inactive)) {
  768. return;
  769. }
  770. // Remember new selected date
  771. self.options.selectedDate =
  772. self.getTargetDateString(event.currentTarget);
  773. // Handle "selected" class
  774. $currentTarget
  775. .siblings().removeClass(classes.selected).end()
  776. .addClass(classes.selected);
  777. }
  778. });
  779. // Target the empty calendar boxes as well
  780. $container.on(eventName, '.' + targets.empty, function (event) {
  781. var $eventTarget = $(event.currentTarget),
  782. target;
  783. if (self.options.clickEvents.click) {
  784. target = self.buildTargetObject(event.currentTarget, false);
  785. self.options.clickEvents.click.apply(self, [target]);
  786. }
  787. if (self.options.adjacentDaysChangeMonth) {
  788. if ($eventTarget.is('.' + classes.lastMonth)) {
  789. self.backActionWithContext(self);
  790. } else if ($eventTarget.is('.' + classes.nextMonth)) {
  791. self.forwardActionWithContext(self);
  792. }
  793. }
  794. });
  795. // Bind the previous, next and today buttons. We pass the current
  796. // context along with the event so that it can update this instance.
  797. data = {
  798. context: this
  799. };
  800. $container
  801. .on(eventName, '.' + targets.todayButton, data, this.todayAction)
  802. .on(eventName, '.' + targets.nextButton, data, this.forwardAction)
  803. .on(eventName, '.' + targets.previousButton, data, this.backAction)
  804. .on(eventName, '.' + targets.nextYearButton, data, this.nextYearAction)
  805. .on(eventName, '.' + targets.previousYearButton, data, this.previousYearAction);
  806. };
  807. /**
  808. * If the user provided a click callback we'd like to give them something
  809. * nice to work with. buildTargetObject takes the DOM element that was
  810. * clicked and returns an object with the DOM element, events, and the date
  811. * (if the latter two exist). Currently it is based on the id, however it'd
  812. * be nice to use a data- attribute in the future.
  813. */
  814. Clndr.prototype.buildTargetObject = function (currentTarget, targetWasDay) {
  815. // This is our default target object, assuming we hit an empty day
  816. // with no events.
  817. var target = {
  818. date: null,
  819. events: [],
  820. element: currentTarget
  821. };
  822. var dateString, filterFn;
  823. // Did we click on a day or just an empty box?
  824. if (targetWasDay) {
  825. dateString = this.getTargetDateString(currentTarget);
  826. target.date = (dateString)
  827. ? moment(dateString)
  828. : null;
  829. // Do we have events?
  830. if (this.options.events) {
  831. // Are any of the events happening today?
  832. if (this.options.multiDayEvents) {
  833. filterFn = function () {
  834. var isSameStart = target.date.isSame(
  835. this._clndrStartDateObject,
  836. 'day');
  837. var isAfterStart = target.date.isAfter(
  838. this._clndrStartDateObject,
  839. 'day');
  840. var isSameEnd = target.date.isSame(
  841. this._clndrEndDateObject,
  842. 'day');
  843. var isBeforeEnd = target.date.isBefore(
  844. this._clndrEndDateObject,
  845. 'day');
  846. return (isSameStart || isAfterStart)
  847. && (isSameEnd || isBeforeEnd);
  848. };
  849. } else {
  850. filterFn = function () {
  851. var startString = this._clndrStartDateObject
  852. .format('YYYY-MM-DD');
  853. return startString == dateString;
  854. };
  855. }
  856. // Filter the dates down to the ones that match.
  857. target.events = $.makeArray(
  858. $(this.options.events).filter(filterFn));
  859. }
  860. }
  861. return target;
  862. };
  863. /**
  864. * Get moment date object of the date associated with the given target.
  865. * This method is meant to be called on ".day" elements.
  866. */
  867. Clndr.prototype.getTargetDateString = function (target) {
  868. // Our identifier is in the list of classNames. Find it!
  869. var classNameIndex = target.className.indexOf('calendar-day-');
  870. if (classNameIndex !== -1) {
  871. // Our unique identifier is always 23 characters long.
  872. // If this feels a little wonky, that's probably because it is.
  873. // Open to suggestions on how to improve this guy.
  874. return target.className.substring(
  875. classNameIndex + 13,
  876. classNameIndex + 23);
  877. }
  878. return null;
  879. };
  880. /**
  881. * Triggers any applicable events given a change in the calendar's start
  882. * and end dates. ctx contains the current (changed) start and end date,
  883. * orig contains the original start and end dates.
  884. */
  885. Clndr.prototype.triggerEvents = function (ctx, orig) {
  886. var timeOpt = ctx.options.lengthOfTime,
  887. eventsOpt = ctx.options.clickEvents,
  888. newInt = {
  889. end: ctx.intervalEnd,
  890. start: ctx.intervalStart
  891. },
  892. intervalArg = [
  893. moment(ctx.intervalStart),
  894. moment(ctx.intervalEnd)
  895. ],
  896. monthArg = [moment(ctx.month)],
  897. nextYear, prevYear, yearChanged,
  898. nextMonth, prevMonth, monthChanged,
  899. nextInterval, prevInterval, intervalChanged;
  900. // We want to determine if any of the change conditions have been
  901. // hit and then trigger our events based off that.
  902. nextMonth = newInt.start.isAfter(orig.start)
  903. && (Math.abs(newInt.start.month() - orig.start.month()) == 1
  904. || orig.start.month() === 11 && newInt.start.month() === 0);
  905. prevMonth = newInt.start.isBefore(orig.start)
  906. && (Math.abs(orig.start.month() - newInt.start.month()) == 1
  907. || orig.start.month() === 0 && newInt.start.month() === 11);
  908. monthChanged = newInt.start.month() !== orig.start.month()
  909. || newInt.start.year() !== orig.start.year();
  910. nextYear = newInt.start.year() - orig.start.year() === 1
  911. || newInt.end.year() - orig.end.year() === 1;
  912. prevYear = orig.start.year() - newInt.start.year() === 1
  913. || orig.end.year() - newInt.end.year() === 1;
  914. yearChanged = newInt.start.year() !== orig.start.year();
  915. // Only configs with a time period will get the interval change event
  916. if (timeOpt.days || timeOpt.months) {
  917. nextInterval = newInt.start.isAfter(orig.start);
  918. prevInterval = newInt.start.isBefore(orig.start);
  919. intervalChanged = nextInterval || prevInterval;
  920. if (nextInterval && eventsOpt.nextInterval) {
  921. eventsOpt.nextInterval.apply(ctx, intervalArg);
  922. }
  923. if (prevInterval && eventsOpt.previousInterval) {
  924. eventsOpt.previousInterval.apply(ctx, intervalArg);
  925. }
  926. if (intervalChanged && eventsOpt.onIntervalChange) {
  927. eventsOpt.onIntervalChange.apply(ctx, intervalArg);
  928. }
  929. }
  930. // @V2-todo see https://github.com/kylestetz/CLNDR/issues/225
  931. else {
  932. if (nextMonth && eventsOpt.nextMonth) {
  933. eventsOpt.nextMonth.apply(ctx, monthArg);
  934. }
  935. if (prevMonth && eventsOpt.previousMonth) {
  936. eventsOpt.previousMonth.apply(ctx, monthArg);
  937. }
  938. if (monthChanged && eventsOpt.onMonthChange) {
  939. eventsOpt.onMonthChange.apply(ctx, monthArg);
  940. }
  941. if (nextYear && eventsOpt.nextYear) {
  942. eventsOpt.nextYear.apply(ctx, monthArg);
  943. }
  944. if (prevYear && eventsOpt.previousYear) {
  945. eventsOpt.previousYear.apply(ctx, monthArg);
  946. }
  947. if (yearChanged && eventsOpt.onYearChange) {
  948. eventsOpt.onYearChange.apply(ctx, monthArg);
  949. }
  950. }
  951. };
  952. /**
  953. * Main action to go backward one period. Other methods call these, like
  954. * backAction which proxies jQuery events, and backActionWithContext which
  955. * is an internal method that this library uses.
  956. */
  957. Clndr.prototype.back = function (options /*, ctx */) {
  958. var yearChanged = null,
  959. ctx = (arguments.length > 1)
  960. ? arguments[1]
  961. : this,
  962. timeOpt = ctx.options.lengthOfTime,
  963. defaults = {
  964. withCallbacks: false
  965. },
  966. orig = {
  967. end: ctx.intervalEnd.clone(),
  968. start: ctx.intervalStart.clone()
  969. };
  970. // Extend any options
  971. options = $.extend(true, {}, defaults, options);
  972. // Before we do anything, check if any constraints are limiting this
  973. if (!ctx.constraints.previous) {
  974. return ctx;
  975. }
  976. if (!timeOpt.days) {
  977. // Shift the interval by a month (or several months)
  978. ctx.intervalStart
  979. .subtract(timeOpt.interval, 'months')
  980. .startOf('month');
  981. ctx.intervalEnd = ctx.intervalStart.clone()
  982. .add(timeOpt.months || timeOpt.interval, 'months')
  983. .subtract(1, 'days')
  984. .endOf('month');
  985. ctx.month = ctx.intervalStart.clone();
  986. } else {
  987. // Shift the interval in days
  988. ctx.intervalStart
  989. .subtract(timeOpt.interval, 'days')
  990. .startOf('day');
  991. ctx.intervalEnd = ctx.intervalStart.clone()
  992. .add(timeOpt.days - 1, 'days')
  993. .endOf('day');
  994. // @V2-todo Useless, but consistent with API
  995. ctx.month = ctx.intervalStart.clone();
  996. }
  997. ctx.render();
  998. if (options.withCallbacks) {
  999. ctx.triggerEvents(ctx, orig);
  1000. }
  1001. return ctx;
  1002. };
  1003. Clndr.prototype.backAction = function (event) {
  1004. var ctx = event.data.context;
  1005. ctx.backActionWithContext(ctx);
  1006. };
  1007. Clndr.prototype.backActionWithContext = function (ctx) {
  1008. ctx.back({
  1009. withCallbacks: true
  1010. }, ctx);
  1011. };
  1012. Clndr.prototype.previous = function (options) {
  1013. // Alias
  1014. return this.back(options);
  1015. };
  1016. /**
  1017. * Main action to go forward one period. Other methods call these, like
  1018. * forwardAction which proxies jQuery events, and backActionWithContext
  1019. * which is an internal method that this library uses.
  1020. */
  1021. Clndr.prototype.forward = function (options /*, ctx */) {
  1022. var ctx = (arguments.length > 1)
  1023. ? arguments[1]
  1024. : this,
  1025. timeOpt = ctx.options.lengthOfTime,
  1026. defaults = {
  1027. withCallbacks: false
  1028. },
  1029. orig = {
  1030. end: ctx.intervalEnd.clone(),
  1031. start: ctx.intervalStart.clone()
  1032. };
  1033. // Extend any options
  1034. options = $.extend(true, {}, defaults, options);
  1035. // Before we do anything, check if any constraints are limiting this
  1036. if (!ctx.constraints.next) {
  1037. return ctx;
  1038. }
  1039. if (ctx.options.lengthOfTime.days) {
  1040. // Shift the interval in days
  1041. ctx.intervalStart
  1042. .add(timeOpt.interval, 'days')
  1043. .startOf('day');
  1044. ctx.intervalEnd = ctx.intervalStart.clone()
  1045. .add(timeOpt.days - 1, 'days')
  1046. .endOf('day');
  1047. // @V2-todo Useless, but consistent with API
  1048. ctx.month = ctx.intervalStart.clone();
  1049. } else {
  1050. // Shift the interval by a month (or several months)
  1051. ctx.intervalStart
  1052. .add(timeOpt.interval, 'months')
  1053. .startOf('month');
  1054. ctx.intervalEnd = ctx.intervalStart.clone()
  1055. .add(timeOpt.months || timeOpt.interval, 'months')
  1056. .subtract(1, 'days')
  1057. .endOf('month');
  1058. ctx.month = ctx.intervalStart.clone();
  1059. }
  1060. ctx.render();
  1061. if (options.withCallbacks) {
  1062. ctx.triggerEvents(ctx, orig);
  1063. }
  1064. return ctx;
  1065. };
  1066. Clndr.prototype.forwardAction = function (event) {
  1067. var ctx = event.data.context;
  1068. ctx.forwardActionWithContext(ctx);
  1069. };
  1070. Clndr.prototype.forwardActionWithContext = function (ctx) {
  1071. ctx.forward({
  1072. withCallbacks: true
  1073. }, ctx);
  1074. };
  1075. Clndr.prototype.next = function (options) {
  1076. // Alias
  1077. return this.forward(options);
  1078. };
  1079. /**
  1080. * Main action to go back one year.
  1081. */
  1082. Clndr.prototype.previousYear = function (options /*, ctx */) {
  1083. var ctx = (arguments.length > 1)
  1084. ? arguments[1]
  1085. : this,
  1086. defaults = {
  1087. withCallbacks: false
  1088. },
  1089. orig = {
  1090. end: ctx.intervalEnd.clone(),
  1091. start: ctx.intervalStart.clone()
  1092. };
  1093. // Extend any options
  1094. options = $.extend(true, {}, defaults, options);
  1095. // Before we do anything, check if any constraints are limiting this
  1096. if (!ctx.constraints.previousYear) {
  1097. return ctx;
  1098. }
  1099. ctx.month.subtract(1, 'year');
  1100. ctx.intervalStart.subtract(1, 'year');
  1101. ctx.intervalEnd.subtract(1, 'year');
  1102. ctx.render();
  1103. if (options.withCallbacks) {
  1104. ctx.triggerEvents(ctx, orig);
  1105. }
  1106. return ctx;
  1107. };
  1108. Clndr.prototype.previousYearAction = function (event) {
  1109. var ctx = event.data.context;
  1110. ctx.previousYear({
  1111. withCallbacks: true
  1112. }, ctx);
  1113. };
  1114. /**
  1115. * Main action to go forward one year.
  1116. */
  1117. Clndr.prototype.nextYear = function (options /*, ctx */) {
  1118. var ctx = (arguments.length > 1)
  1119. ? arguments[1]
  1120. : this,
  1121. defaults = {
  1122. withCallbacks: false
  1123. },
  1124. orig = {
  1125. end: ctx.intervalEnd.clone(),
  1126. start: ctx.intervalStart.clone()
  1127. };
  1128. // Extend any options
  1129. options = $.extend(true, {}, defaults, options);
  1130. // Before we do anything, check if any constraints are limiting this
  1131. if (!ctx.constraints.nextYear) {
  1132. return ctx;
  1133. }
  1134. ctx.month.add(1, 'year');
  1135. ctx.intervalStart.add(1, 'year');
  1136. ctx.intervalEnd.add(1, 'year');
  1137. ctx.render();
  1138. if (options.withCallbacks) {
  1139. ctx.triggerEvents(ctx, orig);
  1140. }
  1141. return ctx;
  1142. };
  1143. Clndr.prototype.nextYearAction = function (event) {
  1144. var ctx = event.data.context;
  1145. ctx.nextYear({
  1146. withCallbacks: true
  1147. }, ctx);
  1148. };
  1149. Clndr.prototype.today = function (options /*, ctx */) {
  1150. var ctx = (arguments.length > 1)
  1151. ? arguments[1]
  1152. : this,
  1153. timeOpt = ctx.options.lengthOfTime,
  1154. defaults = {
  1155. withCallbacks: false
  1156. },
  1157. orig = {
  1158. end: ctx.intervalEnd.clone(),
  1159. start: ctx.intervalStart.clone()
  1160. };
  1161. // Extend any options
  1162. options = $.extend(true, {}, defaults, options);
  1163. // @V2-todo Only used for legacy month view
  1164. ctx.month = moment().startOf('month');
  1165. if (timeOpt.days) {
  1166. // If there was a startDate specified, we should figure out what
  1167. // the weekday is and use that as the starting point of our
  1168. // interval. If not, go to today.weekday(0).
  1169. if (timeOpt.startDate) {
  1170. ctx.intervalStart = moment()
  1171. .weekday(timeOpt.startDate.weekday())
  1172. .startOf('day');
  1173. } else {
  1174. ctx.intervalStart = moment().weekday(0).startOf('day');
  1175. }
  1176. ctx.intervalEnd = ctx.intervalStart.clone()
  1177. .add(timeOpt.days - 1, 'days')
  1178. .endOf('day');
  1179. } else {
  1180. // Set the intervalStart to this month.
  1181. ctx.intervalStart = moment().startOf('month');
  1182. ctx.intervalEnd = ctx.intervalStart.clone()
  1183. .add(timeOpt.months || timeOpt.interval, 'months')
  1184. .subtract(1, 'days')
  1185. .endOf('month');
  1186. }
  1187. // No need to re-render if we didn't change months.
  1188. if (!ctx.intervalStart.isSame(orig.start)
  1189. || !ctx.intervalEnd.isSame(orig.end)) {
  1190. ctx.render();
  1191. }
  1192. // Fire the today event handler regardless of any change
  1193. if (options.withCallbacks) {
  1194. if (ctx.options.clickEvents.today) {
  1195. ctx.options.clickEvents.today.apply(ctx, [moment(ctx.month)]);
  1196. }
  1197. ctx.triggerEvents(ctx, orig);
  1198. }
  1199. };
  1200. Clndr.prototype.todayAction = function (event) {
  1201. var ctx = event.data.context;
  1202. ctx.today({
  1203. withCallbacks: true
  1204. }, ctx);
  1205. };
  1206. /**
  1207. * Changes the month. Accepts 0-11 or a full/partial month name e.g. "Jan",
  1208. * "February", "Mar", etc.
  1209. */
  1210. Clndr.prototype.setMonth = function (newMonth, options) {
  1211. var timeOpt = this.options.lengthOfTime,
  1212. orig = {
  1213. end: this.intervalEnd.clone(),
  1214. start: this.intervalStart.clone()
  1215. };
  1216. if (timeOpt.days || timeOpt.months) {
  1217. console.log(
  1218. 'You are using a custom date interval. Use ' +
  1219. 'Clndr.setIntervalStart(startDate) instead.');
  1220. return this;
  1221. }
  1222. this.month.month(newMonth);
  1223. this.intervalStart = this.month.clone().startOf('month');
  1224. this.intervalEnd = this.intervalStart.clone().endOf('month');
  1225. this.render();
  1226. if (options && options.withCallbacks) {
  1227. this.triggerEvents(this, orig);
  1228. }
  1229. return this;
  1230. };
  1231. Clndr.prototype.setYear = function (newYear, options) {
  1232. var orig = {
  1233. end: this.intervalEnd.clone(),
  1234. start: this.intervalStart.clone()
  1235. };
  1236. this.month.year(newYear);
  1237. this.intervalEnd.year(newYear);
  1238. this.intervalStart.year(newYear);
  1239. this.render();
  1240. if (options && options.withCallbacks) {
  1241. this.triggerEvents(this, orig);
  1242. }
  1243. return this;
  1244. };
  1245. /**
  1246. * Sets the start of the time period according to newDate. newDate can be
  1247. * a string or a moment object.
  1248. */
  1249. Clndr.prototype.setIntervalStart = function (newDate, options) {
  1250. var timeOpt = this.options.lengthOfTime,
  1251. orig = {
  1252. end: this.intervalEnd.clone(),
  1253. start: this.intervalStart.clone()
  1254. };
  1255. if (!timeOpt.days && !timeOpt.months) {
  1256. console.log(
  1257. 'You are using a custom date interval. Use ' +
  1258. 'Clndr.setIntervalStart(startDate) instead.');
  1259. return this;
  1260. }
  1261. if (timeOpt.days) {
  1262. this.intervalStart = moment(newDate).startOf('day');
  1263. this.intervalEnd = this.intervalStart.clone()
  1264. .add(timeOpt - 1, 'days')
  1265. .endOf('day');
  1266. } else {
  1267. this.intervalStart = moment(newDate).startOf('month');
  1268. this.intervalEnd = this.intervalStart.clone()
  1269. .add(timeOpt.months || timeOpt.interval, 'months')
  1270. .subtract(1, 'days')
  1271. .endOf('month');
  1272. }
  1273. this.month = this.intervalStart.clone();
  1274. this.render();
  1275. if (options && options.withCallbacks) {
  1276. this.triggerEvents(this, orig);
  1277. }
  1278. return this;
  1279. };
  1280. /**
  1281. * Overwrites events in the calendar and triggers a render.
  1282. */
  1283. Clndr.prototype.setEvents = function (events) {
  1284. // Go through each event and add a moment object
  1285. if (this.options.multiDayEvents) {
  1286. this.options.events = this.addMultiDayMomentObjectsToEvents(events);
  1287. } else {
  1288. this.options.events = this.addMomentObjectToEvents(events);
  1289. }
  1290. this.render();
  1291. return this;
  1292. };
  1293. /**
  1294. * Adds additional events to the calendar and triggers a render.
  1295. */
  1296. Clndr.prototype.addEvents = function (events) {
  1297. // Go through each event and add a moment object
  1298. if (this.options.multiDayEvents) {
  1299. this.options.events = $.merge(
  1300. this.options.events,
  1301. this.addMultiDayMomentObjectsToEvents(events));
  1302. } else {
  1303. this.options.events = $.merge(
  1304. this.options.events,
  1305. this.addMomentObjectToEvents(events));
  1306. }
  1307. this.render();
  1308. return this;
  1309. };
  1310. /**
  1311. * Passes all events through a matching function. Any that pass a truth
  1312. * test will be removed from the calendar's events. This triggers a render.
  1313. */
  1314. Clndr.prototype.removeEvents = function (matchingFn) {
  1315. for (var i = this.options.events.length - 1; i >= 0; i--) {
  1316. if (matchingFn(this.options.events[i]) == true) {
  1317. this.options.events.splice(i, 1);
  1318. }
  1319. }
  1320. this.render();
  1321. return this;
  1322. };
  1323. Clndr.prototype.addMomentObjectToEvents = function (events) {
  1324. var i = 0,
  1325. self = this;
  1326. for (i; i < events.length; i++) {
  1327. // Add the date as both start and end, since it's a single-day
  1328. // event by default
  1329. events[i]._clndrStartDateObject =
  1330. moment(events[i][self.options.dateParameter]);
  1331. events[i]._clndrEndDateObject =
  1332. moment(events[i][self.options.dateParameter]);
  1333. }
  1334. return events;
  1335. };
  1336. Clndr.prototype.addMultiDayMomentObjectsToEvents = function (events) {
  1337. var i = 0,
  1338. self = this,
  1339. multiEvents = self.options.multiDayEvents;
  1340. for (i; i < events.length; i++) {
  1341. var end = events[i][multiEvents.endDate],
  1342. start = events[i][multiEvents.startDate];
  1343. // If we don't find the startDate OR endDate fields, look for
  1344. // singleDay
  1345. if (!end && !start) {
  1346. events[i]._clndrEndDateObject =
  1347. moment(events[i][multiEvents.singleDay]);
  1348. events[i]._clndrStartDateObject =
  1349. moment(events[i][multiEvents.singleDay]);
  1350. }
  1351. // Otherwise use startDate and endDate, or whichever one is present
  1352. else {
  1353. events[i]._clndrEndDateObject = moment(end || start);
  1354. events[i]._clndrStartDateObject = moment(start || end);
  1355. }
  1356. }
  1357. return events;
  1358. };
  1359. Clndr.prototype.calendarDay = function (options) {
  1360. var defaults = {
  1361. day: "",
  1362. date: null,
  1363. events: [],
  1364. classes: this.options.targets.empty
  1365. };
  1366. return $.extend({}, defaults, options);
  1367. };
  1368. Clndr.prototype.destroy = function () {
  1369. var $container = $(this.calendarContainer);
  1370. $container.parent().data('plugin_clndr', null);
  1371. this.options = defaults;
  1372. $container.empty().remove();
  1373. this.element = null;
  1374. };
  1375. $.fn.clndr = function (options) {
  1376. var clndrInstance;
  1377. if (this.length > 1) {
  1378. throw new Error(
  1379. "CLNDR does not support multiple elements yet. Make sure " +
  1380. "your clndr selector returns only one element.");
  1381. }
  1382. if (!this.length) {
  1383. throw new Error(
  1384. "CLNDR cannot be instantiated on an empty selector.");
  1385. }
  1386. if (!this.data('plugin_clndr')) {
  1387. clndrInstance = new Clndr(this, options);
  1388. this.data('plugin_clndr', clndrInstance);
  1389. return clndrInstance;
  1390. }
  1391. return this.data('plugin_clndr');
  1392. };
  1393. }));