Calendar.js
21 KB
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
var Calendar = fc.Calendar = fc.CalendarBase = Class.extend({
dirDefaults: null, // option defaults related to LTR or RTL
langDefaults: null, // option defaults related to current locale
overrides: null, // option overrides given to the fullCalendar constructor
options: null, // all defaults combined with overrides
viewSpecCache: null, // cache of view definitions
view: null, // current View object
header: null,
// a lot of this class' OOP logic is scoped within this constructor function,
// but in the future, write individual methods on the prototype.
constructor: Calendar_constructor,
// Initializes `this.options` and other important options-related objects
initOptions: function(overrides) {
var lang, langDefaults;
var isRTL, dirDefaults;
// converts legacy options into non-legacy ones.
// in the future, when this is removed, don't use `overrides` reference. make a copy.
overrides = massageOverrides(overrides);
lang = overrides.lang;
langDefaults = langOptionHash[lang];
if (!langDefaults) {
lang = Calendar.defaults.lang;
langDefaults = langOptionHash[lang] || {};
}
isRTL = firstDefined(
overrides.isRTL,
langDefaults.isRTL,
Calendar.defaults.isRTL
);
dirDefaults = isRTL ? Calendar.rtlDefaults : {};
this.dirDefaults = dirDefaults;
this.langDefaults = langDefaults;
this.overrides = overrides;
this.options = mergeOptions( // merge defaults and overrides. lowest to highest precedence
Calendar.defaults, // global defaults
dirDefaults,
langDefaults,
overrides
);
populateInstanceComputableOptions(this.options);
this.viewSpecCache = {}; // somewhat unrelated
},
// Gets information about how to create a view. Will use a cache.
getViewSpec: function(viewType) {
var cache = this.viewSpecCache;
return cache[viewType] || (cache[viewType] = this.buildViewSpec(viewType));
},
// Given a duration singular unit, like "week" or "day", finds a matching view spec.
// Preference is given to views that have corresponding buttons.
getUnitViewSpec: function(unit) {
var viewTypes;
var i;
var spec;
if ($.inArray(unit, intervalUnits) != -1) {
// put views that have buttons first. there will be duplicates, but oh well
viewTypes = this.header.getViewsWithButtons();
$.each(fc.views, function(viewType) { // all views
viewTypes.push(viewType);
});
for (i = 0; i < viewTypes.length; i++) {
spec = this.getViewSpec(viewTypes[i]);
if (spec) {
if (spec.singleUnit == unit) {
return spec;
}
}
}
}
},
// Builds an object with information on how to create a given view
buildViewSpec: function(requestedViewType) {
var viewOverrides = this.overrides.views || {};
var defaultsChain = []; // for the view. lowest to highest priority
var overridesChain = []; // for the view. lowest to highest priority
var viewType = requestedViewType;
var viewClass;
var defaults; // for the view
var overrides; // for the view
var duration;
var unit;
var spec;
// iterate from the specific view definition to a more general one until we hit an actual View class
while (viewType && !viewClass) {
defaults = fcViews[viewType] || {};
overrides = viewOverrides[viewType] || {};
duration = duration || overrides.duration || defaults.duration;
viewType = overrides.type || defaults.type; // for next iteration
if (typeof defaults === 'function') { // a class
viewClass = defaults;
defaultsChain.unshift(viewClass.defaults || {});
}
else { // an options object
defaultsChain.unshift(defaults);
}
overridesChain.unshift(overrides);
}
if (viewClass) {
spec = { 'class': viewClass, type: requestedViewType };
if (duration) {
duration = moment.duration(duration);
if (!duration.valueOf()) { // invalid?
duration = null;
}
}
if (duration) {
spec.duration = duration;
unit = computeIntervalUnit(duration);
// view is a single-unit duration, like "week" or "day"
// incorporate options for this. lowest priority
if (duration.as(unit) === 1) {
spec.singleUnit = unit;
overridesChain.unshift(viewOverrides[unit] || {});
}
}
// collapse into single objects
spec.defaults = mergeOptions.apply(null, defaultsChain);
spec.overrides = mergeOptions.apply(null, overridesChain);
this.buildViewSpecOptions(spec);
this.buildViewSpecButtonText(spec, requestedViewType);
return spec;
}
},
// Builds and assigns a view spec's options object from its already-assigned defaults and overrides
buildViewSpecOptions: function(spec) {
spec.options = mergeOptions( // lowest to highest priority
Calendar.defaults, // global defaults
spec.defaults, // view's defaults (from ViewSubclass.defaults)
this.dirDefaults,
this.langDefaults, // locale and dir take precedence over view's defaults!
this.overrides, // calendar's overrides (options given to constructor)
spec.overrides // view's overrides (view-specific options)
);
populateInstanceComputableOptions(spec.options);
},
// Computes and assigns a view spec's buttonText-related options
buildViewSpecButtonText: function(spec, requestedViewType) {
// given an options object with a possible `buttonText` hash, lookup the buttonText for the
// requested view, falling back to a generic unit entry like "week" or "day"
function queryButtonText(options) {
var buttonText = options.buttonText || {};
return buttonText[requestedViewType] ||
(spec.singleUnit ? buttonText[spec.singleUnit] : null);
}
// highest to lowest priority
spec.buttonTextOverride =
queryButtonText(this.overrides) || // constructor-specified buttonText lookup hash takes precedence
spec.overrides.buttonText; // `buttonText` for view-specific options is a string
// highest to lowest priority. mirrors buildViewSpecOptions
spec.buttonTextDefault =
queryButtonText(this.langDefaults) ||
queryButtonText(this.dirDefaults) ||
spec.defaults.buttonText || // a single string. from ViewSubclass.defaults
queryButtonText(Calendar.defaults) ||
(spec.duration ? this.humanizeDuration(spec.duration) : null) || // like "3 days"
requestedViewType; // fall back to given view name
},
// Given a view name for a custom view or a standard view, creates a ready-to-go View object
instantiateView: function(viewType) {
var spec = this.getViewSpec(viewType);
return new spec['class'](this, viewType, spec.options, spec.duration);
},
// Returns a boolean about whether the view is okay to instantiate at some point
isValidViewType: function(viewType) {
return Boolean(this.getViewSpec(viewType));
}
});
function Calendar_constructor(element, overrides) {
var t = this;
t.initOptions(overrides || {});
var options = this.options;
// Exports
// -----------------------------------------------------------------------------------
t.render = render;
t.destroy = destroy;
t.refetchEvents = refetchEvents;
t.reportEvents = reportEvents;
t.reportEventChange = reportEventChange;
t.rerenderEvents = renderEvents; // `renderEvents` serves as a rerender. an API method
t.changeView = renderView; // `renderView` will switch to another view
t.select = select;
t.unselect = unselect;
t.prev = prev;
t.next = next;
t.prevYear = prevYear;
t.nextYear = nextYear;
t.today = today;
t.gotoDate = gotoDate;
t.incrementDate = incrementDate;
t.zoomTo = zoomTo;
t.getDate = getDate;
t.getCalendar = getCalendar;
t.getView = getView;
t.option = option;
t.trigger = trigger;
// Language-data Internals
// -----------------------------------------------------------------------------------
// Apply overrides to the current language's data
var localeData = createObject( // make a cheap copy
getMomentLocaleData(options.lang) // will fall back to en
);
if (options.monthNames) {
localeData._months = options.monthNames;
}
if (options.monthNamesShort) {
localeData._monthsShort = options.monthNamesShort;
}
if (options.dayNames) {
localeData._weekdays = options.dayNames;
}
if (options.dayNamesShort) {
localeData._weekdaysShort = options.dayNamesShort;
}
if (options.firstDay != null) {
var _week = createObject(localeData._week); // _week: { dow: # }
_week.dow = options.firstDay;
localeData._week = _week;
}
// assign a normalized value, to be used by our .week() moment extension
localeData._fullCalendar_weekCalc = (function(weekCalc) {
if (typeof weekCalc === 'function') {
return weekCalc;
}
else if (weekCalc === 'local') {
return weekCalc;
}
else if (weekCalc === 'iso' || weekCalc === 'ISO') {
return 'ISO';
}
})(options.weekNumberCalculation);
// Calendar-specific Date Utilities
// -----------------------------------------------------------------------------------
t.defaultAllDayEventDuration = moment.duration(options.defaultAllDayEventDuration);
t.defaultTimedEventDuration = moment.duration(options.defaultTimedEventDuration);
// Builds a moment using the settings of the current calendar: timezone and language.
// Accepts anything the vanilla moment() constructor accepts.
t.moment = function() {
var mom;
if (options.timezone === 'local') {
mom = fc.moment.apply(null, arguments);
// Force the moment to be local, because fc.moment doesn't guarantee it.
if (mom.hasTime()) { // don't give ambiguously-timed moments a local zone
mom.local();
}
}
else if (options.timezone === 'UTC') {
mom = fc.moment.utc.apply(null, arguments); // process as UTC
}
else {
mom = fc.moment.parseZone.apply(null, arguments); // let the input decide the zone
}
if ('_locale' in mom) { // moment 2.8 and above
mom._locale = localeData;
}
else { // pre-moment-2.8
mom._lang = localeData;
}
return mom;
};
// Returns a boolean about whether or not the calendar knows how to calculate
// the timezone offset of arbitrary dates in the current timezone.
t.getIsAmbigTimezone = function() {
return options.timezone !== 'local' && options.timezone !== 'UTC';
};
// Returns a copy of the given date in the current timezone of it is ambiguously zoned.
// This will also give the date an unambiguous time.
t.rezoneDate = function(date) {
return t.moment(date.toArray());
};
// Returns a moment for the current date, as defined by the client's computer,
// or overridden by the `now` option.
t.getNow = function() {
var now = options.now;
if (typeof now === 'function') {
now = now();
}
return t.moment(now);
};
// Get an event's normalized end date. If not present, calculate it from the defaults.
t.getEventEnd = function(event) {
if (event.end) {
return event.end.clone();
}
else {
return t.getDefaultEventEnd(event.allDay, event.start);
}
};
// Given an event's allDay status and start date, return swhat its fallback end date should be.
t.getDefaultEventEnd = function(allDay, start) { // TODO: rename to computeDefaultEventEnd
var end = start.clone();
if (allDay) {
end.stripTime().add(t.defaultAllDayEventDuration);
}
else {
end.add(t.defaultTimedEventDuration);
}
if (t.getIsAmbigTimezone()) {
end.stripZone(); // we don't know what the tzo should be
}
return end;
};
// Produces a human-readable string for the given duration.
// Side-effect: changes the locale of the given duration.
t.humanizeDuration = function(duration) {
return (duration.locale || duration.lang).call(duration, options.lang) // works moment-pre-2.8
.humanize();
};
// Imports
// -----------------------------------------------------------------------------------
EventManager.call(t, options);
var isFetchNeeded = t.isFetchNeeded;
var fetchEvents = t.fetchEvents;
// Locals
// -----------------------------------------------------------------------------------
var _element = element[0];
var header;
var headerElement;
var content;
var tm; // for making theme classes
var currentView; // NOTE: keep this in sync with this.view
var viewsByType = {}; // holds all instantiated view instances, current or not
var suggestedViewHeight;
var windowResizeProxy; // wraps the windowResize function
var ignoreWindowResize = 0;
var date;
var events = [];
// Main Rendering
// -----------------------------------------------------------------------------------
if (options.defaultDate != null) {
date = t.moment(options.defaultDate);
}
else {
date = t.getNow();
}
function render() {
if (!content) {
initialRender();
}
else if (elementVisible()) {
// mainly for the public API
calcSize();
renderView();
}
}
function initialRender() {
tm = options.theme ? 'ui' : 'fc';
element.addClass('fc');
if (options.isRTL) {
element.addClass('fc-rtl');
}
else {
element.addClass('fc-ltr');
}
if (options.theme) {
element.addClass('ui-widget');
}
else {
element.addClass('fc-unthemed');
}
content = $("<div class='fc-view-container'/>").prependTo(element);
header = t.header = new Header(t, options);
headerElement = header.render();
if (headerElement) {
element.prepend(headerElement);
}
renderView(options.defaultView);
if (options.handleWindowResize) {
windowResizeProxy = debounce(windowResize, options.windowResizeDelay); // prevents rapid calls
$(window).resize(windowResizeProxy);
}
}
function destroy() {
if (currentView) {
currentView.removeElement();
// NOTE: don't null-out currentView/t.view in case API methods are called after destroy.
// It is still the "current" view, just not rendered.
}
header.destroy();
content.remove();
element.removeClass('fc fc-ltr fc-rtl fc-unthemed ui-widget');
if (windowResizeProxy) {
$(window).unbind('resize', windowResizeProxy);
}
}
function elementVisible() {
return element.is(':visible');
}
// View Rendering
// -----------------------------------------------------------------------------------
// Renders a view because of a date change, view-type change, or for the first time.
// If not given a viewType, keep the current view but render different dates.
function renderView(viewType) {
ignoreWindowResize++;
// if viewType is changing, destroy the old view
if (currentView && viewType && currentView.type !== viewType) {
header.deactivateButton(currentView.type);
freezeContentHeight(); // prevent a scroll jump when view element is removed
currentView.removeElement();
currentView = t.view = null;
}
// if viewType changed, or the view was never created, create a fresh view
if (!currentView && viewType) {
currentView = t.view =
viewsByType[viewType] ||
(viewsByType[viewType] = t.instantiateView(viewType));
currentView.setElement(
$("<div class='fc-view fc-" + viewType + "-view' />").appendTo(content)
);
header.activateButton(viewType);
}
if (currentView) {
// in case the view should render a period of time that is completely hidden
date = currentView.massageCurrentDate(date);
// render or rerender the view
if (
!currentView.isDisplayed ||
!date.isWithin(currentView.intervalStart, currentView.intervalEnd) // implicit date window change
) {
if (elementVisible()) {
freezeContentHeight();
currentView.display(date);
unfreezeContentHeight();
// need to do this after View::render, so dates are calculated
updateHeaderTitle();
updateTodayButton();
getAndRenderEvents();
}
}
}
unfreezeContentHeight(); // undo any lone freezeContentHeight calls
ignoreWindowResize--;
}
// Resizing
// -----------------------------------------------------------------------------------
t.getSuggestedViewHeight = function() {
if (suggestedViewHeight === undefined) {
calcSize();
}
return suggestedViewHeight;
};
t.isHeightAuto = function() {
return options.contentHeight === 'auto' || options.height === 'auto';
};
function updateSize(shouldRecalc) {
if (elementVisible()) {
if (shouldRecalc) {
_calcSize();
}
ignoreWindowResize++;
currentView.updateSize(true); // isResize=true. will poll getSuggestedViewHeight() and isHeightAuto()
ignoreWindowResize--;
return true; // signal success
}
}
function calcSize() {
if (elementVisible()) {
_calcSize();
}
}
function _calcSize() { // assumes elementVisible
if (typeof options.contentHeight === 'number') { // exists and not 'auto'
suggestedViewHeight = options.contentHeight;
}
else if (typeof options.height === 'number') { // exists and not 'auto'
suggestedViewHeight = options.height - (headerElement ? headerElement.outerHeight(true) : 0);
}
else {
suggestedViewHeight = Math.round(content.width() / Math.max(options.aspectRatio, .5));
}
}
function windowResize(ev) {
if (
!ignoreWindowResize &&
ev.target === window && // so we don't process jqui "resize" events that have bubbled up
currentView.start // view has already been rendered
) {
if (updateSize(true)) {
currentView.trigger('windowResize', _element);
}
}
}
/* Event Fetching/Rendering
-----------------------------------------------------------------------------*/
// TODO: going forward, most of this stuff should be directly handled by the view
function refetchEvents() { // can be called as an API method
destroyEvents(); // so that events are cleared before user starts waiting for AJAX
fetchAndRenderEvents();
}
function renderEvents() { // destroys old events if previously rendered
if (elementVisible()) {
freezeContentHeight();
currentView.displayEvents(events);
unfreezeContentHeight();
}
}
function destroyEvents() {
freezeContentHeight();
currentView.clearEvents();
unfreezeContentHeight();
}
function getAndRenderEvents() {
if (!options.lazyFetching || isFetchNeeded(currentView.start, currentView.end)) {
fetchAndRenderEvents();
}
else {
renderEvents();
}
}
function fetchAndRenderEvents() {
fetchEvents(currentView.start, currentView.end);
// ... will call reportEvents
// ... which will call renderEvents
}
// called when event data arrives
function reportEvents(_events) {
events = _events;
renderEvents();
}
// called when a single event's data has been changed
function reportEventChange() {
renderEvents();
}
/* Header Updating
-----------------------------------------------------------------------------*/
function updateHeaderTitle() {
header.updateTitle(currentView.title);
}
function updateTodayButton() {
var now = t.getNow();
if (now.isWithin(currentView.intervalStart, currentView.intervalEnd)) {
header.disableButton('today');
}
else {
header.enableButton('today');
}
}
/* Selection
-----------------------------------------------------------------------------*/
function select(start, end) {
start = t.moment(start);
if (end) {
end = t.moment(end);
}
else if (start.hasTime()) {
end = start.clone().add(t.defaultTimedEventDuration);
}
else {
end = start.clone().add(t.defaultAllDayEventDuration);
}
currentView.select({ start: start, end: end }); // accepts a range
}
function unselect() { // safe to be called before renderView
if (currentView) {
currentView.unselect();
}
}
/* Date
-----------------------------------------------------------------------------*/
function prev() {
date = currentView.computePrevDate(date);
renderView();
}
function next() {
date = currentView.computeNextDate(date);
renderView();
}
function prevYear() {
date.add(-1, 'years');
renderView();
}
function nextYear() {
date.add(1, 'years');
renderView();
}
function today() {
date = t.getNow();
renderView();
}
function gotoDate(dateInput) {
date = t.moment(dateInput);
renderView();
}
function incrementDate(delta) {
date.add(moment.duration(delta));
renderView();
}
// Forces navigation to a view for the given date.
// `viewType` can be a specific view name or a generic one like "week" or "day".
function zoomTo(newDate, viewType) {
var spec;
viewType = viewType || 'day'; // day is default zoom
spec = t.getViewSpec(viewType) || t.getUnitViewSpec(viewType);
date = newDate;
renderView(spec ? spec.type : null);
}
function getDate() {
return date.clone();
}
/* Height "Freezing"
-----------------------------------------------------------------------------*/
// TODO: move this into the view
function freezeContentHeight() {
content.css({
width: '100%',
height: content.height(),
overflow: 'hidden'
});
}
function unfreezeContentHeight() {
content.css({
width: '',
height: '',
overflow: ''
});
}
/* Misc
-----------------------------------------------------------------------------*/
function getCalendar() {
return t;
}
function getView() {
return currentView;
}
function option(name, value) {
if (value === undefined) {
return options[name];
}
if (name == 'height' || name == 'contentHeight' || name == 'aspectRatio') {
options[name] = value;
updateSize(true); // true = allow recalculation of height
}
}
function trigger(name, thisObj) {
if (options[name]) {
return options[name].apply(
thisObj || _element,
Array.prototype.slice.call(arguments, 2)
);
}
}
}