forked from kylestetz/CLNDR
-
Notifications
You must be signed in to change notification settings - Fork 0
/
clndr.js
1680 lines (1481 loc) · 61 KB
/
clndr.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* ~ CLNDR v1.4.7 ~
* ==============================================
* https://github.com/kylestetz/CLNDR
* ==============================================
* Created by kyle stetz (github.com/kylestetz)
* & available under the MIT license
* http:https://opensource.org/licenses/mit-license.php
* ==============================================
*
* This is the fully-commented development version of CLNDR.
* For the production version, check out clndr.min.js
* at https://github.com/kylestetz/CLNDR
*
* This work is based on the
* jQuery lightweight plugin boilerplate
* Original author: @ajpiano
* Further changes, comments: @addyosmani
* Licensed under the MIT license
*/
(function (factory) {
// Multiple loading methods are supported depending on
// what is available globally. While moment is loaded
// here, the instance can be passed in at config time.
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery', 'moment'], factory);
}
else if (typeof exports === 'object') {
// Node/CommonJS
factory(require('jquery'), require('moment'));
}
else {
// Browser globals
factory(jQuery, moment);
}
}(function ($, moment) {
// Namespace
var pluginName = 'clndr';
// This is the default calendar template. This can be overridden.
var clndrTemplate =
"<div class='clndr-controls'>" +
"<div class='clndr-control-button'>" +
"<span class='clndr-previous-button'>previous</span>" +
"</div>" +
"<div class='month'><%= month %> <%= year %></div>" +
"<div class='clndr-control-button rightalign'>" +
"<span class='clndr-next-button'>next</span>" +
"</div>" +
"</div>" +
"<table class='clndr-table' border='0' cellspacing='0' cellpadding='0'>" +
"<thead>" +
"<tr class='header-days'>" +
"<% for(var i = 0; i < daysOfTheWeek.length; i++) { %>" +
"<td class='header-day'><%= daysOfTheWeek[i] %></td>" +
"<% } %>" +
"</tr>" +
"</thead>" +
"<tbody>" +
"<% for(var i = 0; i < numberOfRows; i++){ %>" +
"<tr>" +
"<% for(var j = 0; j < 7; j++){ %>" +
"<% var d = j + i * 7; %>" +
"<td class='<%= days[d].classes %>'>" +
"<div class='day-contents'><%= days[d].day %></div>" +
"</td>" +
"<% } %>" +
"</tr>" +
"<% } %>" +
"</tbody>" +
"</table>";
// Defaults used throughout the application, see docs.
var defaults = {
events: [],
ready: null,
extras: null,
render: null,
moment: null,
weekOffset: 0,
constraints: null,
forceSixRows: null,
selectedDate: null,
doneRendering: null,
daysOfTheWeek: null,
multiDayEvents: null,
startWithMonth: null,
dateParameter: 'date',
template: clndrTemplate,
showAdjacentMonths: true,
trackSelectedDate: false,
adjacentDaysChangeMonth: false,
ignoreInactiveDaysInSelection: null,
lengthOfTime: {
days: null,
interval: 1,
months: null
},
clickEvents: {
click: null,
today: null,
nextYear: null,
nextMonth: null,
nextInterval: null,
previousYear: null,
onYearChange: null,
previousMonth: null,
onMonthChange: null,
previousInterval: null,
onIntervalChange: null
},
targets: {
day: 'day',
empty: 'empty',
nextButton: 'clndr-next-button',
todayButton: 'clndr-today-button',
previousButton: 'clndr-previous-button',
nextYearButton: 'clndr-next-year-button',
previousYearButton: 'clndr-previous-year-button'
},
classes: {
past: "past",
today: "today",
event: "event",
inactive: "inactive",
selected: "selected",
lastMonth: "last-month",
nextMonth: "next-month",
adjacentMonth: "adjacent-month"
},
};
/**
* The actual plugin constructor.
* Parses the events and lengthOfTime options to build a calendar of day
* objects containing event information from the events array.
*/
function Clndr(element, options) {
var dayDiff;
var constraintEnd;
var constraintStart;
this.element = element;
// Merge the default options with user-provided options
this.options = $.extend(true, {}, defaults, options);
// Check if moment was passed in as a dependency
if (this.options.moment) {
moment = this.options.moment;
}
// Boolean values used to log if any contraints are met
this.constraints = {
next: true,
today: true,
previous: true,
nextYear: true,
previousYear: true
};
// If there are events, we should run them through our
// addMomentObjectToEvents function which will add a date object that
// we can use to make life easier. This is only necessarywhen events
// are provided on instantiation, since our setEvents function uses
// addMomentObjectToEvents.
if (this.options.events.length) {
if (this.options.multiDayEvents) {
this.options.events =
this.addMultiDayMomentObjectsToEvents(this.options.events);
} else {
this.options.events =
this.addMomentObjectToEvents(this.options.events);
}
}
// This used to be a place where we'd figure out the current month,
// but since we want to open up support for arbitrary lengths of time
// we're going to store the current range in addition to the current
// month.
if (this.options.lengthOfTime.months || this.options.lengthOfTime.days) {
// We want to establish intervalStart and intervalEnd, which will
// keep track of our boundaries. Let's look at the possibilities...
if (this.options.lengthOfTime.months) {
// Gonna go right ahead and annihilate any chance for bugs here
this.options.lengthOfTime.days = null;
// The length is specified in months. Is there a start date?
if (this.options.lengthOfTime.startDate) {
this.intervalStart =
moment(this.options.lengthOfTime.startDate)
.startOf('month');
} else if (this.options.startWithMonth) {
this.intervalStart =
moment(this.options.startWithMonth)
.startOf('month');
} else {
this.intervalStart = moment().startOf('month');
}
// Subtract a day so that we are at the end of the interval. We
// always want intervalEnd to be inclusive.
this.intervalEnd = moment(this.intervalStart)
.add(this.options.lengthOfTime.months, 'months')
.subtract(1, 'days');
this.month = this.intervalStart.clone();
}
else if (this.options.lengthOfTime.days) {
// The length is specified in days. Start date?
if (this.options.lengthOfTime.startDate) {
this.intervalStart =
moment(this.options.lengthOfTime.startDate)
.startOf('day');
} else {
this.intervalStart = moment().weekday(0).startOf('day');
}
this.intervalEnd = moment(this.intervalStart)
.add(this.options.lengthOfTime.days - 1, 'days')
.endOf('day');
this.month = this.intervalStart.clone();
}
// No length of time specified so we're going to default into using the
// current month as the time period.
} else {
this.month = moment().startOf('month');
this.intervalStart = moment(this.month);
this.intervalEnd = moment(this.month).endOf('month');
}
if (this.options.startWithMonth) {
this.month = moment(this.options.startWithMonth).startOf('month');
this.intervalStart = moment(this.month);
this.intervalEnd = (this.options.lengthOfTime.days)
? moment(this.month)
.add(this.options.lengthOfTime.days - 1, 'days')
.endOf('day')
: moment(this.month).endOf('month');
}
// If we've got constraints set, make sure the interval is within them.
if (this.options.constraints) {
// First check if the startDate exists & is later than now.
if (this.options.constraints.startDate) {
constraintStart = moment(this.options.constraints.startDate);
// We need to handle the constraints differently for weekly
// calendars vs. monthly calendars.
if (this.options.lengthOfTime.days) {
if (this.intervalStart.isBefore(constraintStart, 'week')) {
this.intervalStart = constraintStart.startOf('week');
}
// If the new interval period is less than the desired length
// of time, or before the starting interval, then correct it.
dayDiff = this.intervalStart.diff(this.intervalEnd, 'days');
if (dayDiff < this.options.lengthOfTime.days
|| this.intervalEnd.isBefore(this.intervalStart))
{
this.intervalEnd = moment(this.intervalStart)
.add(this.options.lengthOfTime.days - 1, 'days')
.endOf('day');
this.month = this.intervalStart.clone();
}
}
else {
if (this.intervalStart.isBefore(constraintStart, 'month')) {
// Try to preserve the date by moving only the month.
this.intervalStart
.set('month', constraintStart.month())
.set('year', constraintStart.year());
this.month
.set('month', constraintStart.month())
.set('year', constraintStart.year());
}
// Check if the ending interval is earlier than now.
if (this.intervalEnd.isBefore(constraintStart, 'month')) {
this.intervalEnd
.set('month', constraintStart.month())
.set('year', constraintStart.year());
}
}
}
// Make sure the intervalEnd is before the endDate.
if (this.options.constraints.endDate) {
constraintEnd = moment(this.options.constraints.endDate);
// We need to handle the constraints differently for weekly
// calendars vs. monthly calendars.
if (this.options.lengthOfTime.days) {
// The starting interval is after our ending constraint.
if (this.intervalStart.isAfter(constraintEnd, 'week')) {
this.intervalStart = moment(constraintEnd)
.endOf('week')
.subtract(this.options.lengthOfTime.days - 1, 'days')
.startOf('day');
this.intervalEnd = moment(constraintEnd)
.endOf('week');
this.month = this.intervalStart.clone();
}
}
else {
if (this.intervalEnd.isAfter(constraintEnd, 'month')) {
this.intervalEnd
.set('month', constraintEnd.month())
.set('year', constraintEnd.year());
this.month
.set('month', constraintEnd.month())
.set('year', constraintEnd.year());
}
// Check if the starting interval is later than the ending.
if (this.intervalStart.isAfter(constraintEnd, 'month')) {
this.intervalStart
.set('month', constraintEnd.month())
.set('year', constraintEnd.year());
}
}
}
}
this._defaults = defaults;
this._name = pluginName;
// Some first-time initialization -> day of the week offset, template
// compiling, making and storing some elements we'll need later, and
// event handling for the controller.
this.init();
}
/**
* Calendar initialization.
* Sets up the days of the week, the rendering function, binds all of the
* events to the rendered calendar, and then stores the node locally.
*/
Clndr.prototype.init = function () {
// Create the days of the week using moment's current language setting
this.daysOfTheWeek = this.options.daysOfTheWeek || [];
if (!this.options.daysOfTheWeek) {
this.daysOfTheWeek = [];
for (var i = 0; i < 7; i++) {
this.daysOfTheWeek.push(
moment().weekday(i).format('dd').charAt(0));
}
}
// Shuffle the week if there's an offset
if (this.options.weekOffset) {
this.daysOfTheWeek = this.shiftWeekdayLabels(this.options.weekOffset);
}
// Quick and dirty test to make sure rendering is possible.
if (!$.isFunction(this.options.render)) {
this.options.render = null;
if (typeof _ === 'undefined') {
throw new Error(
"Underscore was not found. Please include underscore.js " +
"OR provide a custom render function.");
} else {
// We're just going ahead and using underscore here if no
// render method has been supplied.
this.compiledClndrTemplate = _.template(this.options.template);
}
}
// Create the parent element that will hold the plugin and save it
// for later
$(this.element).html("<div class='clndr'></div>");
this.calendarContainer = $('.clndr', this.element);
// Attach event handlers for clicks on buttons/cells
this.bindEvents();
// Do a normal render of the calendar template
this.render();
// If a ready callback has been provided, call it.
if (this.options.ready) {
this.options.ready.apply(this, []);
}
};
Clndr.prototype.shiftWeekdayLabels = function (offset) {
var days = this.daysOfTheWeek;
for (var i = 0; i < offset; i++) {
days.push(days.shift());
}
return days;
};
/**
* This is where the magic happens. Given a starting date and ending date,
* an array of calendarDay objects is constructed that contains appropriate
* events and classes depending on the circumstance.
*/
Clndr.prototype.createDaysObject = function (startDate, endDate) {
// This array will hold numbers for the entire grid (even the blank
// spaces).
var daysArray = [],
date = startDate.clone(),
lengthOfInterval = endDate.diff(startDate, 'days'),
startOfLastMonth, endOfLastMonth, startOfNextMonth,
endOfNextMonth, diff, dateIterator;
// This is a helper object so that days can resolve their classes
// correctly. Don't use it for anything please.
this._currentIntervalStart = startDate.clone();
// Filter the events list (if it exists) to events that are happening
// last month, this month and next month (within the current grid view).
this.eventsLastMonth = [];
this.eventsNextMonth = [];
this.eventsThisInterval = [];
// Event parsing
if (this.options.events.length) {
// Here are the only two cases where we don't get an event in our
// interval:
// startDate | endDate | e.start | e.end
// e.start | e.end | startDate | endDate
this.eventsThisInterval = $(this.options.events).filter(
function () {
var afterEnd = this._clndrStartDateObject.isAfter(endDate),
beforeStart = this._clndrEndDateObject.isBefore(startDate);
if (beforeStart || afterEnd) {
return false;
} else {
return true;
}
}).toArray();
if (this.options.showAdjacentMonths) {
startOfLastMonth = startDate.clone()
.subtract(1, 'months')
.startOf('month');
endOfLastMonth = startOfLastMonth.clone().endOf('month');
startOfNextMonth = endDate.clone()
.add(1, 'months')
.startOf('month');
endOfNextMonth = startOfNextMonth.clone().endOf('month');
this.eventsLastMonth = $(this.options.events).filter(
function () {
var beforeStart = this._clndrEndDateObject
.isBefore(startOfLastMonth);
var afterEnd = this._clndrStartDateObject
.isAfter(endOfLastMonth);
if (beforeStart || afterEnd) {
return false;
} else {
return true;
}
}).toArray();
this.eventsNextMonth = $(this.options.events).filter(
function () {
var beforeStart = this._clndrEndDateObject
.isBefore(startOfNextMonth);
var afterEnd = this._clndrStartDateObject
.isAfter(endOfNextMonth);
if (beforeStart || afterEnd) {
return false;
} else {
return true;
}
}).toArray();
}
}
// If diff is greater than 0, we'll have to fill in last days of the
// previous month to account for the empty boxes in the grid. We also
// need to take into account the weekOffset parameter. None of this
// needs to happen if the interval is being specified in days rather
// than months.
if (!this.options.lengthOfTime.days) {
diff = date.weekday() - this.options.weekOffset;
if (diff < 0) {
diff += 7;
}
if (this.options.showAdjacentMonths) {
for (var i = 1; i <= diff; i++) {
var day = moment([
startDate.year(),
startDate.month(),
i
]).subtract(diff, 'days');
daysArray.push(
this.createDayObject(
day,
this.eventsLastMonth
));
}
} else {
for (var i = 0; i < diff; i++) {
daysArray.push(
this.calendarDay({
classes: this.options.targets.empty +
" " + this.options.classes.lastMonth
}));
}
}
}
// Now we push all of the days in the interval
dateIterator = startDate.clone();
while (dateIterator.isBefore(endDate) || dateIterator.isSame(endDate, 'day')) {
daysArray.push(
this.createDayObject(
dateIterator.clone(),
this.eventsThisInterval
));
dateIterator.add(1, 'days');
}
// ...and if there are any trailing blank boxes, fill those in with the
// next month first days. Again, we can ignore this if the interval is
// specified in days.
if (!this.options.lengthOfTime.days) {
while (daysArray.length % 7 !== 0) {
if (this.options.showAdjacentMonths) {
daysArray.push(
this.createDayObject(
dateIterator.clone(),
this.eventsNextMonth
));
} else {
daysArray.push(
this.calendarDay({
classes: this.options.targets.empty + " " +
this.options.classes.nextMonth
}));
}
dateIterator.add(1, 'days');
}
}
// If we want to force six rows of calendar, now's our Last Chance to
// add another row. If the 42 seems explicit it's because we're
// creating a 7-row grid and 6 rows of 7 is always 42!
if (this.options.forceSixRows && daysArray.length !== 42) {
while (daysArray.length < 42) {
if (this.options.showAdjacentMonths) {
daysArray.push(
this.createDayObject(
dateIterator.clone(),
this.eventsNextMonth
));
dateIterator.add(1, 'days');
} else {
daysArray.push(
this.calendarDay({
classes: this.options.targets.empty + " " +
this.options.classes.nextMonth
}));
}
}
}
return daysArray;
};
Clndr.prototype.createDayObject = function (day, monthEvents) {
var j = 0,
self = this,
now = moment(),
eventsToday = [],
extraClasses = "",
properties = {
isToday: false,
isInactive: false,
isAdjacentMonth: false
},
startMoment, endMoment, selectedMoment;
// Validate moment date
if (!day.isValid() && day.hasOwnProperty('_d') && day._d != undefined) {
day = moment(day._d);
}
for (j; j < monthEvents.length; j++) {
// Keep in mind that the events here already passed the month/year
// test. Now all we have to compare is the moment.date(), which
// returns the day of the month.
var start = monthEvents[j]._clndrStartDateObject,
end = monthEvents[j]._clndrEndDateObject;
// If today is the same day as start or is after the start, and
// if today is the same day as the end or before the end ...
// woohoo semantics!
if ( (day.isSame(start, 'day') || day.isAfter(start, 'day'))
&& (day.isSame(end, 'day') || day.isBefore(end, 'day')) )
{
eventsToday.push( monthEvents[j] );
}
}
if (now.format("YYYY-MM-DD") == day.format("YYYY-MM-DD")) {
extraClasses += (" " + this.options.classes.today);
properties.isToday = true;
}
if (day.isBefore(now, 'day')) {
extraClasses += (" " + this.options.classes.past);
}
if (eventsToday.length) {
extraClasses += (" " + this.options.classes.event);
}
if (!this.options.lengthOfTime.days) {
if (this._currentIntervalStart.month() > day.month()) {
extraClasses += (" " + this.options.classes.adjacentMonth);
properties.isAdjacentMonth = true;
this._currentIntervalStart.year() === day.year()
? extraClasses += (" " + this.options.classes.lastMonth)
: extraClasses += (" " + this.options.classes.nextMonth);
}
else if (this._currentIntervalStart.month() < day.month()) {
extraClasses += (" " + this.options.classes.adjacentMonth);
properties.isAdjacentMonth = true;
this._currentIntervalStart.year() === day.year()
? extraClasses += (" " + this.options.classes.nextMonth)
: extraClasses += (" " + this.options.classes.lastMonth);
}
}
// If there are constraints, we need to add the inactive class to the
// days outside of them
if (this.options.constraints) {
endMoment = moment(this.options.constraints.endDate);
startMoment = moment(this.options.constraints.startDate);
if (this.options.constraints.startDate && day.isBefore(startMoment)) {
extraClasses += (" " + this.options.classes.inactive);
properties.isInactive = true;
}
if (this.options.constraints.endDate && day.isAfter(endMoment)) {
extraClasses += (" " + this.options.classes.inactive);
properties.isInactive = true;
}
}
// Validate moment date
if (!day.isValid() && day.hasOwnProperty('_d') && day._d != undefined) {
day = moment(day._d);
}
// Check whether the day is "selected"
selectedMoment = moment(this.options.selectedDate);
if (this.options.selectedDate && day.isSame(selectedMoment, 'day')) {
extraClasses += (" " + this.options.classes.selected);
}
// We're moving away from using IDs in favor of classes, since when
// using multiple calendars on a page we are technically violating the
// uniqueness of IDs.
extraClasses += " calendar-day-" + day.format("YYYY-MM-DD");
// Day of week
extraClasses += " calendar-dow-" + day.weekday();
return this.calendarDay({
date: day,
day: day.date(),
events: eventsToday,
properties: properties,
classes: this.options.targets.day + extraClasses
});
};
Clndr.prototype.render = function () {
// Get rid of the previous set of calendar parts. This should handle garbage
// collection according to jQuery's docs:
// http:https://api.jquery.com/empty/
// To avoid memory leaks, jQuery removes other constructs such as
// data and event handlers from the child elements before removing
// the elements themselves.
var data = {},
end = null,
start = null,
oneYearFromEnd = this.intervalEnd.clone().add(1, 'years'),
oneYearAgo = this.intervalStart.clone().subtract(1, 'years'),
days, months, currentMonth, eventsThisInterval,
numberOfRows;
this.calendarContainer.empty();
if (this.options.lengthOfTime.days) {
days = this.createDaysObject(
this.intervalStart.clone(),
this.intervalEnd.clone());
data = {
days: days,
months: [],
year: null,
month: null,
eventsLastMonth: [],
eventsNextMonth: [],
eventsThisMonth: [],
extras: this.options.extras,
daysOfTheWeek: this.daysOfTheWeek,
intervalEnd: this.intervalEnd.clone(),
numberOfRows: Math.ceil(days.length / 7),
intervalStart: this.intervalStart.clone(),
eventsThisInterval: this.eventsThisInterval
};
}
else if (this.options.lengthOfTime.months) {
months = [];
numberOfRows = 0;
eventsThisInterval = [];
for (i = 0; i < this.options.lengthOfTime.months; i++) {
var currentIntervalStart = this.intervalStart
.clone()
.add(i, 'months');
var currentIntervalEnd = currentIntervalStart
.clone()
.endOf('month');
var days = this.createDaysObject(
currentIntervalStart,
currentIntervalEnd);
// Save events processed for each month into a master array of
// events for this interval
eventsThisInterval.push(this.eventsThisInterval);
months.push({
days: days,
month: currentIntervalStart
});
}
// Get the total number of rows across all months
for (i = 0; i < months.length; i++) {
numberOfRows += Math.ceil(months[i].days.length / 7);
}
data = {
days: [],
year: null,
month: null,
months: months,
eventsThisMonth: [],
numberOfRows: numberOfRows,
extras: this.options.extras,
intervalEnd: this.intervalEnd,
intervalStart: this.intervalStart,
daysOfTheWeek: this.daysOfTheWeek,
eventsLastMonth: this.eventsLastMonth,
eventsNextMonth: this.eventsNextMonth,
eventsThisInterval: eventsThisInterval,
};
}
else {
// Get an array of days and blank spaces
days = this.createDaysObject(
this.month.clone().startOf('month'),
this.month.clone().endOf('month'));
// This is to prevent a scope/naming issue between this.month and
// data.month
currentMonth = this.month;
data = {
days: days,
months: [],
intervalEnd: null,
intervalStart: null,
year: this.month.year(),
eventsThisInterval: null,
extras: this.options.extras,
month: this.month.format('MMMM'),
daysOfTheWeek: this.daysOfTheWeek,
eventsLastMonth: this.eventsLastMonth,
eventsNextMonth: this.eventsNextMonth,
numberOfRows: Math.ceil(days.length / 7),
eventsThisMonth: this.eventsThisInterval
};
}
// Render the calendar with the data above & bind events to its
// elements
if ( !this.options.render) {
this.calendarContainer.html(
this.compiledClndrTemplate(data));
} else {
this.calendarContainer.html(
this.options.render.apply(this, [data]));
}
// If there are constraints, we need to add the 'inactive' class to
// the controls.
if (this.options.constraints) {
// In the interest of clarity we're just going to remove all
// inactive classes and re-apply them each render.
for (var target in this.options.targets) {
if (target != this.options.targets.day) {
this.element.find('.' + this.options.targets[target])
.toggleClass(
this.options.classes.inactive,
false);
}
}
// Just like the classes we'll set this internal state to true and
// handle the disabling below.
for (var i in this.constraints) {
this.constraints[i] = true;
}
if (this.options.constraints.startDate) {
start = moment(this.options.constraints.startDate);
}
if (this.options.constraints.endDate) {
end = moment(this.options.constraints.endDate);
}
// Deal with the month controls first. Do we have room to go back?
if (start
&& (start.isAfter(this.intervalStart)
|| start.isSame(this.intervalStart, 'day')))
{
this.element.find('.' + this.options.targets.previousButton)
.toggleClass(this.options.classes.inactive, true);
this.constraints.previous = !this.constraints.previous;
}
// Do we have room to go forward?
if (end
&& (end.isBefore(this.intervalEnd)
|| end.isSame(this.intervalEnd, 'day')))
{
this.element.find('.' + this.options.targets.nextButton)
.toggleClass(this.options.classes.inactive, true);
this.constraints.next = !this.constraints.next;
}
// What's last year looking like?
if (start && start.isAfter(oneYearAgo)) {
this.element.find('.' + this.options.targets.previousYearButton)
.toggleClass(this.options.classes.inactive, true);
this.constraints.previousYear = !this.constraints.previousYear;
}
// How about next year?
if (end && end.isBefore(oneYearFromEnd)) {
this.element.find('.' + this.options.targets.nextYearButton)
.toggleClass(this.options.classes.inactive, true);
this.constraints.nextYear = !this.constraints.nextYear;
}
// Today? We could put this in init(), but we want to support the
// user changing the constraints on a living instance.
if ( (start && start.isAfter( moment(), 'month' ))
|| (end && end.isBefore( moment(), 'month' )) )
{
this.element.find('.' + this.options.targets.today)
.toggleClass(this.options.classes.inactive, true);
this.constraints.today = !this.constraints.today;
}
}
if (this.options.doneRendering) {
this.options.doneRendering.apply(this, []);
}
};
Clndr.prototype.bindEvents = function () {
var data = {},
self = this,
$container = $(this.element),
targets = this.options.targets,
classes = self.options.classes,
eventType = (this.options.useTouchEvents === true)
? 'touchstart'
: 'click',
eventName = eventType + '.clndr';
// Make sure we don't already have events
$container
.off(eventName, '.' + targets.day)
.off(eventName, '.' + targets.empty)
.off(eventName, '.' + targets.nextButton)
.off(eventName, '.' + targets.todayButton)
.off(eventName, '.' + targets.previousButton)
.off(eventName, '.' + targets.nextYearButton)
.off(eventName, '.' + targets.previousYearButton);
// Target the day elements and give them click events
$container.on(eventName, '.' + targets.day, function (event) {
var target,
$currentTarget = $(event.currentTarget);
if (self.options.clickEvents.click) {
target = self.buildTargetObject(event.currentTarget, true);
self.options.clickEvents.click.apply(self, [target]);
}
// If adjacentDaysChangeMonth is on, we need to change the
// month here.
if (self.options.adjacentDaysChangeMonth) {
if ($currentTarget.is('.' + classes.lastMonth)) {
self.backActionWithContext(self);
}
else if ($currentTarget.is('.' + classes.nextMonth)) {
self.forwardActionWithContext(self);
}
}
// if trackSelectedDate is on, we need to handle click on a new day
if (self.options.trackSelectedDate) {
if (self.options.ignoreInactiveDaysInSelection
&& $currentTarget.hasClass(classes.inactive))
{
return;
}
// Remember new selected date
self.options.selectedDate =
self.getTargetDateString(event.currentTarget);
// Handle "selected" class. This handles more complex templates
// that may have the selected elements nested.
$container.find('.' + classes.selected)
.removeClass(classes.selected);
$currentTarget.addClass(classes.selected);
}
});
// Target the empty calendar boxes as well
$container.on(eventName, '.' + targets.empty, function (event) {
var target,
$eventTarget = $(event.currentTarget);
if (self.options.clickEvents.click) {
target = self.buildTargetObject(event.currentTarget, false);
self.options.clickEvents.click.apply(self, [target]);
}
if (self.options.adjacentDaysChangeMonth) {
if ($eventTarget.is('.' + classes.lastMonth)) {
self.backActionWithContext(self);
}
else if ($eventTarget.is('.' + classes.nextMonth)) {
self.forwardActionWithContext(self);
}
}
});
// Bind the previous, next and today buttons. We pass the current
// context along with the event so that it can update this instance.
data = {
context: this
};
$container
.on(eventName, '.' + targets.todayButton, data, this.todayAction)
.on(eventName, '.' + targets.nextButton, data, this.forwardAction)
.on(eventName, '.' + targets.previousButton, data, this.backAction)
.on(eventName, '.' + targets.nextYearButton, data, this.nextYearAction)
.on(eventName, '.' + targets.previousYearButton, data, this.previousYearAction);
};
/**
* If the user provided a click callback we'd like to give them something
* nice to work with. buildTargetObject takes the DOM element that was
* clicked and returns an object with the DOM element, events, and the date
* (if the latter two exist). Currently it is based on the id, however it'd
* be nice to use a data- attribute in the future.
*/
Clndr.prototype.buildTargetObject = function (currentTarget, targetWasDay) {
// This is our default target object, assuming we hit an empty day
// with no events.
var target = {
date: null,
events: [],
element: currentTarget
};
var dateString, filterFn;
// Did we click on a day or just an empty box?
if (targetWasDay) {
dateString = this.getTargetDateString(currentTarget);
target.date = (dateString)
? moment(dateString)
: null;