better-staridc-MNBT
1/*!
2FullCalendar Core Package v4.3.1
3Docs & License: https://fullcalendar.io/
4(c) 2019 Adam Shaw
5*/
6
7// Creating
8// ----------------------------------------------------------------------------------------------------------------
9var elementPropHash = {
10 className: true,
11 colSpan: true,
12 rowSpan: true
13};
14var containerTagHash = {
15 '<tr': 'tbody',
16 '<td': 'tr'
17};
18function createElement(tagName, attrs, content) {
19 var el = document.createElement(tagName);
20 if (attrs) {
21 for (var attrName in attrs) {
22 if (attrName === 'style') {
23 applyStyle(el, attrs[attrName]);
24 }
25 else if (elementPropHash[attrName]) {
26 el[attrName] = attrs[attrName];
27 }
28 else {
29 el.setAttribute(attrName, attrs[attrName]);
30 }
31 }
32 }
33 if (typeof content === 'string') {
34 el.innerHTML = content; // shortcut. no need to process HTML in any way
35 }
36 else if (content != null) {
37 appendToElement(el, content);
38 }
39 return el;
40}
41function htmlToElement(html) {
42 html = html.trim();
43 var container = document.createElement(computeContainerTag(html));
44 container.innerHTML = html;
45 return container.firstChild;
46}
47function htmlToElements(html) {
48 return Array.prototype.slice.call(htmlToNodeList(html));
49}
50function htmlToNodeList(html) {
51 html = html.trim();
52 var container = document.createElement(computeContainerTag(html));
53 container.innerHTML = html;
54 return container.childNodes;
55}
56// assumes html already trimmed and tag names are lowercase
57function computeContainerTag(html) {
58 return containerTagHash[html.substr(0, 3) // faster than using regex
59 ] || 'div';
60}
61function appendToElement(el, content) {
62 var childNodes = normalizeContent(content);
63 for (var i = 0; i < childNodes.length; i++) {
64 el.appendChild(childNodes[i]);
65 }
66}
67function prependToElement(parent, content) {
68 var newEls = normalizeContent(content);
69 var afterEl = parent.firstChild || null; // if no firstChild, will append to end, but that's okay, b/c there were no children
70 for (var i = 0; i < newEls.length; i++) {
71 parent.insertBefore(newEls[i], afterEl);
72 }
73}
74function insertAfterElement(refEl, content) {
75 var newEls = normalizeContent(content);
76 var afterEl = refEl.nextSibling || null;
77 for (var i = 0; i < newEls.length; i++) {
78 refEl.parentNode.insertBefore(newEls[i], afterEl);
79 }
80}
81function normalizeContent(content) {
82 var els;
83 if (typeof content === 'string') {
84 els = htmlToElements(content);
85 }
86 else if (content instanceof Node) {
87 els = [content];
88 }
89 else { // Node[] or NodeList
90 els = Array.prototype.slice.call(content);
91 }
92 return els;
93}
94function removeElement(el) {
95 if (el.parentNode) {
96 el.parentNode.removeChild(el);
97 }
98}
99// Querying
100// ----------------------------------------------------------------------------------------------------------------
101// from https://developer.mozilla.org/en-US/docs/Web/API/Element/closest
102var matchesMethod = Element.prototype.matches ||
103 Element.prototype.matchesSelector ||
104 Element.prototype.msMatchesSelector;
105var closestMethod = Element.prototype.closest || function (selector) {
106 // polyfill
107 var el = this;
108 if (!document.documentElement.contains(el)) {
109 return null;
110 }
111 do {
112 if (elementMatches(el, selector)) {
113 return el;
114 }
115 el = el.parentElement || el.parentNode;
116 } while (el !== null && el.nodeType === 1);
117 return null;
118};
119function elementClosest(el, selector) {
120 return closestMethod.call(el, selector);
121}
122function elementMatches(el, selector) {
123 return matchesMethod.call(el, selector);
124}
125// accepts multiple subject els
126// returns a real array. good for methods like forEach
127function findElements(container, selector) {
128 var containers = container instanceof HTMLElement ? [container] : container;
129 var allMatches = [];
130 for (var i = 0; i < containers.length; i++) {
131 var matches = containers[i].querySelectorAll(selector);
132 for (var j = 0; j < matches.length; j++) {
133 allMatches.push(matches[j]);
134 }
135 }
136 return allMatches;
137}
138// accepts multiple subject els
139// only queries direct child elements
140function findChildren(parent, selector) {
141 var parents = parent instanceof HTMLElement ? [parent] : parent;
142 var allMatches = [];
143 for (var i = 0; i < parents.length; i++) {
144 var childNodes = parents[i].children; // only ever elements
145 for (var j = 0; j < childNodes.length; j++) {
146 var childNode = childNodes[j];
147 if (!selector || elementMatches(childNode, selector)) {
148 allMatches.push(childNode);
149 }
150 }
151 }
152 return allMatches;
153}
154// Attributes
155// ----------------------------------------------------------------------------------------------------------------
156function forceClassName(el, className, bool) {
157 if (bool) {
158 el.classList.add(className);
159 }
160 else {
161 el.classList.remove(className);
162 }
163}
164// Style
165// ----------------------------------------------------------------------------------------------------------------
166var PIXEL_PROP_RE = /(top|left|right|bottom|width|height)$/i;
167function applyStyle(el, props) {
168 for (var propName in props) {
169 applyStyleProp(el, propName, props[propName]);
170 }
171}
172function applyStyleProp(el, name, val) {
173 if (val == null) {
174 el.style[name] = '';
175 }
176 else if (typeof val === 'number' && PIXEL_PROP_RE.test(name)) {
177 el.style[name] = val + 'px';
178 }
179 else {
180 el.style[name] = val;
181 }
182}
183
184function pointInsideRect(point, rect) {
185 return point.left >= rect.left &&
186 point.left < rect.right &&
187 point.top >= rect.top &&
188 point.top < rect.bottom;
189}
190// Returns a new rectangle that is the intersection of the two rectangles. If they don't intersect, returns false
191function intersectRects(rect1, rect2) {
192 var res = {
193 left: Math.max(rect1.left, rect2.left),
194 right: Math.min(rect1.right, rect2.right),
195 top: Math.max(rect1.top, rect2.top),
196 bottom: Math.min(rect1.bottom, rect2.bottom)
197 };
198 if (res.left < res.right && res.top < res.bottom) {
199 return res;
200 }
201 return false;
202}
203function translateRect(rect, deltaX, deltaY) {
204 return {
205 left: rect.left + deltaX,
206 right: rect.right + deltaX,
207 top: rect.top + deltaY,
208 bottom: rect.bottom + deltaY
209 };
210}
211// Returns a new point that will have been moved to reside within the given rectangle
212function constrainPoint(point, rect) {
213 return {
214 left: Math.min(Math.max(point.left, rect.left), rect.right),
215 top: Math.min(Math.max(point.top, rect.top), rect.bottom)
216 };
217}
218// Returns a point that is the center of the given rectangle
219function getRectCenter(rect) {
220 return {
221 left: (rect.left + rect.right) / 2,
222 top: (rect.top + rect.bottom) / 2
223 };
224}
225// Subtracts point2's coordinates from point1's coordinates, returning a delta
226function diffPoints(point1, point2) {
227 return {
228 left: point1.left - point2.left,
229 top: point1.top - point2.top
230 };
231}
232
233// Logic for determining if, when the element is right-to-left, the scrollbar appears on the left side
234var isRtlScrollbarOnLeft = null;
235function getIsRtlScrollbarOnLeft() {
236 if (isRtlScrollbarOnLeft === null) {
237 isRtlScrollbarOnLeft = computeIsRtlScrollbarOnLeft();
238 }
239 return isRtlScrollbarOnLeft;
240}
241function computeIsRtlScrollbarOnLeft() {
242 var outerEl = createElement('div', {
243 style: {
244 position: 'absolute',
245 top: -1000,
246 left: 0,
247 border: 0,
248 padding: 0,
249 overflow: 'scroll',
250 direction: 'rtl'
251 }
252 }, '<div></div>');
253 document.body.appendChild(outerEl);
254 var innerEl = outerEl.firstChild;
255 var res = innerEl.getBoundingClientRect().left > outerEl.getBoundingClientRect().left;
256 removeElement(outerEl);
257 return res;
258}
259// The scrollbar width computations in computeEdges are sometimes flawed when it comes to
260// retina displays, rounding, and IE11. Massage them into a usable value.
261function sanitizeScrollbarWidth(width) {
262 width = Math.max(0, width); // no negatives
263 width = Math.round(width);
264 return width;
265}
266
267function computeEdges(el, getPadding) {
268 if (getPadding === void 0) { getPadding = false; }
269 var computedStyle = window.getComputedStyle(el);
270 var borderLeft = parseInt(computedStyle.borderLeftWidth, 10) || 0;
271 var borderRight = parseInt(computedStyle.borderRightWidth, 10) || 0;
272 var borderTop = parseInt(computedStyle.borderTopWidth, 10) || 0;
273 var borderBottom = parseInt(computedStyle.borderBottomWidth, 10) || 0;
274 // must use offset(Width|Height) because compatible with client(Width|Height)
275 var scrollbarLeftRight = sanitizeScrollbarWidth(el.offsetWidth - el.clientWidth - borderLeft - borderRight);
276 var scrollbarBottom = sanitizeScrollbarWidth(el.offsetHeight - el.clientHeight - borderTop - borderBottom);
277 var res = {
278 borderLeft: borderLeft,
279 borderRight: borderRight,
280 borderTop: borderTop,
281 borderBottom: borderBottom,
282 scrollbarBottom: scrollbarBottom,
283 scrollbarLeft: 0,
284 scrollbarRight: 0
285 };
286 if (getIsRtlScrollbarOnLeft() && computedStyle.direction === 'rtl') { // is the scrollbar on the left side?
287 res.scrollbarLeft = scrollbarLeftRight;
288 }
289 else {
290 res.scrollbarRight = scrollbarLeftRight;
291 }
292 if (getPadding) {
293 res.paddingLeft = parseInt(computedStyle.paddingLeft, 10) || 0;
294 res.paddingRight = parseInt(computedStyle.paddingRight, 10) || 0;
295 res.paddingTop = parseInt(computedStyle.paddingTop, 10) || 0;
296 res.paddingBottom = parseInt(computedStyle.paddingBottom, 10) || 0;
297 }
298 return res;
299}
300function computeInnerRect(el, goWithinPadding) {
301 if (goWithinPadding === void 0) { goWithinPadding = false; }
302 var outerRect = computeRect(el);
303 var edges = computeEdges(el, goWithinPadding);
304 var res = {
305 left: outerRect.left + edges.borderLeft + edges.scrollbarLeft,
306 right: outerRect.right - edges.borderRight - edges.scrollbarRight,
307 top: outerRect.top + edges.borderTop,
308 bottom: outerRect.bottom - edges.borderBottom - edges.scrollbarBottom
309 };
310 if (goWithinPadding) {
311 res.left += edges.paddingLeft;
312 res.right -= edges.paddingRight;
313 res.top += edges.paddingTop;
314 res.bottom -= edges.paddingBottom;
315 }
316 return res;
317}
318function computeRect(el) {
319 var rect = el.getBoundingClientRect();
320 return {
321 left: rect.left + window.pageXOffset,
322 top: rect.top + window.pageYOffset,
323 right: rect.right + window.pageXOffset,
324 bottom: rect.bottom + window.pageYOffset
325 };
326}
327function computeViewportRect() {
328 return {
329 left: window.pageXOffset,
330 right: window.pageXOffset + document.documentElement.clientWidth,
331 top: window.pageYOffset,
332 bottom: window.pageYOffset + document.documentElement.clientHeight
333 };
334}
335function computeHeightAndMargins(el) {
336 return el.getBoundingClientRect().height + computeVMargins(el);
337}
338function computeVMargins(el) {
339 var computed = window.getComputedStyle(el);
340 return parseInt(computed.marginTop, 10) +
341 parseInt(computed.marginBottom, 10);
342}
343// does not return window
344function getClippingParents(el) {
345 var parents = [];
346 while (el instanceof HTMLElement) { // will stop when gets to document or null
347 var computedStyle = window.getComputedStyle(el);
348 if (computedStyle.position === 'fixed') {
349 break;
350 }
351 if ((/(auto|scroll)/).test(computedStyle.overflow + computedStyle.overflowY + computedStyle.overflowX)) {
352 parents.push(el);
353 }
354 el = el.parentNode;
355 }
356 return parents;
357}
358function computeClippingRect(el) {
359 return getClippingParents(el)
360 .map(function (el) {
361 return computeInnerRect(el);
362 })
363 .concat(computeViewportRect())
364 .reduce(function (rect0, rect1) {
365 return intersectRects(rect0, rect1) || rect1; // should always intersect
366 });
367}
368
369// Stops a mouse/touch event from doing it's native browser action
370function preventDefault(ev) {
371 ev.preventDefault();
372}
373// Event Delegation
374// ----------------------------------------------------------------------------------------------------------------
375function listenBySelector(container, eventType, selector, handler) {
376 function realHandler(ev) {
377 var matchedChild = elementClosest(ev.target, selector);
378 if (matchedChild) {
379 handler.call(matchedChild, ev, matchedChild);
380 }
381 }
382 container.addEventListener(eventType, realHandler);
383 return function () {
384 container.removeEventListener(eventType, realHandler);
385 };
386}
387function listenToHoverBySelector(container, selector, onMouseEnter, onMouseLeave) {
388 var currentMatchedChild;
389 return listenBySelector(container, 'mouseover', selector, function (ev, matchedChild) {
390 if (matchedChild !== currentMatchedChild) {
391 currentMatchedChild = matchedChild;
392 onMouseEnter(ev, matchedChild);
393 var realOnMouseLeave_1 = function (ev) {
394 currentMatchedChild = null;
395 onMouseLeave(ev, matchedChild);
396 matchedChild.removeEventListener('mouseleave', realOnMouseLeave_1);
397 };
398 // listen to the next mouseleave, and then unattach
399 matchedChild.addEventListener('mouseleave', realOnMouseLeave_1);
400 }
401 });
402}
403// Animation
404// ----------------------------------------------------------------------------------------------------------------
405var transitionEventNames = [
406 'webkitTransitionEnd',
407 'otransitionend',
408 'oTransitionEnd',
409 'msTransitionEnd',
410 'transitionend'
411];
412// triggered only when the next single subsequent transition finishes
413function whenTransitionDone(el, callback) {
414 var realCallback = function (ev) {
415 callback(ev);
416 transitionEventNames.forEach(function (eventName) {
417 el.removeEventListener(eventName, realCallback);
418 });
419 };
420 transitionEventNames.forEach(function (eventName) {
421 el.addEventListener(eventName, realCallback); // cross-browser way to determine when the transition finishes
422 });
423}
424
425var DAY_IDS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
426// Adding
427function addWeeks(m, n) {
428 var a = dateToUtcArray(m);
429 a[2] += n * 7;
430 return arrayToUtcDate(a);
431}
432function addDays(m, n) {
433 var a = dateToUtcArray(m);
434 a[2] += n;
435 return arrayToUtcDate(a);
436}
437function addMs(m, n) {
438 var a = dateToUtcArray(m);
439 a[6] += n;
440 return arrayToUtcDate(a);
441}
442// Diffing (all return floats)
443function diffWeeks(m0, m1) {
444 return diffDays(m0, m1) / 7;
445}
446function diffDays(m0, m1) {
447 return (m1.valueOf() - m0.valueOf()) / (1000 * 60 * 60 * 24);
448}
449function diffHours(m0, m1) {
450 return (m1.valueOf() - m0.valueOf()) / (1000 * 60 * 60);
451}
452function diffMinutes(m0, m1) {
453 return (m1.valueOf() - m0.valueOf()) / (1000 * 60);
454}
455function diffSeconds(m0, m1) {
456 return (m1.valueOf() - m0.valueOf()) / 1000;
457}
458function diffDayAndTime(m0, m1) {
459 var m0day = startOfDay(m0);
460 var m1day = startOfDay(m1);
461 return {
462 years: 0,
463 months: 0,
464 days: Math.round(diffDays(m0day, m1day)),
465 milliseconds: (m1.valueOf() - m1day.valueOf()) - (m0.valueOf() - m0day.valueOf())
466 };
467}
468// Diffing Whole Units
469function diffWholeWeeks(m0, m1) {
470 var d = diffWholeDays(m0, m1);
471 if (d !== null && d % 7 === 0) {
472 return d / 7;
473 }
474 return null;
475}
476function diffWholeDays(m0, m1) {
477 if (timeAsMs(m0) === timeAsMs(m1)) {
478 return Math.round(diffDays(m0, m1));
479 }
480 return null;
481}
482// Start-Of
483function startOfDay(m) {
484 return arrayToUtcDate([
485 m.getUTCFullYear(),
486 m.getUTCMonth(),
487 m.getUTCDate()
488 ]);
489}
490function startOfHour(m) {
491 return arrayToUtcDate([
492 m.getUTCFullYear(),
493 m.getUTCMonth(),
494 m.getUTCDate(),
495 m.getUTCHours()
496 ]);
497}
498function startOfMinute(m) {
499 return arrayToUtcDate([
500 m.getUTCFullYear(),
501 m.getUTCMonth(),
502 m.getUTCDate(),
503 m.getUTCHours(),
504 m.getUTCMinutes()
505 ]);
506}
507function startOfSecond(m) {
508 return arrayToUtcDate([
509 m.getUTCFullYear(),
510 m.getUTCMonth(),
511 m.getUTCDate(),
512 m.getUTCHours(),
513 m.getUTCMinutes(),
514 m.getUTCSeconds()
515 ]);
516}
517// Week Computation
518function weekOfYear(marker, dow, doy) {
519 var y = marker.getUTCFullYear();
520 var w = weekOfGivenYear(marker, y, dow, doy);
521 if (w < 1) {
522 return weekOfGivenYear(marker, y - 1, dow, doy);
523 }
524 var nextW = weekOfGivenYear(marker, y + 1, dow, doy);
525 if (nextW >= 1) {
526 return Math.min(w, nextW);
527 }
528 return w;
529}
530function weekOfGivenYear(marker, year, dow, doy) {
531 var firstWeekStart = arrayToUtcDate([year, 0, 1 + firstWeekOffset(year, dow, doy)]);
532 var dayStart = startOfDay(marker);
533 var days = Math.round(diffDays(firstWeekStart, dayStart));
534 return Math.floor(days / 7) + 1; // zero-indexed
535}
536// start-of-first-week - start-of-year
537function firstWeekOffset(year, dow, doy) {
538 // first-week day -- which january is always in the first week (4 for iso, 1 for other)
539 var fwd = 7 + dow - doy;
540 // first-week day local weekday -- which local weekday is fwd
541 var fwdlw = (7 + arrayToUtcDate([year, 0, fwd]).getUTCDay() - dow) % 7;
542 return -fwdlw + fwd - 1;
543}
544// Array Conversion
545function dateToLocalArray(date) {
546 return [
547 date.getFullYear(),
548 date.getMonth(),
549 date.getDate(),
550 date.getHours(),
551 date.getMinutes(),
552 date.getSeconds(),
553 date.getMilliseconds()
554 ];
555}
556function arrayToLocalDate(a) {
557 return new Date(a[0], a[1] || 0, a[2] == null ? 1 : a[2], // day of month
558 a[3] || 0, a[4] || 0, a[5] || 0);
559}
560function dateToUtcArray(date) {
561 return [
562 date.getUTCFullYear(),
563 date.getUTCMonth(),
564 date.getUTCDate(),
565 date.getUTCHours(),
566 date.getUTCMinutes(),
567 date.getUTCSeconds(),
568 date.getUTCMilliseconds()
569 ];
570}
571function arrayToUtcDate(a) {
572 // according to web standards (and Safari), a month index is required.
573 // massage if only given a year.
574 if (a.length === 1) {
575 a = a.concat([0]);
576 }
577 return new Date(Date.UTC.apply(Date, a));
578}
579// Other Utils
580function isValidDate(m) {
581 return !isNaN(m.valueOf());
582}
583function timeAsMs(m) {
584 return m.getUTCHours() * 1000 * 60 * 60 +
585 m.getUTCMinutes() * 1000 * 60 +
586 m.getUTCSeconds() * 1000 +
587 m.getUTCMilliseconds();
588}
589
590var INTERNAL_UNITS = ['years', 'months', 'days', 'milliseconds'];
591var PARSE_RE = /^(-?)(?:(\d+)\.)?(\d+):(\d\d)(?::(\d\d)(?:\.(\d\d\d))?)?/;
592// Parsing and Creation
593function createDuration(input, unit) {
594 var _a;
595 if (typeof input === 'string') {
596 return parseString(input);
597 }
598 else if (typeof input === 'object' && input) { // non-null object
599 return normalizeObject(input);
600 }
601 else if (typeof input === 'number') {
602 return normalizeObject((_a = {}, _a[unit || 'milliseconds'] = input, _a));
603 }
604 else {
605 return null;
606 }
607}
608function parseString(s) {
609 var m = PARSE_RE.exec(s);
610 if (m) {
611 var sign = m[1] ? -1 : 1;
612 return {
613 years: 0,
614 months: 0,
615 days: sign * (m[2] ? parseInt(m[2], 10) : 0),
616 milliseconds: sign * ((m[3] ? parseInt(m[3], 10) : 0) * 60 * 60 * 1000 + // hours
617 (m[4] ? parseInt(m[4], 10) : 0) * 60 * 1000 + // minutes
618 (m[5] ? parseInt(m[5], 10) : 0) * 1000 + // seconds
619 (m[6] ? parseInt(m[6], 10) : 0) // ms
620 )
621 };
622 }
623 return null;
624}
625function normalizeObject(obj) {
626 return {
627 years: obj.years || obj.year || 0,
628 months: obj.months || obj.month || 0,
629 days: (obj.days || obj.day || 0) +
630 getWeeksFromInput(obj) * 7,
631 milliseconds: (obj.hours || obj.hour || 0) * 60 * 60 * 1000 + // hours
632 (obj.minutes || obj.minute || 0) * 60 * 1000 + // minutes
633 (obj.seconds || obj.second || 0) * 1000 + // seconds
634 (obj.milliseconds || obj.millisecond || obj.ms || 0) // ms
635 };
636}
637function getWeeksFromInput(obj) {
638 return obj.weeks || obj.week || 0;
639}
640// Equality
641function durationsEqual(d0, d1) {
642 return d0.years === d1.years &&
643 d0.months === d1.months &&
644 d0.days === d1.days &&
645 d0.milliseconds === d1.milliseconds;
646}
647function isSingleDay(dur) {
648 return dur.years === 0 && dur.months === 0 && dur.days === 1 && dur.milliseconds === 0;
649}
650// Simple Math
651function addDurations(d0, d1) {
652 return {
653 years: d0.years + d1.years,
654 months: d0.months + d1.months,
655 days: d0.days + d1.days,
656 milliseconds: d0.milliseconds + d1.milliseconds
657 };
658}
659function subtractDurations(d1, d0) {
660 return {
661 years: d1.years - d0.years,
662 months: d1.months - d0.months,
663 days: d1.days - d0.days,
664 milliseconds: d1.milliseconds - d0.milliseconds
665 };
666}
667function multiplyDuration(d, n) {
668 return {
669 years: d.years * n,
670 months: d.months * n,
671 days: d.days * n,
672 milliseconds: d.milliseconds * n
673 };
674}
675// Conversions
676// "Rough" because they are based on average-case Gregorian months/years
677function asRoughYears(dur) {
678 return asRoughDays(dur) / 365;
679}
680function asRoughMonths(dur) {
681 return asRoughDays(dur) / 30;
682}
683function asRoughDays(dur) {
684 return asRoughMs(dur) / 864e5;
685}
686function asRoughMinutes(dur) {
687 return asRoughMs(dur) / (1000 * 60);
688}
689function asRoughSeconds(dur) {
690 return asRoughMs(dur) / 1000;
691}
692function asRoughMs(dur) {
693 return dur.years * (365 * 864e5) +
694 dur.months * (30 * 864e5) +
695 dur.days * 864e5 +
696 dur.milliseconds;
697}
698// Advanced Math
699function wholeDivideDurations(numerator, denominator) {
700 var res = null;
701 for (var i = 0; i < INTERNAL_UNITS.length; i++) {
702 var unit = INTERNAL_UNITS[i];
703 if (denominator[unit]) {
704 var localRes = numerator[unit] / denominator[unit];
705 if (!isInt(localRes) || (res !== null && res !== localRes)) {
706 return null;
707 }
708 res = localRes;
709 }
710 else if (numerator[unit]) {
711 // needs to divide by something but can't!
712 return null;
713 }
714 }
715 return res;
716}
717function greatestDurationDenominator(dur, dontReturnWeeks) {
718 var ms = dur.milliseconds;
719 if (ms) {
720 if (ms % 1000 !== 0) {
721 return { unit: 'millisecond', value: ms };
722 }
723 if (ms % (1000 * 60) !== 0) {
724 return { unit: 'second', value: ms / 1000 };
725 }
726 if (ms % (1000 * 60 * 60) !== 0) {
727 return { unit: 'minute', value: ms / (1000 * 60) };
728 }
729 if (ms) {
730 return { unit: 'hour', value: ms / (1000 * 60 * 60) };
731 }
732 }
733 if (dur.days) {
734 if (!dontReturnWeeks && dur.days % 7 === 0) {
735 return { unit: 'week', value: dur.days / 7 };
736 }
737 return { unit: 'day', value: dur.days };
738 }
739 if (dur.months) {
740 return { unit: 'month', value: dur.months };
741 }
742 if (dur.years) {
743 return { unit: 'year', value: dur.years };
744 }
745 return { unit: 'millisecond', value: 0 };
746}
747
748/* FullCalendar-specific DOM Utilities
749----------------------------------------------------------------------------------------------------------------------*/
750// Given the scrollbar widths of some other container, create borders/margins on rowEls in order to match the left
751// and right space that was offset by the scrollbars. A 1-pixel border first, then margin beyond that.
752function compensateScroll(rowEl, scrollbarWidths) {
753 if (scrollbarWidths.left) {
754 applyStyle(rowEl, {
755 borderLeftWidth: 1,
756 marginLeft: scrollbarWidths.left - 1
757 });
758 }
759 if (scrollbarWidths.right) {
760 applyStyle(rowEl, {
761 borderRightWidth: 1,
762 marginRight: scrollbarWidths.right - 1
763 });
764 }
765}
766// Undoes compensateScroll and restores all borders/margins
767function uncompensateScroll(rowEl) {
768 applyStyle(rowEl, {
769 marginLeft: '',
770 marginRight: '',
771 borderLeftWidth: '',
772 borderRightWidth: ''
773 });
774}
775// Make the mouse cursor express that an event is not allowed in the current area
776function disableCursor() {
777 document.body.classList.add('fc-not-allowed');
778}
779// Returns the mouse cursor to its original look
780function enableCursor() {
781 document.body.classList.remove('fc-not-allowed');
782}
783// Given a total available height to fill, have `els` (essentially child rows) expand to accomodate.
784// By default, all elements that are shorter than the recommended height are expanded uniformly, not considering
785// any other els that are already too tall. if `shouldRedistribute` is on, it considers these tall rows and
786// reduces the available height.
787function distributeHeight(els, availableHeight, shouldRedistribute) {
788 // *FLOORING NOTE*: we floor in certain places because zoom can give inaccurate floating-point dimensions,
789 // and it is better to be shorter than taller, to avoid creating unnecessary scrollbars.
790 var minOffset1 = Math.floor(availableHeight / els.length); // for non-last element
791 var minOffset2 = Math.floor(availableHeight - minOffset1 * (els.length - 1)); // for last element *FLOORING NOTE*
792 var flexEls = []; // elements that are allowed to expand. array of DOM nodes
793 var flexOffsets = []; // amount of vertical space it takes up
794 var flexHeights = []; // actual css height
795 var usedHeight = 0;
796 undistributeHeight(els); // give all elements their natural height
797 // find elements that are below the recommended height (expandable).
798 // important to query for heights in a single first pass (to avoid reflow oscillation).
799 els.forEach(function (el, i) {
800 var minOffset = i === els.length - 1 ? minOffset2 : minOffset1;
801 var naturalHeight = el.getBoundingClientRect().height;
802 var naturalOffset = naturalHeight + computeVMargins(el);
803 if (naturalOffset < minOffset) {
804 flexEls.push(el);
805 flexOffsets.push(naturalOffset);
806 flexHeights.push(naturalHeight);
807 }
808 else {
809 // this element stretches past recommended height (non-expandable). mark the space as occupied.
810 usedHeight += naturalOffset;
811 }
812 });
813 // readjust the recommended height to only consider the height available to non-maxed-out rows.
814 if (shouldRedistribute) {
815 availableHeight -= usedHeight;
816 minOffset1 = Math.floor(availableHeight / flexEls.length);
817 minOffset2 = Math.floor(availableHeight - minOffset1 * (flexEls.length - 1)); // *FLOORING NOTE*
818 }
819 // assign heights to all expandable elements
820 flexEls.forEach(function (el, i) {
821 var minOffset = i === flexEls.length - 1 ? minOffset2 : minOffset1;
822 var naturalOffset = flexOffsets[i];
823 var naturalHeight = flexHeights[i];
824 var newHeight = minOffset - (naturalOffset - naturalHeight); // subtract the margin/padding
825 if (naturalOffset < minOffset) { // we check this again because redistribution might have changed things
826 el.style.height = newHeight + 'px';
827 }
828 });
829}
830// Undoes distrubuteHeight, restoring all els to their natural height
831function undistributeHeight(els) {
832 els.forEach(function (el) {
833 el.style.height = '';
834 });
835}
836// Given `els`, a set of <td> cells, find the cell with the largest natural width and set the widths of all the
837// cells to be that width.
838// PREREQUISITE: if you want a cell to take up width, it needs to have a single inner element w/ display:inline
839function matchCellWidths(els) {
840 var maxInnerWidth = 0;
841 els.forEach(function (el) {
842 var innerEl = el.firstChild; // hopefully an element
843 if (innerEl instanceof HTMLElement) {
844 var innerWidth_1 = innerEl.getBoundingClientRect().width;
845 if (innerWidth_1 > maxInnerWidth) {
846 maxInnerWidth = innerWidth_1;
847 }
848 }
849 });
850 maxInnerWidth++; // sometimes not accurate of width the text needs to stay on one line. insurance
851 els.forEach(function (el) {
852 el.style.width = maxInnerWidth + 'px';
853 });
854 return maxInnerWidth;
855}
856// Given one element that resides inside another,
857// Subtracts the height of the inner element from the outer element.
858function subtractInnerElHeight(outerEl, innerEl) {
859 // effin' IE8/9/10/11 sometimes returns 0 for dimensions. this weird hack was the only thing that worked
860 var reflowStyleProps = {
861 position: 'relative',
862 left: -1 // ensure reflow in case the el was already relative. negative is less likely to cause new scroll
863 };
864 applyStyle(outerEl, reflowStyleProps);
865 applyStyle(innerEl, reflowStyleProps);
866 var diff = // grab the dimensions
867 outerEl.getBoundingClientRect().height -
868 innerEl.getBoundingClientRect().height;
869 // undo hack
870 var resetStyleProps = { position: '', left: '' };
871 applyStyle(outerEl, resetStyleProps);
872 applyStyle(innerEl, resetStyleProps);
873 return diff;
874}
875/* Selection
876----------------------------------------------------------------------------------------------------------------------*/
877function preventSelection(el) {
878 el.classList.add('fc-unselectable');
879 el.addEventListener('selectstart', preventDefault);
880}
881function allowSelection(el) {
882 el.classList.remove('fc-unselectable');
883 el.removeEventListener('selectstart', preventDefault);
884}
885/* Context Menu
886----------------------------------------------------------------------------------------------------------------------*/
887function preventContextMenu(el) {
888 el.addEventListener('contextmenu', preventDefault);
889}
890function allowContextMenu(el) {
891 el.removeEventListener('contextmenu', preventDefault);
892}
893/* Object Ordering by Field
894----------------------------------------------------------------------------------------------------------------------*/
895function parseFieldSpecs(input) {
896 var specs = [];
897 var tokens = [];
898 var i;
899 var token;
900 if (typeof input === 'string') {
901 tokens = input.split(/\s*,\s*/);
902 }
903 else if (typeof input === 'function') {
904 tokens = [input];
905 }
906 else if (Array.isArray(input)) {
907 tokens = input;
908 }
909 for (i = 0; i < tokens.length; i++) {
910 token = tokens[i];
911 if (typeof token === 'string') {
912 specs.push(token.charAt(0) === '-' ?
913 { field: token.substring(1), order: -1 } :
914 { field: token, order: 1 });
915 }
916 else if (typeof token === 'function') {
917 specs.push({ func: token });
918 }
919 }
920 return specs;
921}
922function compareByFieldSpecs(obj0, obj1, fieldSpecs) {
923 var i;
924 var cmp;
925 for (i = 0; i < fieldSpecs.length; i++) {
926 cmp = compareByFieldSpec(obj0, obj1, fieldSpecs[i]);
927 if (cmp) {
928 return cmp;
929 }
930 }
931 return 0;
932}
933function compareByFieldSpec(obj0, obj1, fieldSpec) {
934 if (fieldSpec.func) {
935 return fieldSpec.func(obj0, obj1);
936 }
937 return flexibleCompare(obj0[fieldSpec.field], obj1[fieldSpec.field])
938 * (fieldSpec.order || 1);
939}
940function flexibleCompare(a, b) {
941 if (!a && !b) {
942 return 0;
943 }
944 if (b == null) {
945 return -1;
946 }
947 if (a == null) {
948 return 1;
949 }
950 if (typeof a === 'string' || typeof b === 'string') {
951 return String(a).localeCompare(String(b));
952 }
953 return a - b;
954}
955/* String Utilities
956----------------------------------------------------------------------------------------------------------------------*/
957function capitaliseFirstLetter(str) {
958 return str.charAt(0).toUpperCase() + str.slice(1);
959}
960function padStart(val, len) {
961 var s = String(val);
962 return '000'.substr(0, len - s.length) + s;
963}
964/* Number Utilities
965----------------------------------------------------------------------------------------------------------------------*/
966function compareNumbers(a, b) {
967 return a - b;
968}
969function isInt(n) {
970 return n % 1 === 0;
971}
972/* Weird Utilities
973----------------------------------------------------------------------------------------------------------------------*/
974function applyAll(functions, thisObj, args) {
975 if (typeof functions === 'function') { // supplied a single function
976 functions = [functions];
977 }
978 if (functions) {
979 var i = void 0;
980 var ret = void 0;
981 for (i = 0; i < functions.length; i++) {
982 ret = functions[i].apply(thisObj, args) || ret;
983 }
984 return ret;
985 }
986}
987function firstDefined() {
988 var args = [];
989 for (var _i = 0; _i < arguments.length; _i++) {
990 args[_i] = arguments[_i];
991 }
992 for (var i = 0; i < args.length; i++) {
993 if (args[i] !== undefined) {
994 return args[i];
995 }
996 }
997}
998// Returns a function, that, as long as it continues to be invoked, will not
999// be triggered. The function will be called after it stops being called for
1000// N milliseconds. If `immediate` is passed, trigger the function on the
1001// leading edge, instead of the trailing.
1002// https://github.com/jashkenas/underscore/blob/1.6.0/underscore.js#L714
1003function debounce(func, wait) {
1004 var timeout;
1005 var args;
1006 var context;
1007 var timestamp;
1008 var result;
1009 var later = function () {
1010 var last = new Date().valueOf() - timestamp;
1011 if (last < wait) {
1012 timeout = setTimeout(later, wait - last);
1013 }
1014 else {
1015 timeout = null;
1016 result = func.apply(context, args);
1017 context = args = null;
1018 }
1019 };
1020 return function () {
1021 context = this;
1022 args = arguments;
1023 timestamp = new Date().valueOf();
1024 if (!timeout) {
1025 timeout = setTimeout(later, wait);
1026 }
1027 return result;
1028 };
1029}
1030// Number and Boolean are only types that defaults or not computed for
1031// TODO: write more comments
1032function refineProps(rawProps, processors, defaults, leftoverProps) {
1033 if (defaults === void 0) { defaults = {}; }
1034 var refined = {};
1035 for (var key in processors) {
1036 var processor = processors[key];
1037 if (rawProps[key] !== undefined) {
1038 // found
1039 if (processor === Function) {
1040 refined[key] = typeof rawProps[key] === 'function' ? rawProps[key] : null;
1041 }
1042 else if (processor) { // a refining function?
1043 refined[key] = processor(rawProps[key]);
1044 }
1045 else {
1046 refined[key] = rawProps[key];
1047 }
1048 }
1049 else if (defaults[key] !== undefined) {
1050 // there's an explicit default
1051 refined[key] = defaults[key];
1052 }
1053 else {
1054 // must compute a default
1055 if (processor === String) {
1056 refined[key] = ''; // empty string is default for String
1057 }
1058 else if (!processor || processor === Number || processor === Boolean || processor === Function) {
1059 refined[key] = null; // assign null for other non-custom processor funcs
1060 }
1061 else {
1062 refined[key] = processor(null); // run the custom processor func
1063 }
1064 }
1065 }
1066 if (leftoverProps) {
1067 for (var key in rawProps) {
1068 if (processors[key] === undefined) {
1069 leftoverProps[key] = rawProps[key];
1070 }
1071 }
1072 }
1073 return refined;
1074}
1075/* Date stuff that doesn't belong in datelib core
1076----------------------------------------------------------------------------------------------------------------------*/
1077// given a timed range, computes an all-day range that has the same exact duration,
1078// but whose start time is aligned with the start of the day.
1079function computeAlignedDayRange(timedRange) {
1080 var dayCnt = Math.floor(diffDays(timedRange.start, timedRange.end)) || 1;
1081 var start = startOfDay(timedRange.start);
1082 var end = addDays(start, dayCnt);
1083 return { start: start, end: end };
1084}
1085// given a timed range, computes an all-day range based on how for the end date bleeds into the next day
1086// TODO: give nextDayThreshold a default arg
1087function computeVisibleDayRange(timedRange, nextDayThreshold) {
1088 if (nextDayThreshold === void 0) { nextDayThreshold = createDuration(0); }
1089 var startDay = null;
1090 var endDay = null;
1091 if (timedRange.end) {
1092 endDay = startOfDay(timedRange.end);
1093 var endTimeMS = timedRange.end.valueOf() - endDay.valueOf(); // # of milliseconds into `endDay`
1094 // If the end time is actually inclusively part of the next day and is equal to or
1095 // beyond the next day threshold, adjust the end to be the exclusive end of `endDay`.
1096 // Otherwise, leaving it as inclusive will cause it to exclude `endDay`.
1097 if (endTimeMS && endTimeMS >= asRoughMs(nextDayThreshold)) {
1098 endDay = addDays(endDay, 1);
1099 }
1100 }
1101 if (timedRange.start) {
1102 startDay = startOfDay(timedRange.start); // the beginning of the day the range starts
1103 // If end is within `startDay` but not past nextDayThreshold, assign the default duration of one day.
1104 if (endDay && endDay <= startDay) {
1105 endDay = addDays(startDay, 1);
1106 }
1107 }
1108 return { start: startDay, end: endDay };
1109}
1110// spans from one day into another?
1111function isMultiDayRange(range) {
1112 var visibleRange = computeVisibleDayRange(range);
1113 return diffDays(visibleRange.start, visibleRange.end) > 1;
1114}
1115function diffDates(date0, date1, dateEnv, largeUnit) {
1116 if (largeUnit === 'year') {
1117 return createDuration(dateEnv.diffWholeYears(date0, date1), 'year');
1118 }
1119 else if (largeUnit === 'month') {
1120 return createDuration(dateEnv.diffWholeMonths(date0, date1), 'month');
1121 }
1122 else {
1123 return diffDayAndTime(date0, date1); // returns a duration
1124 }
1125}
1126
1127/*! *****************************************************************************
1128Copyright (c) Microsoft Corporation. All rights reserved.
1129Licensed under the Apache License, Version 2.0 (the "License"); you may not use
1130this file except in compliance with the License. You may obtain a copy of the
1131License at http://www.apache.org/licenses/LICENSE-2.0
1132
1133THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
1134KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
1135WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
1136MERCHANTABLITY OR NON-INFRINGEMENT.
1137
1138See the Apache Version 2.0 License for specific language governing permissions
1139and limitations under the License.
1140***************************************************************************** */
1141/* global Reflect, Promise */
1142
1143var extendStatics = function(d, b) {
1144 extendStatics = Object.setPrototypeOf ||
1145 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
1146 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
1147 return extendStatics(d, b);
1148};
1149
1150function __extends(d, b) {
1151 extendStatics(d, b);
1152 function __() { this.constructor = d; }
1153 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
1154}
1155
1156var __assign = function() {
1157 __assign = Object.assign || function __assign(t) {
1158 for (var s, i = 1, n = arguments.length; i < n; i++) {
1159 s = arguments[i];
1160 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
1161 }
1162 return t;
1163 };
1164 return __assign.apply(this, arguments);
1165};
1166
1167function parseRecurring(eventInput, allDayDefault, dateEnv, recurringTypes, leftovers) {
1168 for (var i = 0; i < recurringTypes.length; i++) {
1169 var localLeftovers = {};
1170 var parsed = recurringTypes[i].parse(eventInput, localLeftovers, dateEnv);
1171 if (parsed) {
1172 var allDay = localLeftovers.allDay;
1173 delete localLeftovers.allDay; // remove from leftovers
1174 if (allDay == null) {
1175 allDay = allDayDefault;
1176 if (allDay == null) {
1177 allDay = parsed.allDayGuess;
1178 if (allDay == null) {
1179 allDay = false;
1180 }
1181 }
1182 }
1183 __assign(leftovers, localLeftovers);
1184 return {
1185 allDay: allDay,
1186 duration: parsed.duration,
1187 typeData: parsed.typeData,
1188 typeId: i
1189 };
1190 }
1191 }
1192 return null;
1193}
1194/*
1195Event MUST have a recurringDef
1196*/
1197function expandRecurringRanges(eventDef, duration, framingRange, dateEnv, recurringTypes) {
1198 var typeDef = recurringTypes[eventDef.recurringDef.typeId];
1199 var markers = typeDef.expand(eventDef.recurringDef.typeData, {
1200 start: dateEnv.subtract(framingRange.start, duration),
1201 end: framingRange.end
1202 }, dateEnv);
1203 // the recurrence plugins don't guarantee that all-day events are start-of-day, so we have to
1204 if (eventDef.allDay) {
1205 markers = markers.map(startOfDay);
1206 }
1207 return markers;
1208}
1209
1210var hasOwnProperty = Object.prototype.hasOwnProperty;
1211// Merges an array of objects into a single object.
1212// The second argument allows for an array of property names who's object values will be merged together.
1213function mergeProps(propObjs, complexProps) {
1214 var dest = {};
1215 var i;
1216 var name;
1217 var complexObjs;
1218 var j;
1219 var val;
1220 var props;
1221 if (complexProps) {
1222 for (i = 0; i < complexProps.length; i++) {
1223 name = complexProps[i];
1224 complexObjs = [];
1225 // collect the trailing object values, stopping when a non-object is discovered
1226 for (j = propObjs.length - 1; j >= 0; j--) {
1227 val = propObjs[j][name];
1228 if (typeof val === 'object' && val) { // non-null object
1229 complexObjs.unshift(val);
1230 }
1231 else if (val !== undefined) {
1232 dest[name] = val; // if there were no objects, this value will be used
1233 break;
1234 }
1235 }
1236 // if the trailing values were objects, use the merged value
1237 if (complexObjs.length) {
1238 dest[name] = mergeProps(complexObjs);
1239 }
1240 }
1241 }
1242 // copy values into the destination, going from last to first
1243 for (i = propObjs.length - 1; i >= 0; i--) {
1244 props = propObjs[i];
1245 for (name in props) {
1246 if (!(name in dest)) { // if already assigned by previous props or complex props, don't reassign
1247 dest[name] = props[name];
1248 }
1249 }
1250 }
1251 return dest;
1252}
1253function filterHash(hash, func) {
1254 var filtered = {};
1255 for (var key in hash) {
1256 if (func(hash[key], key)) {
1257 filtered[key] = hash[key];
1258 }
1259 }
1260 return filtered;
1261}
1262function mapHash(hash, func) {
1263 var newHash = {};
1264 for (var key in hash) {
1265 newHash[key] = func(hash[key], key);
1266 }
1267 return newHash;
1268}
1269function arrayToHash(a) {
1270 var hash = {};
1271 for (var _i = 0, a_1 = a; _i < a_1.length; _i++) {
1272 var item = a_1[_i];
1273 hash[item] = true;
1274 }
1275 return hash;
1276}
1277function hashValuesToArray(obj) {
1278 var a = [];
1279 for (var key in obj) {
1280 a.push(obj[key]);
1281 }
1282 return a;
1283}
1284function isPropsEqual(obj0, obj1) {
1285 for (var key in obj0) {
1286 if (hasOwnProperty.call(obj0, key)) {
1287 if (!(key in obj1)) {
1288 return false;
1289 }
1290 }
1291 }
1292 for (var key in obj1) {
1293 if (hasOwnProperty.call(obj1, key)) {
1294 if (obj0[key] !== obj1[key]) {
1295 return false;
1296 }
1297 }
1298 }
1299 return true;
1300}
1301
1302function parseEvents(rawEvents, sourceId, calendar, allowOpenRange) {
1303 var eventStore = createEmptyEventStore();
1304 for (var _i = 0, rawEvents_1 = rawEvents; _i < rawEvents_1.length; _i++) {
1305 var rawEvent = rawEvents_1[_i];
1306 var tuple = parseEvent(rawEvent, sourceId, calendar, allowOpenRange);
1307 if (tuple) {
1308 eventTupleToStore(tuple, eventStore);
1309 }
1310 }
1311 return eventStore;
1312}
1313function eventTupleToStore(tuple, eventStore) {
1314 if (eventStore === void 0) { eventStore = createEmptyEventStore(); }
1315 eventStore.defs[tuple.def.defId] = tuple.def;
1316 if (tuple.instance) {
1317 eventStore.instances[tuple.instance.instanceId] = tuple.instance;
1318 }
1319 return eventStore;
1320}
1321function expandRecurring(eventStore, framingRange, calendar) {
1322 var dateEnv = calendar.dateEnv;
1323 var defs = eventStore.defs, instances = eventStore.instances;
1324 // remove existing recurring instances
1325 instances = filterHash(instances, function (instance) {
1326 return !defs[instance.defId].recurringDef;
1327 });
1328 for (var defId in defs) {
1329 var def = defs[defId];
1330 if (def.recurringDef) {
1331 var duration = def.recurringDef.duration;
1332 if (!duration) {
1333 duration = def.allDay ?
1334 calendar.defaultAllDayEventDuration :
1335 calendar.defaultTimedEventDuration;
1336 }
1337 var starts = expandRecurringRanges(def, duration, framingRange, calendar.dateEnv, calendar.pluginSystem.hooks.recurringTypes);
1338 for (var _i = 0, starts_1 = starts; _i < starts_1.length; _i++) {
1339 var start = starts_1[_i];
1340 var instance = createEventInstance(defId, {
1341 start: start,
1342 end: dateEnv.add(start, duration)
1343 });
1344 instances[instance.instanceId] = instance;
1345 }
1346 }
1347 }
1348 return { defs: defs, instances: instances };
1349}
1350// retrieves events that have the same groupId as the instance specified by `instanceId`
1351// or they are the same as the instance.
1352// why might instanceId not be in the store? an event from another calendar?
1353function getRelevantEvents(eventStore, instanceId) {
1354 var instance = eventStore.instances[instanceId];
1355 if (instance) {
1356 var def_1 = eventStore.defs[instance.defId];
1357 // get events/instances with same group
1358 var newStore = filterEventStoreDefs(eventStore, function (lookDef) {
1359 return isEventDefsGrouped(def_1, lookDef);
1360 });
1361 // add the original
1362 // TODO: wish we could use eventTupleToStore or something like it
1363 newStore.defs[def_1.defId] = def_1;
1364 newStore.instances[instance.instanceId] = instance;
1365 return newStore;
1366 }
1367 return createEmptyEventStore();
1368}
1369function isEventDefsGrouped(def0, def1) {
1370 return Boolean(def0.groupId && def0.groupId === def1.groupId);
1371}
1372function transformRawEvents(rawEvents, eventSource, calendar) {
1373 var calEachTransform = calendar.opt('eventDataTransform');
1374 var sourceEachTransform = eventSource ? eventSource.eventDataTransform : null;
1375 if (sourceEachTransform) {
1376 rawEvents = transformEachRawEvent(rawEvents, sourceEachTransform);
1377 }
1378 if (calEachTransform) {
1379 rawEvents = transformEachRawEvent(rawEvents, calEachTransform);
1380 }
1381 return rawEvents;
1382}
1383function transformEachRawEvent(rawEvents, func) {
1384 var refinedEvents;
1385 if (!func) {
1386 refinedEvents = rawEvents;
1387 }
1388 else {
1389 refinedEvents = [];
1390 for (var _i = 0, rawEvents_2 = rawEvents; _i < rawEvents_2.length; _i++) {
1391 var rawEvent = rawEvents_2[_i];
1392 var refinedEvent = func(rawEvent);
1393 if (refinedEvent) {
1394 refinedEvents.push(refinedEvent);
1395 }
1396 else if (refinedEvent == null) {
1397 refinedEvents.push(rawEvent);
1398 } // if a different falsy value, do nothing
1399 }
1400 }
1401 return refinedEvents;
1402}
1403function createEmptyEventStore() {
1404 return { defs: {}, instances: {} };
1405}
1406function mergeEventStores(store0, store1) {
1407 return {
1408 defs: __assign({}, store0.defs, store1.defs),
1409 instances: __assign({}, store0.instances, store1.instances)
1410 };
1411}
1412function filterEventStoreDefs(eventStore, filterFunc) {
1413 var defs = filterHash(eventStore.defs, filterFunc);
1414 var instances = filterHash(eventStore.instances, function (instance) {
1415 return defs[instance.defId]; // still exists?
1416 });
1417 return { defs: defs, instances: instances };
1418}
1419
1420function parseRange(input, dateEnv) {
1421 var start = null;
1422 var end = null;
1423 if (input.start) {
1424 start = dateEnv.createMarker(input.start);
1425 }
1426 if (input.end) {
1427 end = dateEnv.createMarker(input.end);
1428 }
1429 if (!start && !end) {
1430 return null;
1431 }
1432 if (start && end && end < start) {
1433 return null;
1434 }
1435 return { start: start, end: end };
1436}
1437// SIDE-EFFECT: will mutate ranges.
1438// Will return a new array result.
1439function invertRanges(ranges, constraintRange) {
1440 var invertedRanges = [];
1441 var start = constraintRange.start; // the end of the previous range. the start of the new range
1442 var i;
1443 var dateRange;
1444 // ranges need to be in order. required for our date-walking algorithm
1445 ranges.sort(compareRanges);
1446 for (i = 0; i < ranges.length; i++) {
1447 dateRange = ranges[i];
1448 // add the span of time before the event (if there is any)
1449 if (dateRange.start > start) { // compare millisecond time (skip any ambig logic)
1450 invertedRanges.push({ start: start, end: dateRange.start });
1451 }
1452 if (dateRange.end > start) {
1453 start = dateRange.end;
1454 }
1455 }
1456 // add the span of time after the last event (if there is any)
1457 if (start < constraintRange.end) { // compare millisecond time (skip any ambig logic)
1458 invertedRanges.push({ start: start, end: constraintRange.end });
1459 }
1460 return invertedRanges;
1461}
1462function compareRanges(range0, range1) {
1463 return range0.start.valueOf() - range1.start.valueOf(); // earlier ranges go first
1464}
1465function intersectRanges(range0, range1) {
1466 var start = range0.start;
1467 var end = range0.end;
1468 var newRange = null;
1469 if (range1.start !== null) {
1470 if (start === null) {
1471 start = range1.start;
1472 }
1473 else {
1474 start = new Date(Math.max(start.valueOf(), range1.start.valueOf()));
1475 }
1476 }
1477 if (range1.end != null) {
1478 if (end === null) {
1479 end = range1.end;
1480 }
1481 else {
1482 end = new Date(Math.min(end.valueOf(), range1.end.valueOf()));
1483 }
1484 }
1485 if (start === null || end === null || start < end) {
1486 newRange = { start: start, end: end };
1487 }
1488 return newRange;
1489}
1490function rangesEqual(range0, range1) {
1491 return (range0.start === null ? null : range0.start.valueOf()) === (range1.start === null ? null : range1.start.valueOf()) &&
1492 (range0.end === null ? null : range0.end.valueOf()) === (range1.end === null ? null : range1.end.valueOf());
1493}
1494function rangesIntersect(range0, range1) {
1495 return (range0.end === null || range1.start === null || range0.end > range1.start) &&
1496 (range0.start === null || range1.end === null || range0.start < range1.end);
1497}
1498function rangeContainsRange(outerRange, innerRange) {
1499 return (outerRange.start === null || (innerRange.start !== null && innerRange.start >= outerRange.start)) &&
1500 (outerRange.end === null || (innerRange.end !== null && innerRange.end <= outerRange.end));
1501}
1502function rangeContainsMarker(range, date) {
1503 return (range.start === null || date >= range.start) &&
1504 (range.end === null || date < range.end);
1505}
1506// If the given date is not within the given range, move it inside.
1507// (If it's past the end, make it one millisecond before the end).
1508function constrainMarkerToRange(date, range) {
1509 if (range.start != null && date < range.start) {
1510 return range.start;
1511 }
1512 if (range.end != null && date >= range.end) {
1513 return new Date(range.end.valueOf() - 1);
1514 }
1515 return date;
1516}
1517
1518function removeExact(array, exactVal) {
1519 var removeCnt = 0;
1520 var i = 0;
1521 while (i < array.length) {
1522 if (array[i] === exactVal) {
1523 array.splice(i, 1);
1524 removeCnt++;
1525 }
1526 else {
1527 i++;
1528 }
1529 }
1530 return removeCnt;
1531}
1532function isArraysEqual(a0, a1) {
1533 var len = a0.length;
1534 var i;
1535 if (len !== a1.length) { // not array? or not same length?
1536 return false;
1537 }
1538 for (i = 0; i < len; i++) {
1539 if (a0[i] !== a1[i]) {
1540 return false;
1541 }
1542 }
1543 return true;
1544}
1545
1546function memoize(workerFunc) {
1547 var args;
1548 var res;
1549 return function () {
1550 if (!args || !isArraysEqual(args, arguments)) {
1551 args = arguments;
1552 res = workerFunc.apply(this, arguments);
1553 }
1554 return res;
1555 };
1556}
1557/*
1558always executes the workerFunc, but if the result is equal to the previous result,
1559return the previous result instead.
1560*/
1561function memoizeOutput(workerFunc, equalityFunc) {
1562 var cachedRes = null;
1563 return function () {
1564 var newRes = workerFunc.apply(this, arguments);
1565 if (cachedRes === null || !(cachedRes === newRes || equalityFunc(cachedRes, newRes))) {
1566 cachedRes = newRes;
1567 }
1568 return cachedRes;
1569 };
1570}
1571
1572var EXTENDED_SETTINGS_AND_SEVERITIES = {
1573 week: 3,
1574 separator: 0,
1575 omitZeroMinute: 0,
1576 meridiem: 0,
1577 omitCommas: 0
1578};
1579var STANDARD_DATE_PROP_SEVERITIES = {
1580 timeZoneName: 7,
1581 era: 6,
1582 year: 5,
1583 month: 4,
1584 day: 2,
1585 weekday: 2,
1586 hour: 1,
1587 minute: 1,
1588 second: 1
1589};
1590var MERIDIEM_RE = /\s*([ap])\.?m\.?/i; // eats up leading spaces too
1591var COMMA_RE = /,/g; // we need re for globalness
1592var MULTI_SPACE_RE = /\s+/g;
1593var LTR_RE = /\u200e/g; // control character
1594var UTC_RE = /UTC|GMT/;
1595var NativeFormatter = /** @class */ (function () {
1596 function NativeFormatter(formatSettings) {
1597 var standardDateProps = {};
1598 var extendedSettings = {};
1599 var severity = 0;
1600 for (var name_1 in formatSettings) {
1601 if (name_1 in EXTENDED_SETTINGS_AND_SEVERITIES) {
1602 extendedSettings[name_1] = formatSettings[name_1];
1603 severity = Math.max(EXTENDED_SETTINGS_AND_SEVERITIES[name_1], severity);
1604 }
1605 else {
1606 standardDateProps[name_1] = formatSettings[name_1];
1607 if (name_1 in STANDARD_DATE_PROP_SEVERITIES) {
1608 severity = Math.max(STANDARD_DATE_PROP_SEVERITIES[name_1], severity);
1609 }
1610 }
1611 }
1612 this.standardDateProps = standardDateProps;
1613 this.extendedSettings = extendedSettings;
1614 this.severity = severity;
1615 this.buildFormattingFunc = memoize(buildFormattingFunc);
1616 }
1617 NativeFormatter.prototype.format = function (date, context) {
1618 return this.buildFormattingFunc(this.standardDateProps, this.extendedSettings, context)(date);
1619 };
1620 NativeFormatter.prototype.formatRange = function (start, end, context) {
1621 var _a = this, standardDateProps = _a.standardDateProps, extendedSettings = _a.extendedSettings;
1622 var diffSeverity = computeMarkerDiffSeverity(start.marker, end.marker, context.calendarSystem);
1623 if (!diffSeverity) {
1624 return this.format(start, context);
1625 }
1626 var biggestUnitForPartial = diffSeverity;
1627 if (biggestUnitForPartial > 1 && // the two dates are different in a way that's larger scale than time
1628 (standardDateProps.year === 'numeric' || standardDateProps.year === '2-digit') &&
1629 (standardDateProps.month === 'numeric' || standardDateProps.month === '2-digit') &&
1630 (standardDateProps.day === 'numeric' || standardDateProps.day === '2-digit')) {
1631 biggestUnitForPartial = 1; // make it look like the dates are only different in terms of time
1632 }
1633 var full0 = this.format(start, context);
1634 var full1 = this.format(end, context);
1635 if (full0 === full1) {
1636 return full0;
1637 }
1638 var partialDateProps = computePartialFormattingOptions(standardDateProps, biggestUnitForPartial);
1639 var partialFormattingFunc = buildFormattingFunc(partialDateProps, extendedSettings, context);
1640 var partial0 = partialFormattingFunc(start);
1641 var partial1 = partialFormattingFunc(end);
1642 var insertion = findCommonInsertion(full0, partial0, full1, partial1);
1643 var separator = extendedSettings.separator || '';
1644 if (insertion) {
1645 return insertion.before + partial0 + separator + partial1 + insertion.after;
1646 }
1647 return full0 + separator + full1;
1648 };
1649 NativeFormatter.prototype.getLargestUnit = function () {
1650 switch (this.severity) {
1651 case 7:
1652 case 6:
1653 case 5:
1654 return 'year';
1655 case 4:
1656 return 'month';
1657 case 3:
1658 return 'week';
1659 default:
1660 return 'day';
1661 }
1662 };
1663 return NativeFormatter;
1664}());
1665function buildFormattingFunc(standardDateProps, extendedSettings, context) {
1666 var standardDatePropCnt = Object.keys(standardDateProps).length;
1667 if (standardDatePropCnt === 1 && standardDateProps.timeZoneName === 'short') {
1668 return function (date) {
1669 return formatTimeZoneOffset(date.timeZoneOffset);
1670 };
1671 }
1672 if (standardDatePropCnt === 0 && extendedSettings.week) {
1673 return function (date) {
1674 return formatWeekNumber(context.computeWeekNumber(date.marker), context.weekLabel, context.locale, extendedSettings.week);
1675 };
1676 }
1677 return buildNativeFormattingFunc(standardDateProps, extendedSettings, context);
1678}
1679function buildNativeFormattingFunc(standardDateProps, extendedSettings, context) {
1680 standardDateProps = __assign({}, standardDateProps); // copy
1681 extendedSettings = __assign({}, extendedSettings); // copy
1682 sanitizeSettings(standardDateProps, extendedSettings);
1683 standardDateProps.timeZone = 'UTC'; // we leverage the only guaranteed timeZone for our UTC markers
1684 var normalFormat = new Intl.DateTimeFormat(context.locale.codes, standardDateProps);
1685 var zeroFormat; // needed?
1686 if (extendedSettings.omitZeroMinute) {
1687 var zeroProps = __assign({}, standardDateProps);
1688 delete zeroProps.minute; // seconds and ms were already considered in sanitizeSettings
1689 zeroFormat = new Intl.DateTimeFormat(context.locale.codes, zeroProps);
1690 }
1691 return function (date) {
1692 var marker = date.marker;
1693 var format;
1694 if (zeroFormat && !marker.getUTCMinutes()) {
1695 format = zeroFormat;
1696 }
1697 else {
1698 format = normalFormat;
1699 }
1700 var s = format.format(marker);
1701 return postProcess(s, date, standardDateProps, extendedSettings, context);
1702 };
1703}
1704function sanitizeSettings(standardDateProps, extendedSettings) {
1705 // deal with a browser inconsistency where formatting the timezone
1706 // requires that the hour/minute be present.
1707 if (standardDateProps.timeZoneName) {
1708 if (!standardDateProps.hour) {
1709 standardDateProps.hour = '2-digit';
1710 }
1711 if (!standardDateProps.minute) {
1712 standardDateProps.minute = '2-digit';
1713 }
1714 }
1715 // only support short timezone names
1716 if (standardDateProps.timeZoneName === 'long') {
1717 standardDateProps.timeZoneName = 'short';
1718 }
1719 // if requesting to display seconds, MUST display minutes
1720 if (extendedSettings.omitZeroMinute && (standardDateProps.second || standardDateProps.millisecond)) {
1721 delete extendedSettings.omitZeroMinute;
1722 }
1723}
1724function postProcess(s, date, standardDateProps, extendedSettings, context) {
1725 s = s.replace(LTR_RE, ''); // remove left-to-right control chars. do first. good for other regexes
1726 if (standardDateProps.timeZoneName === 'short') {
1727 s = injectTzoStr(s, (context.timeZone === 'UTC' || date.timeZoneOffset == null) ?
1728 'UTC' : // important to normalize for IE, which does "GMT"
1729 formatTimeZoneOffset(date.timeZoneOffset));
1730 }
1731 if (extendedSettings.omitCommas) {
1732 s = s.replace(COMMA_RE, '').trim();
1733 }
1734 if (extendedSettings.omitZeroMinute) {
1735 s = s.replace(':00', ''); // zeroFormat doesn't always achieve this
1736 }
1737 // ^ do anything that might create adjacent spaces before this point,
1738 // because MERIDIEM_RE likes to eat up loading spaces
1739 if (extendedSettings.meridiem === false) {
1740 s = s.replace(MERIDIEM_RE, '').trim();
1741 }
1742 else if (extendedSettings.meridiem === 'narrow') { // a/p
1743 s = s.replace(MERIDIEM_RE, function (m0, m1) {
1744 return m1.toLocaleLowerCase();
1745 });
1746 }
1747 else if (extendedSettings.meridiem === 'short') { // am/pm
1748 s = s.replace(MERIDIEM_RE, function (m0, m1) {
1749 return m1.toLocaleLowerCase() + 'm';
1750 });
1751 }
1752 else if (extendedSettings.meridiem === 'lowercase') { // other meridiem transformers already converted to lowercase
1753 s = s.replace(MERIDIEM_RE, function (m0) {
1754 return m0.toLocaleLowerCase();
1755 });
1756 }
1757 s = s.replace(MULTI_SPACE_RE, ' ');
1758 s = s.trim();
1759 return s;
1760}
1761function injectTzoStr(s, tzoStr) {
1762 var replaced = false;
1763 s = s.replace(UTC_RE, function () {
1764 replaced = true;
1765 return tzoStr;
1766 });
1767 // IE11 doesn't include UTC/GMT in the original string, so append to end
1768 if (!replaced) {
1769 s += ' ' + tzoStr;
1770 }
1771 return s;
1772}
1773function formatWeekNumber(num, weekLabel, locale, display) {
1774 var parts = [];
1775 if (display === 'narrow') {
1776 parts.push(weekLabel);
1777 }
1778 else if (display === 'short') {
1779 parts.push(weekLabel, ' ');
1780 }
1781 // otherwise, considered 'numeric'
1782 parts.push(locale.simpleNumberFormat.format(num));
1783 if (locale.options.isRtl) { // TODO: use control characters instead?
1784 parts.reverse();
1785 }
1786 return parts.join('');
1787}
1788// Range Formatting Utils
1789// 0 = exactly the same
1790// 1 = different by time
1791// and bigger
1792function computeMarkerDiffSeverity(d0, d1, ca) {
1793 if (ca.getMarkerYear(d0) !== ca.getMarkerYear(d1)) {
1794 return 5;
1795 }
1796 if (ca.getMarkerMonth(d0) !== ca.getMarkerMonth(d1)) {
1797 return 4;
1798 }
1799 if (ca.getMarkerDay(d0) !== ca.getMarkerDay(d1)) {
1800 return 2;
1801 }
1802 if (timeAsMs(d0) !== timeAsMs(d1)) {
1803 return 1;
1804 }
1805 return 0;
1806}
1807function computePartialFormattingOptions(options, biggestUnit) {
1808 var partialOptions = {};
1809 for (var name_2 in options) {
1810 if (!(name_2 in STANDARD_DATE_PROP_SEVERITIES) || // not a date part prop (like timeZone)
1811 STANDARD_DATE_PROP_SEVERITIES[name_2] <= biggestUnit) {
1812 partialOptions[name_2] = options[name_2];
1813 }
1814 }
1815 return partialOptions;
1816}
1817function findCommonInsertion(full0, partial0, full1, partial1) {
1818 var i0 = 0;
1819 while (i0 < full0.length) {
1820 var found0 = full0.indexOf(partial0, i0);
1821 if (found0 === -1) {
1822 break;
1823 }
1824 var before0 = full0.substr(0, found0);
1825 i0 = found0 + partial0.length;
1826 var after0 = full0.substr(i0);
1827 var i1 = 0;
1828 while (i1 < full1.length) {
1829 var found1 = full1.indexOf(partial1, i1);
1830 if (found1 === -1) {
1831 break;
1832 }
1833 var before1 = full1.substr(0, found1);
1834 i1 = found1 + partial1.length;
1835 var after1 = full1.substr(i1);
1836 if (before0 === before1 && after0 === after1) {
1837 return {
1838 before: before0,
1839 after: after0
1840 };
1841 }
1842 }
1843 }
1844 return null;
1845}
1846
1847/*
1848TODO: fix the terminology of "formatter" vs "formatting func"
1849*/
1850/*
1851At the time of instantiation, this object does not know which cmd-formatting system it will use.
1852It receives this at the time of formatting, as a setting.
1853*/
1854var CmdFormatter = /** @class */ (function () {
1855 function CmdFormatter(cmdStr, separator) {
1856 this.cmdStr = cmdStr;
1857 this.separator = separator;
1858 }
1859 CmdFormatter.prototype.format = function (date, context) {
1860 return context.cmdFormatter(this.cmdStr, createVerboseFormattingArg(date, null, context, this.separator));
1861 };
1862 CmdFormatter.prototype.formatRange = function (start, end, context) {
1863 return context.cmdFormatter(this.cmdStr, createVerboseFormattingArg(start, end, context, this.separator));
1864 };
1865 return CmdFormatter;
1866}());
1867
1868var FuncFormatter = /** @class */ (function () {
1869 function FuncFormatter(func) {
1870 this.func = func;
1871 }
1872 FuncFormatter.prototype.format = function (date, context) {
1873 return this.func(createVerboseFormattingArg(date, null, context));
1874 };
1875 FuncFormatter.prototype.formatRange = function (start, end, context) {
1876 return this.func(createVerboseFormattingArg(start, end, context));
1877 };
1878 return FuncFormatter;
1879}());
1880
1881// Formatter Object Creation
1882function createFormatter(input, defaultSeparator) {
1883 if (typeof input === 'object' && input) { // non-null object
1884 if (typeof defaultSeparator === 'string') {
1885 input = __assign({ separator: defaultSeparator }, input);
1886 }
1887 return new NativeFormatter(input);
1888 }
1889 else if (typeof input === 'string') {
1890 return new CmdFormatter(input, defaultSeparator);
1891 }
1892 else if (typeof input === 'function') {
1893 return new FuncFormatter(input);
1894 }
1895}
1896// String Utils
1897// timeZoneOffset is in minutes
1898function buildIsoString(marker, timeZoneOffset, stripZeroTime) {
1899 if (stripZeroTime === void 0) { stripZeroTime = false; }
1900 var s = marker.toISOString();
1901 s = s.replace('.000', '');
1902 if (stripZeroTime) {
1903 s = s.replace('T00:00:00Z', '');
1904 }
1905 if (s.length > 10) { // time part wasn't stripped, can add timezone info
1906 if (timeZoneOffset == null) {
1907 s = s.replace('Z', '');
1908 }
1909 else if (timeZoneOffset !== 0) {
1910 s = s.replace('Z', formatTimeZoneOffset(timeZoneOffset, true));
1911 }
1912 // otherwise, its UTC-0 and we want to keep the Z
1913 }
1914 return s;
1915}
1916function formatIsoTimeString(marker) {
1917 return padStart(marker.getUTCHours(), 2) + ':' +
1918 padStart(marker.getUTCMinutes(), 2) + ':' +
1919 padStart(marker.getUTCSeconds(), 2);
1920}
1921function formatTimeZoneOffset(minutes, doIso) {
1922 if (doIso === void 0) { doIso = false; }
1923 var sign = minutes < 0 ? '-' : '+';
1924 var abs = Math.abs(minutes);
1925 var hours = Math.floor(abs / 60);
1926 var mins = Math.round(abs % 60);
1927 if (doIso) {
1928 return sign + padStart(hours, 2) + ':' + padStart(mins, 2);
1929 }
1930 else {
1931 return 'GMT' + sign + hours + (mins ? ':' + padStart(mins, 2) : '');
1932 }
1933}
1934// Arg Utils
1935function createVerboseFormattingArg(start, end, context, separator) {
1936 var startInfo = expandZonedMarker(start, context.calendarSystem);
1937 var endInfo = end ? expandZonedMarker(end, context.calendarSystem) : null;
1938 return {
1939 date: startInfo,
1940 start: startInfo,
1941 end: endInfo,
1942 timeZone: context.timeZone,
1943 localeCodes: context.locale.codes,
1944 separator: separator
1945 };
1946}
1947function expandZonedMarker(dateInfo, calendarSystem) {
1948 var a = calendarSystem.markerToArray(dateInfo.marker);
1949 return {
1950 marker: dateInfo.marker,
1951 timeZoneOffset: dateInfo.timeZoneOffset,
1952 array: a,
1953 year: a[0],
1954 month: a[1],
1955 day: a[2],
1956 hour: a[3],
1957 minute: a[4],
1958 second: a[5],
1959 millisecond: a[6]
1960 };
1961}
1962
1963var EventSourceApi = /** @class */ (function () {
1964 function EventSourceApi(calendar, internalEventSource) {
1965 this.calendar = calendar;
1966 this.internalEventSource = internalEventSource;
1967 }
1968 EventSourceApi.prototype.remove = function () {
1969 this.calendar.dispatch({
1970 type: 'REMOVE_EVENT_SOURCE',
1971 sourceId: this.internalEventSource.sourceId
1972 });
1973 };
1974 EventSourceApi.prototype.refetch = function () {
1975 this.calendar.dispatch({
1976 type: 'FETCH_EVENT_SOURCES',
1977 sourceIds: [this.internalEventSource.sourceId]
1978 });
1979 };
1980 Object.defineProperty(EventSourceApi.prototype, "id", {
1981 get: function () {
1982 return this.internalEventSource.publicId;
1983 },
1984 enumerable: true,
1985 configurable: true
1986 });
1987 Object.defineProperty(EventSourceApi.prototype, "url", {
1988 // only relevant to json-feed event sources
1989 get: function () {
1990 return this.internalEventSource.meta.url;
1991 },
1992 enumerable: true,
1993 configurable: true
1994 });
1995 return EventSourceApi;
1996}());
1997
1998var EventApi = /** @class */ (function () {
1999 function EventApi(calendar, def, instance) {
2000 this._calendar = calendar;
2001 this._def = def;
2002 this._instance = instance || null;
2003 }
2004 /*
2005 TODO: make event struct more responsible for this
2006 */
2007 EventApi.prototype.setProp = function (name, val) {
2008 var _a, _b;
2009 if (name in DATE_PROPS) ;
2010 else if (name in NON_DATE_PROPS) {
2011 if (typeof NON_DATE_PROPS[name] === 'function') {
2012 val = NON_DATE_PROPS[name](val);
2013 }
2014 this.mutate({
2015 standardProps: (_a = {}, _a[name] = val, _a)
2016 });
2017 }
2018 else if (name in UNSCOPED_EVENT_UI_PROPS) {
2019 var ui = void 0;
2020 if (typeof UNSCOPED_EVENT_UI_PROPS[name] === 'function') {
2021 val = UNSCOPED_EVENT_UI_PROPS[name](val);
2022 }
2023 if (name === 'color') {
2024 ui = { backgroundColor: val, borderColor: val };
2025 }
2026 else if (name === 'editable') {
2027 ui = { startEditable: val, durationEditable: val };
2028 }
2029 else {
2030 ui = (_b = {}, _b[name] = val, _b);
2031 }
2032 this.mutate({
2033 standardProps: { ui: ui }
2034 });
2035 }
2036 };
2037 EventApi.prototype.setExtendedProp = function (name, val) {
2038 var _a;
2039 this.mutate({
2040 extendedProps: (_a = {}, _a[name] = val, _a)
2041 });
2042 };
2043 EventApi.prototype.setStart = function (startInput, options) {
2044 if (options === void 0) { options = {}; }
2045 var dateEnv = this._calendar.dateEnv;
2046 var start = dateEnv.createMarker(startInput);
2047 if (start && this._instance) { // TODO: warning if parsed bad
2048 var instanceRange = this._instance.range;
2049 var startDelta = diffDates(instanceRange.start, start, dateEnv, options.granularity); // what if parsed bad!?
2050 if (options.maintainDuration) {
2051 this.mutate({ datesDelta: startDelta });
2052 }
2053 else {
2054 this.mutate({ startDelta: startDelta });
2055 }
2056 }
2057 };
2058 EventApi.prototype.setEnd = function (endInput, options) {
2059 if (options === void 0) { options = {}; }
2060 var dateEnv = this._calendar.dateEnv;
2061 var end;
2062 if (endInput != null) {
2063 end = dateEnv.createMarker(endInput);
2064 if (!end) {
2065 return; // TODO: warning if parsed bad
2066 }
2067 }
2068 if (this._instance) {
2069 if (end) {
2070 var endDelta = diffDates(this._instance.range.end, end, dateEnv, options.granularity);
2071 this.mutate({ endDelta: endDelta });
2072 }
2073 else {
2074 this.mutate({ standardProps: { hasEnd: false } });
2075 }
2076 }
2077 };
2078 EventApi.prototype.setDates = function (startInput, endInput, options) {
2079 if (options === void 0) { options = {}; }
2080 var dateEnv = this._calendar.dateEnv;
2081 var standardProps = { allDay: options.allDay };
2082 var start = dateEnv.createMarker(startInput);
2083 var end;
2084 if (!start) {
2085 return; // TODO: warning if parsed bad
2086 }
2087 if (endInput != null) {
2088 end = dateEnv.createMarker(endInput);
2089 if (!end) { // TODO: warning if parsed bad
2090 return;
2091 }
2092 }
2093 if (this._instance) {
2094 var instanceRange = this._instance.range;
2095 // when computing the diff for an event being converted to all-day,
2096 // compute diff off of the all-day values the way event-mutation does.
2097 if (options.allDay === true) {
2098 instanceRange = computeAlignedDayRange(instanceRange);
2099 }
2100 var startDelta = diffDates(instanceRange.start, start, dateEnv, options.granularity);
2101 if (end) {
2102 var endDelta = diffDates(instanceRange.end, end, dateEnv, options.granularity);
2103 if (durationsEqual(startDelta, endDelta)) {
2104 this.mutate({ datesDelta: startDelta, standardProps: standardProps });
2105 }
2106 else {
2107 this.mutate({ startDelta: startDelta, endDelta: endDelta, standardProps: standardProps });
2108 }
2109 }
2110 else { // means "clear the end"
2111 standardProps.hasEnd = false;
2112 this.mutate({ datesDelta: startDelta, standardProps: standardProps });
2113 }
2114 }
2115 };
2116 EventApi.prototype.moveStart = function (deltaInput) {
2117 var delta = createDuration(deltaInput);
2118 if (delta) { // TODO: warning if parsed bad
2119 this.mutate({ startDelta: delta });
2120 }
2121 };
2122 EventApi.prototype.moveEnd = function (deltaInput) {
2123 var delta = createDuration(deltaInput);
2124 if (delta) { // TODO: warning if parsed bad
2125 this.mutate({ endDelta: delta });
2126 }
2127 };
2128 EventApi.prototype.moveDates = function (deltaInput) {
2129 var delta = createDuration(deltaInput);
2130 if (delta) { // TODO: warning if parsed bad
2131 this.mutate({ datesDelta: delta });
2132 }
2133 };
2134 EventApi.prototype.setAllDay = function (allDay, options) {
2135 if (options === void 0) { options = {}; }
2136 var standardProps = { allDay: allDay };
2137 var maintainDuration = options.maintainDuration;
2138 if (maintainDuration == null) {
2139 maintainDuration = this._calendar.opt('allDayMaintainDuration');
2140 }
2141 if (this._def.allDay !== allDay) {
2142 standardProps.hasEnd = maintainDuration;
2143 }
2144 this.mutate({ standardProps: standardProps });
2145 };
2146 EventApi.prototype.formatRange = function (formatInput) {
2147 var dateEnv = this._calendar.dateEnv;
2148 var instance = this._instance;
2149 var formatter = createFormatter(formatInput, this._calendar.opt('defaultRangeSeparator'));
2150 if (this._def.hasEnd) {
2151 return dateEnv.formatRange(instance.range.start, instance.range.end, formatter, {
2152 forcedStartTzo: instance.forcedStartTzo,
2153 forcedEndTzo: instance.forcedEndTzo
2154 });
2155 }
2156 else {
2157 return dateEnv.format(instance.range.start, formatter, {
2158 forcedTzo: instance.forcedStartTzo
2159 });
2160 }
2161 };
2162 EventApi.prototype.mutate = function (mutation) {
2163 var def = this._def;
2164 var instance = this._instance;
2165 if (instance) {
2166 this._calendar.dispatch({
2167 type: 'MUTATE_EVENTS',
2168 instanceId: instance.instanceId,
2169 mutation: mutation,
2170 fromApi: true
2171 });
2172 var eventStore = this._calendar.state.eventStore;
2173 this._def = eventStore.defs[def.defId];
2174 this._instance = eventStore.instances[instance.instanceId];
2175 }
2176 };
2177 EventApi.prototype.remove = function () {
2178 this._calendar.dispatch({
2179 type: 'REMOVE_EVENT_DEF',
2180 defId: this._def.defId
2181 });
2182 };
2183 Object.defineProperty(EventApi.prototype, "source", {
2184 get: function () {
2185 var sourceId = this._def.sourceId;
2186 if (sourceId) {
2187 return new EventSourceApi(this._calendar, this._calendar.state.eventSources[sourceId]);
2188 }
2189 return null;
2190 },
2191 enumerable: true,
2192 configurable: true
2193 });
2194 Object.defineProperty(EventApi.prototype, "start", {
2195 get: function () {
2196 return this._instance ?
2197 this._calendar.dateEnv.toDate(this._instance.range.start) :
2198 null;
2199 },
2200 enumerable: true,
2201 configurable: true
2202 });
2203 Object.defineProperty(EventApi.prototype, "end", {
2204 get: function () {
2205 return (this._instance && this._def.hasEnd) ?
2206 this._calendar.dateEnv.toDate(this._instance.range.end) :
2207 null;
2208 },
2209 enumerable: true,
2210 configurable: true
2211 });
2212 Object.defineProperty(EventApi.prototype, "id", {
2213 // computable props that all access the def
2214 // TODO: find a TypeScript-compatible way to do this at scale
2215 get: function () { return this._def.publicId; },
2216 enumerable: true,
2217 configurable: true
2218 });
2219 Object.defineProperty(EventApi.prototype, "groupId", {
2220 get: function () { return this._def.groupId; },
2221 enumerable: true,
2222 configurable: true
2223 });
2224 Object.defineProperty(EventApi.prototype, "allDay", {
2225 get: function () { return this._def.allDay; },
2226 enumerable: true,
2227 configurable: true
2228 });
2229 Object.defineProperty(EventApi.prototype, "title", {
2230 get: function () { return this._def.title; },
2231 enumerable: true,
2232 configurable: true
2233 });
2234 Object.defineProperty(EventApi.prototype, "url", {
2235 get: function () { return this._def.url; },
2236 enumerable: true,
2237 configurable: true
2238 });
2239 Object.defineProperty(EventApi.prototype, "rendering", {
2240 get: function () { return this._def.rendering; },
2241 enumerable: true,
2242 configurable: true
2243 });
2244 Object.defineProperty(EventApi.prototype, "startEditable", {
2245 get: function () { return this._def.ui.startEditable; },
2246 enumerable: true,
2247 configurable: true
2248 });
2249 Object.defineProperty(EventApi.prototype, "durationEditable", {
2250 get: function () { return this._def.ui.durationEditable; },
2251 enumerable: true,
2252 configurable: true
2253 });
2254 Object.defineProperty(EventApi.prototype, "constraint", {
2255 get: function () { return this._def.ui.constraints[0] || null; },
2256 enumerable: true,
2257 configurable: true
2258 });
2259 Object.defineProperty(EventApi.prototype, "overlap", {
2260 get: function () { return this._def.ui.overlap; },
2261 enumerable: true,
2262 configurable: true
2263 });
2264 Object.defineProperty(EventApi.prototype, "allow", {
2265 get: function () { return this._def.ui.allows[0] || null; },
2266 enumerable: true,
2267 configurable: true
2268 });
2269 Object.defineProperty(EventApi.prototype, "backgroundColor", {
2270 get: function () { return this._def.ui.backgroundColor; },
2271 enumerable: true,
2272 configurable: true
2273 });
2274 Object.defineProperty(EventApi.prototype, "borderColor", {
2275 get: function () { return this._def.ui.borderColor; },
2276 enumerable: true,
2277 configurable: true
2278 });
2279 Object.defineProperty(EventApi.prototype, "textColor", {
2280 get: function () { return this._def.ui.textColor; },
2281 enumerable: true,
2282 configurable: true
2283 });
2284 Object.defineProperty(EventApi.prototype, "classNames", {
2285 // NOTE: user can't modify these because Object.freeze was called in event-def parsing
2286 get: function () { return this._def.ui.classNames; },
2287 enumerable: true,
2288 configurable: true
2289 });
2290 Object.defineProperty(EventApi.prototype, "extendedProps", {
2291 get: function () { return this._def.extendedProps; },
2292 enumerable: true,
2293 configurable: true
2294 });
2295 return EventApi;
2296}());
2297
2298/*
2299Specifying nextDayThreshold signals that all-day ranges should be sliced.
2300*/
2301function sliceEventStore(eventStore, eventUiBases, framingRange, nextDayThreshold) {
2302 var inverseBgByGroupId = {};
2303 var inverseBgByDefId = {};
2304 var defByGroupId = {};
2305 var bgRanges = [];
2306 var fgRanges = [];
2307 var eventUis = compileEventUis(eventStore.defs, eventUiBases);
2308 for (var defId in eventStore.defs) {
2309 var def = eventStore.defs[defId];
2310 if (def.rendering === 'inverse-background') {
2311 if (def.groupId) {
2312 inverseBgByGroupId[def.groupId] = [];
2313 if (!defByGroupId[def.groupId]) {
2314 defByGroupId[def.groupId] = def;
2315 }
2316 }
2317 else {
2318 inverseBgByDefId[defId] = [];
2319 }
2320 }
2321 }
2322 for (var instanceId in eventStore.instances) {
2323 var instance = eventStore.instances[instanceId];
2324 var def = eventStore.defs[instance.defId];
2325 var ui = eventUis[def.defId];
2326 var origRange = instance.range;
2327 var normalRange = (!def.allDay && nextDayThreshold) ?
2328 computeVisibleDayRange(origRange, nextDayThreshold) :
2329 origRange;
2330 var slicedRange = intersectRanges(normalRange, framingRange);
2331 if (slicedRange) {
2332 if (def.rendering === 'inverse-background') {
2333 if (def.groupId) {
2334 inverseBgByGroupId[def.groupId].push(slicedRange);
2335 }
2336 else {
2337 inverseBgByDefId[instance.defId].push(slicedRange);
2338 }
2339 }
2340 else {
2341 (def.rendering === 'background' ? bgRanges : fgRanges).push({
2342 def: def,
2343 ui: ui,
2344 instance: instance,
2345 range: slicedRange,
2346 isStart: normalRange.start && normalRange.start.valueOf() === slicedRange.start.valueOf(),
2347 isEnd: normalRange.end && normalRange.end.valueOf() === slicedRange.end.valueOf()
2348 });
2349 }
2350 }
2351 }
2352 for (var groupId in inverseBgByGroupId) { // BY GROUP
2353 var ranges = inverseBgByGroupId[groupId];
2354 var invertedRanges = invertRanges(ranges, framingRange);
2355 for (var _i = 0, invertedRanges_1 = invertedRanges; _i < invertedRanges_1.length; _i++) {
2356 var invertedRange = invertedRanges_1[_i];
2357 var def = defByGroupId[groupId];
2358 var ui = eventUis[def.defId];
2359 bgRanges.push({
2360 def: def,
2361 ui: ui,
2362 instance: null,
2363 range: invertedRange,
2364 isStart: false,
2365 isEnd: false
2366 });
2367 }
2368 }
2369 for (var defId in inverseBgByDefId) {
2370 var ranges = inverseBgByDefId[defId];
2371 var invertedRanges = invertRanges(ranges, framingRange);
2372 for (var _a = 0, invertedRanges_2 = invertedRanges; _a < invertedRanges_2.length; _a++) {
2373 var invertedRange = invertedRanges_2[_a];
2374 bgRanges.push({
2375 def: eventStore.defs[defId],
2376 ui: eventUis[defId],
2377 instance: null,
2378 range: invertedRange,
2379 isStart: false,
2380 isEnd: false
2381 });
2382 }
2383 }
2384 return { bg: bgRanges, fg: fgRanges };
2385}
2386function hasBgRendering(def) {
2387 return def.rendering === 'background' || def.rendering === 'inverse-background';
2388}
2389function filterSegsViaEls(view, segs, isMirror) {
2390 if (view.hasPublicHandlers('eventRender')) {
2391 segs = segs.filter(function (seg) {
2392 var custom = view.publiclyTrigger('eventRender', [
2393 {
2394 event: new EventApi(view.calendar, seg.eventRange.def, seg.eventRange.instance),
2395 isMirror: isMirror,
2396 isStart: seg.isStart,
2397 isEnd: seg.isEnd,
2398 // TODO: include seg.range once all components consistently generate it
2399 el: seg.el,
2400 view: view
2401 }
2402 ]);
2403 if (custom === false) { // means don't render at all
2404 return false;
2405 }
2406 else if (custom && custom !== true) {
2407 seg.el = custom;
2408 }
2409 return true;
2410 });
2411 }
2412 for (var _i = 0, segs_1 = segs; _i < segs_1.length; _i++) {
2413 var seg = segs_1[_i];
2414 setElSeg(seg.el, seg);
2415 }
2416 return segs;
2417}
2418function setElSeg(el, seg) {
2419 el.fcSeg = seg;
2420}
2421function getElSeg(el) {
2422 return el.fcSeg || null;
2423}
2424// event ui computation
2425function compileEventUis(eventDefs, eventUiBases) {
2426 return mapHash(eventDefs, function (eventDef) {
2427 return compileEventUi(eventDef, eventUiBases);
2428 });
2429}
2430function compileEventUi(eventDef, eventUiBases) {
2431 var uis = [];
2432 if (eventUiBases['']) {
2433 uis.push(eventUiBases['']);
2434 }
2435 if (eventUiBases[eventDef.defId]) {
2436 uis.push(eventUiBases[eventDef.defId]);
2437 }
2438 uis.push(eventDef.ui);
2439 return combineEventUis(uis);
2440}
2441
2442// applies the mutation to ALL defs/instances within the event store
2443function applyMutationToEventStore(eventStore, eventConfigBase, mutation, calendar) {
2444 var eventConfigs = compileEventUis(eventStore.defs, eventConfigBase);
2445 var dest = createEmptyEventStore();
2446 for (var defId in eventStore.defs) {
2447 var def = eventStore.defs[defId];
2448 dest.defs[defId] = applyMutationToEventDef(def, eventConfigs[defId], mutation, calendar.pluginSystem.hooks.eventDefMutationAppliers, calendar);
2449 }
2450 for (var instanceId in eventStore.instances) {
2451 var instance = eventStore.instances[instanceId];
2452 var def = dest.defs[instance.defId]; // important to grab the newly modified def
2453 dest.instances[instanceId] = applyMutationToEventInstance(instance, def, eventConfigs[instance.defId], mutation, calendar);
2454 }
2455 return dest;
2456}
2457function applyMutationToEventDef(eventDef, eventConfig, mutation, appliers, calendar) {
2458 var standardProps = mutation.standardProps || {};
2459 // if hasEnd has not been specified, guess a good value based on deltas.
2460 // if duration will change, there's no way the default duration will persist,
2461 // and thus, we need to mark the event as having a real end
2462 if (standardProps.hasEnd == null &&
2463 eventConfig.durationEditable &&
2464 (mutation.startDelta || mutation.endDelta)) {
2465 standardProps.hasEnd = true; // TODO: is this mutation okay?
2466 }
2467 var copy = __assign({}, eventDef, standardProps, { ui: __assign({}, eventDef.ui, standardProps.ui) });
2468 if (mutation.extendedProps) {
2469 copy.extendedProps = __assign({}, copy.extendedProps, mutation.extendedProps);
2470 }
2471 for (var _i = 0, appliers_1 = appliers; _i < appliers_1.length; _i++) {
2472 var applier = appliers_1[_i];
2473 applier(copy, mutation, calendar);
2474 }
2475 if (!copy.hasEnd && calendar.opt('forceEventDuration')) {
2476 copy.hasEnd = true;
2477 }
2478 return copy;
2479}
2480function applyMutationToEventInstance(eventInstance, eventDef, // must first be modified by applyMutationToEventDef
2481eventConfig, mutation, calendar) {
2482 var dateEnv = calendar.dateEnv;
2483 var forceAllDay = mutation.standardProps && mutation.standardProps.allDay === true;
2484 var clearEnd = mutation.standardProps && mutation.standardProps.hasEnd === false;
2485 var copy = __assign({}, eventInstance);
2486 if (forceAllDay) {
2487 copy.range = computeAlignedDayRange(copy.range);
2488 }
2489 if (mutation.datesDelta && eventConfig.startEditable) {
2490 copy.range = {
2491 start: dateEnv.add(copy.range.start, mutation.datesDelta),
2492 end: dateEnv.add(copy.range.end, mutation.datesDelta)
2493 };
2494 }
2495 if (mutation.startDelta && eventConfig.durationEditable) {
2496 copy.range = {
2497 start: dateEnv.add(copy.range.start, mutation.startDelta),
2498 end: copy.range.end
2499 };
2500 }
2501 if (mutation.endDelta && eventConfig.durationEditable) {
2502 copy.range = {
2503 start: copy.range.start,
2504 end: dateEnv.add(copy.range.end, mutation.endDelta)
2505 };
2506 }
2507 if (clearEnd) {
2508 copy.range = {
2509 start: copy.range.start,
2510 end: calendar.getDefaultEventEnd(eventDef.allDay, copy.range.start)
2511 };
2512 }
2513 // in case event was all-day but the supplied deltas were not
2514 // better util for this?
2515 if (eventDef.allDay) {
2516 copy.range = {
2517 start: startOfDay(copy.range.start),
2518 end: startOfDay(copy.range.end)
2519 };
2520 }
2521 // handle invalid durations
2522 if (copy.range.end < copy.range.start) {
2523 copy.range.end = calendar.getDefaultEventEnd(eventDef.allDay, copy.range.start);
2524 }
2525 return copy;
2526}
2527
2528function reduceEventStore (eventStore, action, eventSources, dateProfile, calendar) {
2529 switch (action.type) {
2530 case 'RECEIVE_EVENTS': // raw
2531 return receiveRawEvents(eventStore, eventSources[action.sourceId], action.fetchId, action.fetchRange, action.rawEvents, calendar);
2532 case 'ADD_EVENTS': // already parsed, but not expanded
2533 return addEvent(eventStore, action.eventStore, // new ones
2534 dateProfile ? dateProfile.activeRange : null, calendar);
2535 case 'MERGE_EVENTS': // already parsed and expanded
2536 return mergeEventStores(eventStore, action.eventStore);
2537 case 'PREV': // TODO: how do we track all actions that affect dateProfile :(
2538 case 'NEXT':
2539 case 'SET_DATE':
2540 case 'SET_VIEW_TYPE':
2541 if (dateProfile) {
2542 return expandRecurring(eventStore, dateProfile.activeRange, calendar);
2543 }
2544 else {
2545 return eventStore;
2546 }
2547 case 'CHANGE_TIMEZONE':
2548 return rezoneDates(eventStore, action.oldDateEnv, calendar.dateEnv);
2549 case 'MUTATE_EVENTS':
2550 return applyMutationToRelated(eventStore, action.instanceId, action.mutation, action.fromApi, calendar);
2551 case 'REMOVE_EVENT_INSTANCES':
2552 return excludeInstances(eventStore, action.instances);
2553 case 'REMOVE_EVENT_DEF':
2554 return filterEventStoreDefs(eventStore, function (eventDef) {
2555 return eventDef.defId !== action.defId;
2556 });
2557 case 'REMOVE_EVENT_SOURCE':
2558 return excludeEventsBySourceId(eventStore, action.sourceId);
2559 case 'REMOVE_ALL_EVENT_SOURCES':
2560 return filterEventStoreDefs(eventStore, function (eventDef) {
2561 return !eventDef.sourceId; // only keep events with no source id
2562 });
2563 case 'REMOVE_ALL_EVENTS':
2564 return createEmptyEventStore();
2565 case 'RESET_EVENTS':
2566 return {
2567 defs: eventStore.defs,
2568 instances: eventStore.instances
2569 };
2570 default:
2571 return eventStore;
2572 }
2573}
2574function receiveRawEvents(eventStore, eventSource, fetchId, fetchRange, rawEvents, calendar) {
2575 if (eventSource && // not already removed
2576 fetchId === eventSource.latestFetchId // TODO: wish this logic was always in event-sources
2577 ) {
2578 var subset = parseEvents(transformRawEvents(rawEvents, eventSource, calendar), eventSource.sourceId, calendar);
2579 if (fetchRange) {
2580 subset = expandRecurring(subset, fetchRange, calendar);
2581 }
2582 return mergeEventStores(excludeEventsBySourceId(eventStore, eventSource.sourceId), subset);
2583 }
2584 return eventStore;
2585}
2586function addEvent(eventStore, subset, expandRange, calendar) {
2587 if (expandRange) {
2588 subset = expandRecurring(subset, expandRange, calendar);
2589 }
2590 return mergeEventStores(eventStore, subset);
2591}
2592function rezoneDates(eventStore, oldDateEnv, newDateEnv) {
2593 var defs = eventStore.defs;
2594 var instances = mapHash(eventStore.instances, function (instance) {
2595 var def = defs[instance.defId];
2596 if (def.allDay || def.recurringDef) {
2597 return instance; // isn't dependent on timezone
2598 }
2599 else {
2600 return __assign({}, instance, { range: {
2601 start: newDateEnv.createMarker(oldDateEnv.toDate(instance.range.start, instance.forcedStartTzo)),
2602 end: newDateEnv.createMarker(oldDateEnv.toDate(instance.range.end, instance.forcedEndTzo))
2603 }, forcedStartTzo: newDateEnv.canComputeOffset ? null : instance.forcedStartTzo, forcedEndTzo: newDateEnv.canComputeOffset ? null : instance.forcedEndTzo });
2604 }
2605 });
2606 return { defs: defs, instances: instances };
2607}
2608function applyMutationToRelated(eventStore, instanceId, mutation, fromApi, calendar) {
2609 var relevant = getRelevantEvents(eventStore, instanceId);
2610 var eventConfigBase = fromApi ?
2611 { '': {
2612 startEditable: true,
2613 durationEditable: true,
2614 constraints: [],
2615 overlap: null,
2616 allows: [],
2617 backgroundColor: '',
2618 borderColor: '',
2619 textColor: '',
2620 classNames: []
2621 } } :
2622 calendar.eventUiBases;
2623 relevant = applyMutationToEventStore(relevant, eventConfigBase, mutation, calendar);
2624 return mergeEventStores(eventStore, relevant);
2625}
2626function excludeEventsBySourceId(eventStore, sourceId) {
2627 return filterEventStoreDefs(eventStore, function (eventDef) {
2628 return eventDef.sourceId !== sourceId;
2629 });
2630}
2631// QUESTION: why not just return instances? do a general object-property-exclusion util
2632function excludeInstances(eventStore, removals) {
2633 return {
2634 defs: eventStore.defs,
2635 instances: filterHash(eventStore.instances, function (instance) {
2636 return !removals[instance.instanceId];
2637 })
2638 };
2639}
2640
2641// high-level segmenting-aware tester functions
2642// ------------------------------------------------------------------------------------------------------------------------
2643function isInteractionValid(interaction, calendar) {
2644 return isNewPropsValid({ eventDrag: interaction }, calendar); // HACK: the eventDrag props is used for ALL interactions
2645}
2646function isDateSelectionValid(dateSelection, calendar) {
2647 return isNewPropsValid({ dateSelection: dateSelection }, calendar);
2648}
2649function isNewPropsValid(newProps, calendar) {
2650 var view = calendar.view;
2651 var props = __assign({ businessHours: view ? view.props.businessHours : createEmptyEventStore(), dateSelection: '', eventStore: calendar.state.eventStore, eventUiBases: calendar.eventUiBases, eventSelection: '', eventDrag: null, eventResize: null }, newProps);
2652 return (calendar.pluginSystem.hooks.isPropsValid || isPropsValid)(props, calendar);
2653}
2654function isPropsValid(state, calendar, dateSpanMeta, filterConfig) {
2655 if (dateSpanMeta === void 0) { dateSpanMeta = {}; }
2656 if (state.eventDrag && !isInteractionPropsValid(state, calendar, dateSpanMeta, filterConfig)) {
2657 return false;
2658 }
2659 if (state.dateSelection && !isDateSelectionPropsValid(state, calendar, dateSpanMeta, filterConfig)) {
2660 return false;
2661 }
2662 return true;
2663}
2664// Moving Event Validation
2665// ------------------------------------------------------------------------------------------------------------------------
2666function isInteractionPropsValid(state, calendar, dateSpanMeta, filterConfig) {
2667 var interaction = state.eventDrag; // HACK: the eventDrag props is used for ALL interactions
2668 var subjectEventStore = interaction.mutatedEvents;
2669 var subjectDefs = subjectEventStore.defs;
2670 var subjectInstances = subjectEventStore.instances;
2671 var subjectConfigs = compileEventUis(subjectDefs, interaction.isEvent ?
2672 state.eventUiBases :
2673 { '': calendar.selectionConfig } // if not a real event, validate as a selection
2674 );
2675 if (filterConfig) {
2676 subjectConfigs = mapHash(subjectConfigs, filterConfig);
2677 }
2678 var otherEventStore = excludeInstances(state.eventStore, interaction.affectedEvents.instances); // exclude the subject events. TODO: exclude defs too?
2679 var otherDefs = otherEventStore.defs;
2680 var otherInstances = otherEventStore.instances;
2681 var otherConfigs = compileEventUis(otherDefs, state.eventUiBases);
2682 for (var subjectInstanceId in subjectInstances) {
2683 var subjectInstance = subjectInstances[subjectInstanceId];
2684 var subjectRange = subjectInstance.range;
2685 var subjectConfig = subjectConfigs[subjectInstance.defId];
2686 var subjectDef = subjectDefs[subjectInstance.defId];
2687 // constraint
2688 if (!allConstraintsPass(subjectConfig.constraints, subjectRange, otherEventStore, state.businessHours, calendar)) {
2689 return false;
2690 }
2691 // overlap
2692 var overlapFunc = calendar.opt('eventOverlap');
2693 if (typeof overlapFunc !== 'function') {
2694 overlapFunc = null;
2695 }
2696 for (var otherInstanceId in otherInstances) {
2697 var otherInstance = otherInstances[otherInstanceId];
2698 // intersect! evaluate
2699 if (rangesIntersect(subjectRange, otherInstance.range)) {
2700 var otherOverlap = otherConfigs[otherInstance.defId].overlap;
2701 // consider the other event's overlap. only do this if the subject event is a "real" event
2702 if (otherOverlap === false && interaction.isEvent) {
2703 return false;
2704 }
2705 if (subjectConfig.overlap === false) {
2706 return false;
2707 }
2708 if (overlapFunc && !overlapFunc(new EventApi(calendar, otherDefs[otherInstance.defId], otherInstance), // still event
2709 new EventApi(calendar, subjectDef, subjectInstance) // moving event
2710 )) {
2711 return false;
2712 }
2713 }
2714 }
2715 // allow (a function)
2716 var calendarEventStore = calendar.state.eventStore; // need global-to-calendar, not local to component (splittable)state
2717 for (var _i = 0, _a = subjectConfig.allows; _i < _a.length; _i++) {
2718 var subjectAllow = _a[_i];
2719 var subjectDateSpan = __assign({}, dateSpanMeta, { range: subjectInstance.range, allDay: subjectDef.allDay });
2720 var origDef = calendarEventStore.defs[subjectDef.defId];
2721 var origInstance = calendarEventStore.instances[subjectInstanceId];
2722 var eventApi = void 0;
2723 if (origDef) { // was previously in the calendar
2724 eventApi = new EventApi(calendar, origDef, origInstance);
2725 }
2726 else { // was an external event
2727 eventApi = new EventApi(calendar, subjectDef); // no instance, because had no dates
2728 }
2729 if (!subjectAllow(calendar.buildDateSpanApi(subjectDateSpan), eventApi)) {
2730 return false;
2731 }
2732 }
2733 }
2734 return true;
2735}
2736// Date Selection Validation
2737// ------------------------------------------------------------------------------------------------------------------------
2738function isDateSelectionPropsValid(state, calendar, dateSpanMeta, filterConfig) {
2739 var relevantEventStore = state.eventStore;
2740 var relevantDefs = relevantEventStore.defs;
2741 var relevantInstances = relevantEventStore.instances;
2742 var selection = state.dateSelection;
2743 var selectionRange = selection.range;
2744 var selectionConfig = calendar.selectionConfig;
2745 if (filterConfig) {
2746 selectionConfig = filterConfig(selectionConfig);
2747 }
2748 // constraint
2749 if (!allConstraintsPass(selectionConfig.constraints, selectionRange, relevantEventStore, state.businessHours, calendar)) {
2750 return false;
2751 }
2752 // overlap
2753 var overlapFunc = calendar.opt('selectOverlap');
2754 if (typeof overlapFunc !== 'function') {
2755 overlapFunc = null;
2756 }
2757 for (var relevantInstanceId in relevantInstances) {
2758 var relevantInstance = relevantInstances[relevantInstanceId];
2759 // intersect! evaluate
2760 if (rangesIntersect(selectionRange, relevantInstance.range)) {
2761 if (selectionConfig.overlap === false) {
2762 return false;
2763 }
2764 if (overlapFunc && !overlapFunc(new EventApi(calendar, relevantDefs[relevantInstance.defId], relevantInstance))) {
2765 return false;
2766 }
2767 }
2768 }
2769 // allow (a function)
2770 for (var _i = 0, _a = selectionConfig.allows; _i < _a.length; _i++) {
2771 var selectionAllow = _a[_i];
2772 var fullDateSpan = __assign({}, dateSpanMeta, selection);
2773 if (!selectionAllow(calendar.buildDateSpanApi(fullDateSpan), null)) {
2774 return false;
2775 }
2776 }
2777 return true;
2778}
2779// Constraint Utils
2780// ------------------------------------------------------------------------------------------------------------------------
2781function allConstraintsPass(constraints, subjectRange, otherEventStore, businessHoursUnexpanded, calendar) {
2782 for (var _i = 0, constraints_1 = constraints; _i < constraints_1.length; _i++) {
2783 var constraint = constraints_1[_i];
2784 if (!anyRangesContainRange(constraintToRanges(constraint, subjectRange, otherEventStore, businessHoursUnexpanded, calendar), subjectRange)) {
2785 return false;
2786 }
2787 }
2788 return true;
2789}
2790function constraintToRanges(constraint, subjectRange, // for expanding a recurring constraint, or expanding business hours
2791otherEventStore, // for if constraint is an even group ID
2792businessHoursUnexpanded, // for if constraint is 'businessHours'
2793calendar // for expanding businesshours
2794) {
2795 if (constraint === 'businessHours') {
2796 return eventStoreToRanges(expandRecurring(businessHoursUnexpanded, subjectRange, calendar));
2797 }
2798 else if (typeof constraint === 'string') { // an group ID
2799 return eventStoreToRanges(filterEventStoreDefs(otherEventStore, function (eventDef) {
2800 return eventDef.groupId === constraint;
2801 }));
2802 }
2803 else if (typeof constraint === 'object' && constraint) { // non-null object
2804 return eventStoreToRanges(expandRecurring(constraint, subjectRange, calendar));
2805 }
2806 return []; // if it's false
2807}
2808// TODO: move to event-store file?
2809function eventStoreToRanges(eventStore) {
2810 var instances = eventStore.instances;
2811 var ranges = [];
2812 for (var instanceId in instances) {
2813 ranges.push(instances[instanceId].range);
2814 }
2815 return ranges;
2816}
2817// TODO: move to geom file?
2818function anyRangesContainRange(outerRanges, innerRange) {
2819 for (var _i = 0, outerRanges_1 = outerRanges; _i < outerRanges_1.length; _i++) {
2820 var outerRange = outerRanges_1[_i];
2821 if (rangeContainsRange(outerRange, innerRange)) {
2822 return true;
2823 }
2824 }
2825 return false;
2826}
2827// Parsing
2828// ------------------------------------------------------------------------------------------------------------------------
2829function normalizeConstraint(input, calendar) {
2830 if (Array.isArray(input)) {
2831 return parseEvents(input, '', calendar, true); // allowOpenRange=true
2832 }
2833 else if (typeof input === 'object' && input) { // non-null object
2834 return parseEvents([input], '', calendar, true); // allowOpenRange=true
2835 }
2836 else if (input != null) {
2837 return String(input);
2838 }
2839 else {
2840 return null;
2841 }
2842}
2843
2844function htmlEscape(s) {
2845 return (s + '').replace(/&/g, '&')
2846 .replace(/</g, '<')
2847 .replace(/>/g, '>')
2848 .replace(/'/g, ''')
2849 .replace(/"/g, '"')
2850 .replace(/\n/g, '<br />');
2851}
2852// Given a hash of CSS properties, returns a string of CSS.
2853// Uses property names as-is (no camel-case conversion). Will not make statements for null/undefined values.
2854function cssToStr(cssProps) {
2855 var statements = [];
2856 for (var name_1 in cssProps) {
2857 var val = cssProps[name_1];
2858 if (val != null && val !== '') {
2859 statements.push(name_1 + ':' + val);
2860 }
2861 }
2862 return statements.join(';');
2863}
2864// Given an object hash of HTML attribute names to values,
2865// generates a string that can be injected between < > in HTML
2866function attrsToStr(attrs) {
2867 var parts = [];
2868 for (var name_2 in attrs) {
2869 var val = attrs[name_2];
2870 if (val != null) {
2871 parts.push(name_2 + '="' + htmlEscape(val) + '"');
2872 }
2873 }
2874 return parts.join(' ');
2875}
2876function parseClassName(raw) {
2877 if (Array.isArray(raw)) {
2878 return raw;
2879 }
2880 else if (typeof raw === 'string') {
2881 return raw.split(/\s+/);
2882 }
2883 else {
2884 return [];
2885 }
2886}
2887
2888var UNSCOPED_EVENT_UI_PROPS = {
2889 editable: Boolean,
2890 startEditable: Boolean,
2891 durationEditable: Boolean,
2892 constraint: null,
2893 overlap: null,
2894 allow: null,
2895 className: parseClassName,
2896 classNames: parseClassName,
2897 color: String,
2898 backgroundColor: String,
2899 borderColor: String,
2900 textColor: String
2901};
2902function processUnscopedUiProps(rawProps, calendar, leftovers) {
2903 var props = refineProps(rawProps, UNSCOPED_EVENT_UI_PROPS, {}, leftovers);
2904 var constraint = normalizeConstraint(props.constraint, calendar);
2905 return {
2906 startEditable: props.startEditable != null ? props.startEditable : props.editable,
2907 durationEditable: props.durationEditable != null ? props.durationEditable : props.editable,
2908 constraints: constraint != null ? [constraint] : [],
2909 overlap: props.overlap,
2910 allows: props.allow != null ? [props.allow] : [],
2911 backgroundColor: props.backgroundColor || props.color,
2912 borderColor: props.borderColor || props.color,
2913 textColor: props.textColor,
2914 classNames: props.classNames.concat(props.className)
2915 };
2916}
2917function processScopedUiProps(prefix, rawScoped, calendar, leftovers) {
2918 var rawUnscoped = {};
2919 var wasFound = {};
2920 for (var key in UNSCOPED_EVENT_UI_PROPS) {
2921 var scopedKey = prefix + capitaliseFirstLetter(key);
2922 rawUnscoped[key] = rawScoped[scopedKey];
2923 wasFound[scopedKey] = true;
2924 }
2925 if (prefix === 'event') {
2926 rawUnscoped.editable = rawScoped.editable; // special case. there is no 'eventEditable', just 'editable'
2927 }
2928 if (leftovers) {
2929 for (var key in rawScoped) {
2930 if (!wasFound[key]) {
2931 leftovers[key] = rawScoped[key];
2932 }
2933 }
2934 }
2935 return processUnscopedUiProps(rawUnscoped, calendar);
2936}
2937var EMPTY_EVENT_UI = {
2938 startEditable: null,
2939 durationEditable: null,
2940 constraints: [],
2941 overlap: null,
2942 allows: [],
2943 backgroundColor: '',
2944 borderColor: '',
2945 textColor: '',
2946 classNames: []
2947};
2948// prevent against problems with <2 args!
2949function combineEventUis(uis) {
2950 return uis.reduce(combineTwoEventUis, EMPTY_EVENT_UI);
2951}
2952function combineTwoEventUis(item0, item1) {
2953 return {
2954 startEditable: item1.startEditable != null ? item1.startEditable : item0.startEditable,
2955 durationEditable: item1.durationEditable != null ? item1.durationEditable : item0.durationEditable,
2956 constraints: item0.constraints.concat(item1.constraints),
2957 overlap: typeof item1.overlap === 'boolean' ? item1.overlap : item0.overlap,
2958 allows: item0.allows.concat(item1.allows),
2959 backgroundColor: item1.backgroundColor || item0.backgroundColor,
2960 borderColor: item1.borderColor || item0.borderColor,
2961 textColor: item1.textColor || item0.textColor,
2962 classNames: item0.classNames.concat(item1.classNames)
2963 };
2964}
2965
2966var NON_DATE_PROPS = {
2967 id: String,
2968 groupId: String,
2969 title: String,
2970 url: String,
2971 rendering: String,
2972 extendedProps: null
2973};
2974var DATE_PROPS = {
2975 start: null,
2976 date: null,
2977 end: null,
2978 allDay: null
2979};
2980var uid = 0;
2981function parseEvent(raw, sourceId, calendar, allowOpenRange) {
2982 var allDayDefault = computeIsAllDayDefault(sourceId, calendar);
2983 var leftovers0 = {};
2984 var recurringRes = parseRecurring(raw, // raw, but with single-event stuff stripped out
2985 allDayDefault, calendar.dateEnv, calendar.pluginSystem.hooks.recurringTypes, leftovers0 // will populate with non-recurring props
2986 );
2987 if (recurringRes) {
2988 var def = parseEventDef(leftovers0, sourceId, recurringRes.allDay, Boolean(recurringRes.duration), calendar);
2989 def.recurringDef = {
2990 typeId: recurringRes.typeId,
2991 typeData: recurringRes.typeData,
2992 duration: recurringRes.duration
2993 };
2994 return { def: def, instance: null };
2995 }
2996 else {
2997 var leftovers1 = {};
2998 var singleRes = parseSingle(raw, allDayDefault, calendar, leftovers1, allowOpenRange);
2999 if (singleRes) {
3000 var def = parseEventDef(leftovers1, sourceId, singleRes.allDay, singleRes.hasEnd, calendar);
3001 var instance = createEventInstance(def.defId, singleRes.range, singleRes.forcedStartTzo, singleRes.forcedEndTzo);
3002 return { def: def, instance: instance };
3003 }
3004 }
3005 return null;
3006}
3007/*
3008Will NOT populate extendedProps with the leftover properties.
3009Will NOT populate date-related props.
3010The EventNonDateInput has been normalized (id => publicId, etc).
3011*/
3012function parseEventDef(raw, sourceId, allDay, hasEnd, calendar) {
3013 var leftovers = {};
3014 var def = pluckNonDateProps(raw, calendar, leftovers);
3015 def.defId = String(uid++);
3016 def.sourceId = sourceId;
3017 def.allDay = allDay;
3018 def.hasEnd = hasEnd;
3019 for (var _i = 0, _a = calendar.pluginSystem.hooks.eventDefParsers; _i < _a.length; _i++) {
3020 var eventDefParser = _a[_i];
3021 var newLeftovers = {};
3022 eventDefParser(def, leftovers, newLeftovers);
3023 leftovers = newLeftovers;
3024 }
3025 def.extendedProps = __assign(leftovers, def.extendedProps || {});
3026 // help out EventApi from having user modify props
3027 Object.freeze(def.ui.classNames);
3028 Object.freeze(def.extendedProps);
3029 return def;
3030}
3031function createEventInstance(defId, range, forcedStartTzo, forcedEndTzo) {
3032 return {
3033 instanceId: String(uid++),
3034 defId: defId,
3035 range: range,
3036 forcedStartTzo: forcedStartTzo == null ? null : forcedStartTzo,
3037 forcedEndTzo: forcedEndTzo == null ? null : forcedEndTzo
3038 };
3039}
3040function parseSingle(raw, allDayDefault, calendar, leftovers, allowOpenRange) {
3041 var props = pluckDateProps(raw, leftovers);
3042 var allDay = props.allDay;
3043 var startMeta;
3044 var startMarker = null;
3045 var hasEnd = false;
3046 var endMeta;
3047 var endMarker = null;
3048 startMeta = calendar.dateEnv.createMarkerMeta(props.start);
3049 if (startMeta) {
3050 startMarker = startMeta.marker;
3051 }
3052 else if (!allowOpenRange) {
3053 return null;
3054 }
3055 if (props.end != null) {
3056 endMeta = calendar.dateEnv.createMarkerMeta(props.end);
3057 }
3058 if (allDay == null) {
3059 if (allDayDefault != null) {
3060 allDay = allDayDefault;
3061 }
3062 else {
3063 // fall back to the date props LAST
3064 allDay = (!startMeta || startMeta.isTimeUnspecified) &&
3065 (!endMeta || endMeta.isTimeUnspecified);
3066 }
3067 }
3068 if (allDay && startMarker) {
3069 startMarker = startOfDay(startMarker);
3070 }
3071 if (endMeta) {
3072 endMarker = endMeta.marker;
3073 if (allDay) {
3074 endMarker = startOfDay(endMarker);
3075 }
3076 if (startMarker && endMarker <= startMarker) {
3077 endMarker = null;
3078 }
3079 }
3080 if (endMarker) {
3081 hasEnd = true;
3082 }
3083 else if (!allowOpenRange) {
3084 hasEnd = calendar.opt('forceEventDuration') || false;
3085 endMarker = calendar.dateEnv.add(startMarker, allDay ?
3086 calendar.defaultAllDayEventDuration :
3087 calendar.defaultTimedEventDuration);
3088 }
3089 return {
3090 allDay: allDay,
3091 hasEnd: hasEnd,
3092 range: { start: startMarker, end: endMarker },
3093 forcedStartTzo: startMeta ? startMeta.forcedTzo : null,
3094 forcedEndTzo: endMeta ? endMeta.forcedTzo : null
3095 };
3096}
3097function pluckDateProps(raw, leftovers) {
3098 var props = refineProps(raw, DATE_PROPS, {}, leftovers);
3099 props.start = (props.start !== null) ? props.start : props.date;
3100 delete props.date;
3101 return props;
3102}
3103function pluckNonDateProps(raw, calendar, leftovers) {
3104 var preLeftovers = {};
3105 var props = refineProps(raw, NON_DATE_PROPS, {}, preLeftovers);
3106 var ui = processUnscopedUiProps(preLeftovers, calendar, leftovers);
3107 props.publicId = props.id;
3108 delete props.id;
3109 props.ui = ui;
3110 return props;
3111}
3112function computeIsAllDayDefault(sourceId, calendar) {
3113 var res = null;
3114 if (sourceId) {
3115 var source = calendar.state.eventSources[sourceId];
3116 res = source.allDayDefault;
3117 }
3118 if (res == null) {
3119 res = calendar.opt('allDayDefault');
3120 }
3121 return res;
3122}
3123
3124var DEF_DEFAULTS = {
3125 startTime: '09:00',
3126 endTime: '17:00',
3127 daysOfWeek: [1, 2, 3, 4, 5],
3128 rendering: 'inverse-background',
3129 classNames: 'fc-nonbusiness',
3130 groupId: '_businessHours' // so multiple defs get grouped
3131};
3132/*
3133TODO: pass around as EventDefHash!!!
3134*/
3135function parseBusinessHours(input, calendar) {
3136 return parseEvents(refineInputs(input), '', calendar);
3137}
3138function refineInputs(input) {
3139 var rawDefs;
3140 if (input === true) {
3141 rawDefs = [{}]; // will get DEF_DEFAULTS verbatim
3142 }
3143 else if (Array.isArray(input)) {
3144 // if specifying an array, every sub-definition NEEDS a day-of-week
3145 rawDefs = input.filter(function (rawDef) {
3146 return rawDef.daysOfWeek;
3147 });
3148 }
3149 else if (typeof input === 'object' && input) { // non-null object
3150 rawDefs = [input];
3151 }
3152 else { // is probably false
3153 rawDefs = [];
3154 }
3155 rawDefs = rawDefs.map(function (rawDef) {
3156 return __assign({}, DEF_DEFAULTS, rawDef);
3157 });
3158 return rawDefs;
3159}
3160
3161function memoizeRendering(renderFunc, unrenderFunc, dependencies) {
3162 if (dependencies === void 0) { dependencies = []; }
3163 var dependents = [];
3164 var thisContext;
3165 var prevArgs;
3166 function unrender() {
3167 if (prevArgs) {
3168 for (var _i = 0, dependents_1 = dependents; _i < dependents_1.length; _i++) {
3169 var dependent = dependents_1[_i];
3170 dependent.unrender();
3171 }
3172 if (unrenderFunc) {
3173 unrenderFunc.apply(thisContext, prevArgs);
3174 }
3175 prevArgs = null;
3176 }
3177 }
3178 function res() {
3179 if (!prevArgs || !isArraysEqual(prevArgs, arguments)) {
3180 unrender();
3181 thisContext = this;
3182 prevArgs = arguments;
3183 renderFunc.apply(this, arguments);
3184 }
3185 }
3186 res.dependents = dependents;
3187 res.unrender = unrender;
3188 for (var _i = 0, dependencies_1 = dependencies; _i < dependencies_1.length; _i++) {
3189 var dependency = dependencies_1[_i];
3190 dependency.dependents.push(res);
3191 }
3192 return res;
3193}
3194
3195var EMPTY_EVENT_STORE = createEmptyEventStore(); // for purecomponents. TODO: keep elsewhere
3196var Splitter = /** @class */ (function () {
3197 function Splitter() {
3198 this.getKeysForEventDefs = memoize(this._getKeysForEventDefs);
3199 this.splitDateSelection = memoize(this._splitDateSpan);
3200 this.splitEventStore = memoize(this._splitEventStore);
3201 this.splitIndividualUi = memoize(this._splitIndividualUi);
3202 this.splitEventDrag = memoize(this._splitInteraction);
3203 this.splitEventResize = memoize(this._splitInteraction);
3204 this.eventUiBuilders = {}; // TODO: typescript protection
3205 }
3206 Splitter.prototype.splitProps = function (props) {
3207 var _this = this;
3208 var keyInfos = this.getKeyInfo(props);
3209 var defKeys = this.getKeysForEventDefs(props.eventStore);
3210 var dateSelections = this.splitDateSelection(props.dateSelection);
3211 var individualUi = this.splitIndividualUi(props.eventUiBases, defKeys); // the individual *bases*
3212 var eventStores = this.splitEventStore(props.eventStore, defKeys);
3213 var eventDrags = this.splitEventDrag(props.eventDrag);
3214 var eventResizes = this.splitEventResize(props.eventResize);
3215 var splitProps = {};
3216 this.eventUiBuilders = mapHash(keyInfos, function (info, key) {
3217 return _this.eventUiBuilders[key] || memoize(buildEventUiForKey);
3218 });
3219 for (var key in keyInfos) {
3220 var keyInfo = keyInfos[key];
3221 var eventStore = eventStores[key] || EMPTY_EVENT_STORE;
3222 var buildEventUi = this.eventUiBuilders[key];
3223 splitProps[key] = {
3224 businessHours: keyInfo.businessHours || props.businessHours,
3225 dateSelection: dateSelections[key] || null,
3226 eventStore: eventStore,
3227 eventUiBases: buildEventUi(props.eventUiBases[''], keyInfo.ui, individualUi[key]),
3228 eventSelection: eventStore.instances[props.eventSelection] ? props.eventSelection : '',
3229 eventDrag: eventDrags[key] || null,
3230 eventResize: eventResizes[key] || null
3231 };
3232 }
3233 return splitProps;
3234 };
3235 Splitter.prototype._splitDateSpan = function (dateSpan) {
3236 var dateSpans = {};
3237 if (dateSpan) {
3238 var keys = this.getKeysForDateSpan(dateSpan);
3239 for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
3240 var key = keys_1[_i];
3241 dateSpans[key] = dateSpan;
3242 }
3243 }
3244 return dateSpans;
3245 };
3246 Splitter.prototype._getKeysForEventDefs = function (eventStore) {
3247 var _this = this;
3248 return mapHash(eventStore.defs, function (eventDef) {
3249 return _this.getKeysForEventDef(eventDef);
3250 });
3251 };
3252 Splitter.prototype._splitEventStore = function (eventStore, defKeys) {
3253 var defs = eventStore.defs, instances = eventStore.instances;
3254 var splitStores = {};
3255 for (var defId in defs) {
3256 for (var _i = 0, _a = defKeys[defId]; _i < _a.length; _i++) {
3257 var key = _a[_i];
3258 if (!splitStores[key]) {
3259 splitStores[key] = createEmptyEventStore();
3260 }
3261 splitStores[key].defs[defId] = defs[defId];
3262 }
3263 }
3264 for (var instanceId in instances) {
3265 var instance = instances[instanceId];
3266 for (var _b = 0, _c = defKeys[instance.defId]; _b < _c.length; _b++) {
3267 var key = _c[_b];
3268 if (splitStores[key]) { // must have already been created
3269 splitStores[key].instances[instanceId] = instance;
3270 }
3271 }
3272 }
3273 return splitStores;
3274 };
3275 Splitter.prototype._splitIndividualUi = function (eventUiBases, defKeys) {
3276 var splitHashes = {};
3277 for (var defId in eventUiBases) {
3278 if (defId) { // not the '' key
3279 for (var _i = 0, _a = defKeys[defId]; _i < _a.length; _i++) {
3280 var key = _a[_i];
3281 if (!splitHashes[key]) {
3282 splitHashes[key] = {};
3283 }
3284 splitHashes[key][defId] = eventUiBases[defId];
3285 }
3286 }
3287 }
3288 return splitHashes;
3289 };
3290 Splitter.prototype._splitInteraction = function (interaction) {
3291 var splitStates = {};
3292 if (interaction) {
3293 var affectedStores_1 = this._splitEventStore(interaction.affectedEvents, this._getKeysForEventDefs(interaction.affectedEvents) // can't use cached. might be events from other calendar
3294 );
3295 // can't rely on defKeys because event data is mutated
3296 var mutatedKeysByDefId = this._getKeysForEventDefs(interaction.mutatedEvents);
3297 var mutatedStores_1 = this._splitEventStore(interaction.mutatedEvents, mutatedKeysByDefId);
3298 var populate = function (key) {
3299 if (!splitStates[key]) {
3300 splitStates[key] = {
3301 affectedEvents: affectedStores_1[key] || EMPTY_EVENT_STORE,
3302 mutatedEvents: mutatedStores_1[key] || EMPTY_EVENT_STORE,
3303 isEvent: interaction.isEvent,
3304 origSeg: interaction.origSeg
3305 };
3306 }
3307 };
3308 for (var key in affectedStores_1) {
3309 populate(key);
3310 }
3311 for (var key in mutatedStores_1) {
3312 populate(key);
3313 }
3314 }
3315 return splitStates;
3316 };
3317 return Splitter;
3318}());
3319function buildEventUiForKey(allUi, eventUiForKey, individualUi) {
3320 var baseParts = [];
3321 if (allUi) {
3322 baseParts.push(allUi);
3323 }
3324 if (eventUiForKey) {
3325 baseParts.push(eventUiForKey);
3326 }
3327 var stuff = {
3328 '': combineEventUis(baseParts)
3329 };
3330 if (individualUi) {
3331 __assign(stuff, individualUi);
3332 }
3333 return stuff;
3334}
3335
3336// Generates HTML for an anchor to another view into the calendar.
3337// Will either generate an <a> tag or a non-clickable <span> tag, depending on enabled settings.
3338// `gotoOptions` can either be a DateMarker, or an object with the form:
3339// { date, type, forceOff }
3340// `type` is a view-type like "day" or "week". default value is "day".
3341// `attrs` and `innerHtml` are use to generate the rest of the HTML tag.
3342function buildGotoAnchorHtml(component, gotoOptions, attrs, innerHtml) {
3343 var dateEnv = component.dateEnv;
3344 var date;
3345 var type;
3346 var forceOff;
3347 var finalOptions;
3348 if (gotoOptions instanceof Date) {
3349 date = gotoOptions; // a single date-like input
3350 }
3351 else {
3352 date = gotoOptions.date;
3353 type = gotoOptions.type;
3354 forceOff = gotoOptions.forceOff;
3355 }
3356 finalOptions = {
3357 date: dateEnv.formatIso(date, { omitTime: true }),
3358 type: type || 'day'
3359 };
3360 if (typeof attrs === 'string') {
3361 innerHtml = attrs;
3362 attrs = null;
3363 }
3364 attrs = attrs ? ' ' + attrsToStr(attrs) : ''; // will have a leading space
3365 innerHtml = innerHtml || '';
3366 if (!forceOff && component.opt('navLinks')) {
3367 return '<a' + attrs +
3368 ' data-goto="' + htmlEscape(JSON.stringify(finalOptions)) + '">' +
3369 innerHtml +
3370 '</a>';
3371 }
3372 else {
3373 return '<span' + attrs + '>' +
3374 innerHtml +
3375 '</span>';
3376 }
3377}
3378function getAllDayHtml(component) {
3379 return component.opt('allDayHtml') || htmlEscape(component.opt('allDayText'));
3380}
3381// Computes HTML classNames for a single-day element
3382function getDayClasses(date, dateProfile, context, noThemeHighlight) {
3383 var calendar = context.calendar, view = context.view, theme = context.theme, dateEnv = context.dateEnv;
3384 var classes = [];
3385 var todayStart;
3386 var todayEnd;
3387 if (!rangeContainsMarker(dateProfile.activeRange, date)) {
3388 classes.push('fc-disabled-day');
3389 }
3390 else {
3391 classes.push('fc-' + DAY_IDS[date.getUTCDay()]);
3392 if (view.opt('monthMode') &&
3393 dateEnv.getMonth(date) !== dateEnv.getMonth(dateProfile.currentRange.start)) {
3394 classes.push('fc-other-month');
3395 }
3396 todayStart = startOfDay(calendar.getNow());
3397 todayEnd = addDays(todayStart, 1);
3398 if (date < todayStart) {
3399 classes.push('fc-past');
3400 }
3401 else if (date >= todayEnd) {
3402 classes.push('fc-future');
3403 }
3404 else {
3405 classes.push('fc-today');
3406 if (noThemeHighlight !== true) {
3407 classes.push(theme.getClass('today'));
3408 }
3409 }
3410 }
3411 return classes;
3412}
3413
3414// given a function that resolves a result asynchronously.
3415// the function can either call passed-in success and failure callbacks,
3416// or it can return a promise.
3417// if you need to pass additional params to func, bind them first.
3418function unpromisify(func, success, failure) {
3419 // guard against success/failure callbacks being called more than once
3420 // and guard against a promise AND callback being used together.
3421 var isResolved = false;
3422 var wrappedSuccess = function () {
3423 if (!isResolved) {
3424 isResolved = true;
3425 success.apply(this, arguments);
3426 }
3427 };
3428 var wrappedFailure = function () {
3429 if (!isResolved) {
3430 isResolved = true;
3431 if (failure) {
3432 failure.apply(this, arguments);
3433 }
3434 }
3435 };
3436 var res = func(wrappedSuccess, wrappedFailure);
3437 if (res && typeof res.then === 'function') {
3438 res.then(wrappedSuccess, wrappedFailure);
3439 }
3440}
3441
3442var Mixin = /** @class */ (function () {
3443 function Mixin() {
3444 }
3445 // mix into a CLASS
3446 Mixin.mixInto = function (destClass) {
3447 this.mixIntoObj(destClass.prototype);
3448 };
3449 // mix into ANY object
3450 Mixin.mixIntoObj = function (destObj) {
3451 var _this = this;
3452 Object.getOwnPropertyNames(this.prototype).forEach(function (name) {
3453 if (!destObj[name]) { // if destination doesn't already define it
3454 destObj[name] = _this.prototype[name];
3455 }
3456 });
3457 };
3458 /*
3459 will override existing methods
3460 TODO: remove! not used anymore
3461 */
3462 Mixin.mixOver = function (destClass) {
3463 var _this = this;
3464 Object.getOwnPropertyNames(this.prototype).forEach(function (name) {
3465 destClass.prototype[name] = _this.prototype[name];
3466 });
3467 };
3468 return Mixin;
3469}());
3470
3471/*
3472USAGE:
3473 import { default as EmitterMixin, EmitterInterface } from './EmitterMixin'
3474in class:
3475 on: EmitterInterface['on']
3476 one: EmitterInterface['one']
3477 off: EmitterInterface['off']
3478 trigger: EmitterInterface['trigger']
3479 triggerWith: EmitterInterface['triggerWith']
3480 hasHandlers: EmitterInterface['hasHandlers']
3481after class:
3482 EmitterMixin.mixInto(TheClass)
3483*/
3484var EmitterMixin = /** @class */ (function (_super) {
3485 __extends(EmitterMixin, _super);
3486 function EmitterMixin() {
3487 return _super !== null && _super.apply(this, arguments) || this;
3488 }
3489 EmitterMixin.prototype.on = function (type, handler) {
3490 addToHash(this._handlers || (this._handlers = {}), type, handler);
3491 return this; // for chaining
3492 };
3493 // todo: add comments
3494 EmitterMixin.prototype.one = function (type, handler) {
3495 addToHash(this._oneHandlers || (this._oneHandlers = {}), type, handler);
3496 return this; // for chaining
3497 };
3498 EmitterMixin.prototype.off = function (type, handler) {
3499 if (this._handlers) {
3500 removeFromHash(this._handlers, type, handler);
3501 }
3502 if (this._oneHandlers) {
3503 removeFromHash(this._oneHandlers, type, handler);
3504 }
3505 return this; // for chaining
3506 };
3507 EmitterMixin.prototype.trigger = function (type) {
3508 var args = [];
3509 for (var _i = 1; _i < arguments.length; _i++) {
3510 args[_i - 1] = arguments[_i];
3511 }
3512 this.triggerWith(type, this, args);
3513 return this; // for chaining
3514 };
3515 EmitterMixin.prototype.triggerWith = function (type, context, args) {
3516 if (this._handlers) {
3517 applyAll(this._handlers[type], context, args);
3518 }
3519 if (this._oneHandlers) {
3520 applyAll(this._oneHandlers[type], context, args);
3521 delete this._oneHandlers[type]; // will never fire again
3522 }
3523 return this; // for chaining
3524 };
3525 EmitterMixin.prototype.hasHandlers = function (type) {
3526 return (this._handlers && this._handlers[type] && this._handlers[type].length) ||
3527 (this._oneHandlers && this._oneHandlers[type] && this._oneHandlers[type].length);
3528 };
3529 return EmitterMixin;
3530}(Mixin));
3531function addToHash(hash, type, handler) {
3532 (hash[type] || (hash[type] = []))
3533 .push(handler);
3534}
3535function removeFromHash(hash, type, handler) {
3536 if (handler) {
3537 if (hash[type]) {
3538 hash[type] = hash[type].filter(function (func) {
3539 return func !== handler;
3540 });
3541 }
3542 }
3543 else {
3544 delete hash[type]; // remove all handler funcs for this type
3545 }
3546}
3547
3548/*
3549Records offset information for a set of elements, relative to an origin element.
3550Can record the left/right OR the top/bottom OR both.
3551Provides methods for querying the cache by position.
3552*/
3553var PositionCache = /** @class */ (function () {
3554 function PositionCache(originEl, els, isHorizontal, isVertical) {
3555 this.originEl = originEl;
3556 this.els = els;
3557 this.isHorizontal = isHorizontal;
3558 this.isVertical = isVertical;
3559 }
3560 // Queries the els for coordinates and stores them.
3561 // Call this method before using and of the get* methods below.
3562 PositionCache.prototype.build = function () {
3563 var originEl = this.originEl;
3564 var originClientRect = this.originClientRect =
3565 originEl.getBoundingClientRect(); // relative to viewport top-left
3566 if (this.isHorizontal) {
3567 this.buildElHorizontals(originClientRect.left);
3568 }
3569 if (this.isVertical) {
3570 this.buildElVerticals(originClientRect.top);
3571 }
3572 };
3573 // Populates the left/right internal coordinate arrays
3574 PositionCache.prototype.buildElHorizontals = function (originClientLeft) {
3575 var lefts = [];
3576 var rights = [];
3577 for (var _i = 0, _a = this.els; _i < _a.length; _i++) {
3578 var el = _a[_i];
3579 var rect = el.getBoundingClientRect();
3580 lefts.push(rect.left - originClientLeft);
3581 rights.push(rect.right - originClientLeft);
3582 }
3583 this.lefts = lefts;
3584 this.rights = rights;
3585 };
3586 // Populates the top/bottom internal coordinate arrays
3587 PositionCache.prototype.buildElVerticals = function (originClientTop) {
3588 var tops = [];
3589 var bottoms = [];
3590 for (var _i = 0, _a = this.els; _i < _a.length; _i++) {
3591 var el = _a[_i];
3592 var rect = el.getBoundingClientRect();
3593 tops.push(rect.top - originClientTop);
3594 bottoms.push(rect.bottom - originClientTop);
3595 }
3596 this.tops = tops;
3597 this.bottoms = bottoms;
3598 };
3599 // Given a left offset (from document left), returns the index of the el that it horizontally intersects.
3600 // If no intersection is made, returns undefined.
3601 PositionCache.prototype.leftToIndex = function (leftPosition) {
3602 var lefts = this.lefts;
3603 var rights = this.rights;
3604 var len = lefts.length;
3605 var i;
3606 for (i = 0; i < len; i++) {
3607 if (leftPosition >= lefts[i] && leftPosition < rights[i]) {
3608 return i;
3609 }
3610 }
3611 };
3612 // Given a top offset (from document top), returns the index of the el that it vertically intersects.
3613 // If no intersection is made, returns undefined.
3614 PositionCache.prototype.topToIndex = function (topPosition) {
3615 var tops = this.tops;
3616 var bottoms = this.bottoms;
3617 var len = tops.length;
3618 var i;
3619 for (i = 0; i < len; i++) {
3620 if (topPosition >= tops[i] && topPosition < bottoms[i]) {
3621 return i;
3622 }
3623 }
3624 };
3625 // Gets the width of the element at the given index
3626 PositionCache.prototype.getWidth = function (leftIndex) {
3627 return this.rights[leftIndex] - this.lefts[leftIndex];
3628 };
3629 // Gets the height of the element at the given index
3630 PositionCache.prototype.getHeight = function (topIndex) {
3631 return this.bottoms[topIndex] - this.tops[topIndex];
3632 };
3633 return PositionCache;
3634}());
3635
3636/*
3637An object for getting/setting scroll-related information for an element.
3638Internally, this is done very differently for window versus DOM element,
3639so this object serves as a common interface.
3640*/
3641var ScrollController = /** @class */ (function () {
3642 function ScrollController() {
3643 }
3644 ScrollController.prototype.getMaxScrollTop = function () {
3645 return this.getScrollHeight() - this.getClientHeight();
3646 };
3647 ScrollController.prototype.getMaxScrollLeft = function () {
3648 return this.getScrollWidth() - this.getClientWidth();
3649 };
3650 ScrollController.prototype.canScrollVertically = function () {
3651 return this.getMaxScrollTop() > 0;
3652 };
3653 ScrollController.prototype.canScrollHorizontally = function () {
3654 return this.getMaxScrollLeft() > 0;
3655 };
3656 ScrollController.prototype.canScrollUp = function () {
3657 return this.getScrollTop() > 0;
3658 };
3659 ScrollController.prototype.canScrollDown = function () {
3660 return this.getScrollTop() < this.getMaxScrollTop();
3661 };
3662 ScrollController.prototype.canScrollLeft = function () {
3663 return this.getScrollLeft() > 0;
3664 };
3665 ScrollController.prototype.canScrollRight = function () {
3666 return this.getScrollLeft() < this.getMaxScrollLeft();
3667 };
3668 return ScrollController;
3669}());
3670var ElementScrollController = /** @class */ (function (_super) {
3671 __extends(ElementScrollController, _super);
3672 function ElementScrollController(el) {
3673 var _this = _super.call(this) || this;
3674 _this.el = el;
3675 return _this;
3676 }
3677 ElementScrollController.prototype.getScrollTop = function () {
3678 return this.el.scrollTop;
3679 };
3680 ElementScrollController.prototype.getScrollLeft = function () {
3681 return this.el.scrollLeft;
3682 };
3683 ElementScrollController.prototype.setScrollTop = function (top) {
3684 this.el.scrollTop = top;
3685 };
3686 ElementScrollController.prototype.setScrollLeft = function (left) {
3687 this.el.scrollLeft = left;
3688 };
3689 ElementScrollController.prototype.getScrollWidth = function () {
3690 return this.el.scrollWidth;
3691 };
3692 ElementScrollController.prototype.getScrollHeight = function () {
3693 return this.el.scrollHeight;
3694 };
3695 ElementScrollController.prototype.getClientHeight = function () {
3696 return this.el.clientHeight;
3697 };
3698 ElementScrollController.prototype.getClientWidth = function () {
3699 return this.el.clientWidth;
3700 };
3701 return ElementScrollController;
3702}(ScrollController));
3703var WindowScrollController = /** @class */ (function (_super) {
3704 __extends(WindowScrollController, _super);
3705 function WindowScrollController() {
3706 return _super !== null && _super.apply(this, arguments) || this;
3707 }
3708 WindowScrollController.prototype.getScrollTop = function () {
3709 return window.pageYOffset;
3710 };
3711 WindowScrollController.prototype.getScrollLeft = function () {
3712 return window.pageXOffset;
3713 };
3714 WindowScrollController.prototype.setScrollTop = function (n) {
3715 window.scroll(window.pageXOffset, n);
3716 };
3717 WindowScrollController.prototype.setScrollLeft = function (n) {
3718 window.scroll(n, window.pageYOffset);
3719 };
3720 WindowScrollController.prototype.getScrollWidth = function () {
3721 return document.documentElement.scrollWidth;
3722 };
3723 WindowScrollController.prototype.getScrollHeight = function () {
3724 return document.documentElement.scrollHeight;
3725 };
3726 WindowScrollController.prototype.getClientHeight = function () {
3727 return document.documentElement.clientHeight;
3728 };
3729 WindowScrollController.prototype.getClientWidth = function () {
3730 return document.documentElement.clientWidth;
3731 };
3732 return WindowScrollController;
3733}(ScrollController));
3734
3735/*
3736Embodies a div that has potential scrollbars
3737*/
3738var ScrollComponent = /** @class */ (function (_super) {
3739 __extends(ScrollComponent, _super);
3740 function ScrollComponent(overflowX, overflowY) {
3741 var _this = _super.call(this, createElement('div', {
3742 className: 'fc-scroller'
3743 })) || this;
3744 _this.overflowX = overflowX;
3745 _this.overflowY = overflowY;
3746 _this.applyOverflow();
3747 return _this;
3748 }
3749 // sets to natural height, unlocks overflow
3750 ScrollComponent.prototype.clear = function () {
3751 this.setHeight('auto');
3752 this.applyOverflow();
3753 };
3754 ScrollComponent.prototype.destroy = function () {
3755 removeElement(this.el);
3756 };
3757 // Overflow
3758 // -----------------------------------------------------------------------------------------------------------------
3759 ScrollComponent.prototype.applyOverflow = function () {
3760 applyStyle(this.el, {
3761 overflowX: this.overflowX,
3762 overflowY: this.overflowY
3763 });
3764 };
3765 // Causes any 'auto' overflow values to resolves to 'scroll' or 'hidden'.
3766 // Useful for preserving scrollbar widths regardless of future resizes.
3767 // Can pass in scrollbarWidths for optimization.
3768 ScrollComponent.prototype.lockOverflow = function (scrollbarWidths) {
3769 var overflowX = this.overflowX;
3770 var overflowY = this.overflowY;
3771 scrollbarWidths = scrollbarWidths || this.getScrollbarWidths();
3772 if (overflowX === 'auto') {
3773 overflowX = (scrollbarWidths.bottom || // horizontal scrollbars?
3774 this.canScrollHorizontally() // OR scrolling pane with massless scrollbars?
3775 ) ? 'scroll' : 'hidden';
3776 }
3777 if (overflowY === 'auto') {
3778 overflowY = (scrollbarWidths.left || scrollbarWidths.right || // horizontal scrollbars?
3779 this.canScrollVertically() // OR scrolling pane with massless scrollbars?
3780 ) ? 'scroll' : 'hidden';
3781 }
3782 applyStyle(this.el, { overflowX: overflowX, overflowY: overflowY });
3783 };
3784 ScrollComponent.prototype.setHeight = function (height) {
3785 applyStyleProp(this.el, 'height', height);
3786 };
3787 ScrollComponent.prototype.getScrollbarWidths = function () {
3788 var edges = computeEdges(this.el);
3789 return {
3790 left: edges.scrollbarLeft,
3791 right: edges.scrollbarRight,
3792 bottom: edges.scrollbarBottom
3793 };
3794 };
3795 return ScrollComponent;
3796}(ElementScrollController));
3797
3798var Theme = /** @class */ (function () {
3799 function Theme(calendarOptions) {
3800 this.calendarOptions = calendarOptions;
3801 this.processIconOverride();
3802 }
3803 Theme.prototype.processIconOverride = function () {
3804 if (this.iconOverrideOption) {
3805 this.setIconOverride(this.calendarOptions[this.iconOverrideOption]);
3806 }
3807 };
3808 Theme.prototype.setIconOverride = function (iconOverrideHash) {
3809 var iconClassesCopy;
3810 var buttonName;
3811 if (typeof iconOverrideHash === 'object' && iconOverrideHash) { // non-null object
3812 iconClassesCopy = __assign({}, this.iconClasses);
3813 for (buttonName in iconOverrideHash) {
3814 iconClassesCopy[buttonName] = this.applyIconOverridePrefix(iconOverrideHash[buttonName]);
3815 }
3816 this.iconClasses = iconClassesCopy;
3817 }
3818 else if (iconOverrideHash === false) {
3819 this.iconClasses = {};
3820 }
3821 };
3822 Theme.prototype.applyIconOverridePrefix = function (className) {
3823 var prefix = this.iconOverridePrefix;
3824 if (prefix && className.indexOf(prefix) !== 0) { // if not already present
3825 className = prefix + className;
3826 }
3827 return className;
3828 };
3829 Theme.prototype.getClass = function (key) {
3830 return this.classes[key] || '';
3831 };
3832 Theme.prototype.getIconClass = function (buttonName) {
3833 var className = this.iconClasses[buttonName];
3834 if (className) {
3835 return this.baseIconClass + ' ' + className;
3836 }
3837 return '';
3838 };
3839 Theme.prototype.getCustomButtonIconClass = function (customButtonProps) {
3840 var className;
3841 if (this.iconOverrideCustomButtonOption) {
3842 className = customButtonProps[this.iconOverrideCustomButtonOption];
3843 if (className) {
3844 return this.baseIconClass + ' ' + this.applyIconOverridePrefix(className);
3845 }
3846 }
3847 return '';
3848 };
3849 return Theme;
3850}());
3851Theme.prototype.classes = {};
3852Theme.prototype.iconClasses = {};
3853Theme.prototype.baseIconClass = '';
3854Theme.prototype.iconOverridePrefix = '';
3855
3856var guid = 0;
3857var Component = /** @class */ (function () {
3858 function Component(context, isView) {
3859 // HACK to populate view at top of component instantiation call chain
3860 if (isView) {
3861 context.view = this;
3862 }
3863 this.uid = String(guid++);
3864 this.context = context;
3865 this.dateEnv = context.dateEnv;
3866 this.theme = context.theme;
3867 this.view = context.view;
3868 this.calendar = context.calendar;
3869 this.isRtl = this.opt('dir') === 'rtl';
3870 }
3871 Component.addEqualityFuncs = function (newFuncs) {
3872 this.prototype.equalityFuncs = __assign({}, this.prototype.equalityFuncs, newFuncs);
3873 };
3874 Component.prototype.opt = function (name) {
3875 return this.context.options[name];
3876 };
3877 Component.prototype.receiveProps = function (props) {
3878 var _a = recycleProps(this.props || {}, props, this.equalityFuncs), anyChanges = _a.anyChanges, comboProps = _a.comboProps;
3879 this.props = comboProps;
3880 if (anyChanges) {
3881 this.render(comboProps);
3882 }
3883 };
3884 Component.prototype.render = function (props) {
3885 };
3886 // after destroy is called, this component won't ever be used again
3887 Component.prototype.destroy = function () {
3888 };
3889 return Component;
3890}());
3891Component.prototype.equalityFuncs = {};
3892/*
3893Reuses old values when equal. If anything is unequal, returns newProps as-is.
3894Great for PureComponent, but won't be feasible with React, so just eliminate and use React's DOM diffing.
3895*/
3896function recycleProps(oldProps, newProps, equalityFuncs) {
3897 var comboProps = {}; // some old, some new
3898 var anyChanges = false;
3899 for (var key in newProps) {
3900 if (key in oldProps && (oldProps[key] === newProps[key] ||
3901 (equalityFuncs[key] && equalityFuncs[key](oldProps[key], newProps[key])))) {
3902 // equal to old? use old prop
3903 comboProps[key] = oldProps[key];
3904 }
3905 else {
3906 comboProps[key] = newProps[key];
3907 anyChanges = true;
3908 }
3909 }
3910 for (var key in oldProps) {
3911 if (!(key in newProps)) {
3912 anyChanges = true;
3913 break;
3914 }
3915 }
3916 return { anyChanges: anyChanges, comboProps: comboProps };
3917}
3918
3919/*
3920PURPOSES:
3921- hook up to fg, fill, and mirror renderers
3922- interface for dragging and hits
3923*/
3924var DateComponent = /** @class */ (function (_super) {
3925 __extends(DateComponent, _super);
3926 function DateComponent(context, el, isView) {
3927 var _this = _super.call(this, context, isView) || this;
3928 _this.el = el;
3929 return _this;
3930 }
3931 DateComponent.prototype.destroy = function () {
3932 _super.prototype.destroy.call(this);
3933 removeElement(this.el);
3934 };
3935 // TODO: WHAT ABOUT (sourceSeg && sourceSeg.component.doesDragMirror)
3936 //
3937 // Event Drag-n-Drop Rendering (for both events and external elements)
3938 // ---------------------------------------------------------------------------------------------------------------
3939 /*
3940 renderEventDragSegs(state: EventSegUiInteractionState) {
3941 if (state) {
3942 let { isEvent, segs, sourceSeg } = state
3943
3944 if (this.eventRenderer) {
3945 this.eventRenderer.hideByHash(state.affectedInstances)
3946 }
3947
3948 // if the user is dragging something that is considered an event with real event data,
3949 // and this component likes to do drag mirrors OR the component where the seg came from
3950 // likes to do drag mirrors, then render a drag mirror.
3951 if (isEvent && (this.doesDragMirror || sourceSeg && sourceSeg.component.doesDragMirror)) {
3952 if (this.mirrorRenderer) {
3953 this.mirrorRenderer.renderSegs(segs, { isDragging: true, sourceSeg })
3954 }
3955 }
3956
3957 // if it would be impossible to render a drag mirror OR this component likes to render
3958 // highlights, then render a highlight.
3959 if (!isEvent || this.doesDragHighlight) {
3960 if (this.fillRenderer) {
3961 this.fillRenderer.renderSegs('highlight', segs)
3962 }
3963 }
3964 }
3965 }
3966 */
3967 // Hit System
3968 // -----------------------------------------------------------------------------------------------------------------
3969 DateComponent.prototype.buildPositionCaches = function () {
3970 };
3971 DateComponent.prototype.queryHit = function (positionLeft, positionTop, elWidth, elHeight) {
3972 return null; // this should be abstract
3973 };
3974 // Validation
3975 // -----------------------------------------------------------------------------------------------------------------
3976 DateComponent.prototype.isInteractionValid = function (interaction) {
3977 var calendar = this.calendar;
3978 var dateProfile = this.props.dateProfile; // HACK
3979 var instances = interaction.mutatedEvents.instances;
3980 if (dateProfile) { // HACK for DayTile
3981 for (var instanceId in instances) {
3982 if (!rangeContainsRange(dateProfile.validRange, instances[instanceId].range)) {
3983 return false;
3984 }
3985 }
3986 }
3987 return isInteractionValid(interaction, calendar);
3988 };
3989 DateComponent.prototype.isDateSelectionValid = function (selection) {
3990 var dateProfile = this.props.dateProfile; // HACK
3991 if (dateProfile && // HACK for DayTile
3992 !rangeContainsRange(dateProfile.validRange, selection.range)) {
3993 return false;
3994 }
3995 return isDateSelectionValid(selection, this.calendar);
3996 };
3997 // Triggering
3998 // -----------------------------------------------------------------------------------------------------------------
3999 // TODO: move to Calendar
4000 DateComponent.prototype.publiclyTrigger = function (name, args) {
4001 var calendar = this.calendar;
4002 return calendar.publiclyTrigger(name, args);
4003 };
4004 DateComponent.prototype.publiclyTriggerAfterSizing = function (name, args) {
4005 var calendar = this.calendar;
4006 return calendar.publiclyTriggerAfterSizing(name, args);
4007 };
4008 DateComponent.prototype.hasPublicHandlers = function (name) {
4009 var calendar = this.calendar;
4010 return calendar.hasPublicHandlers(name);
4011 };
4012 DateComponent.prototype.triggerRenderedSegs = function (segs, isMirrors) {
4013 var calendar = this.calendar;
4014 if (this.hasPublicHandlers('eventPositioned')) {
4015 for (var _i = 0, segs_1 = segs; _i < segs_1.length; _i++) {
4016 var seg = segs_1[_i];
4017 this.publiclyTriggerAfterSizing('eventPositioned', [
4018 {
4019 event: new EventApi(calendar, seg.eventRange.def, seg.eventRange.instance),
4020 isMirror: isMirrors,
4021 isStart: seg.isStart,
4022 isEnd: seg.isEnd,
4023 el: seg.el,
4024 view: this // safe to cast because this method is only called on context.view
4025 }
4026 ]);
4027 }
4028 }
4029 if (!calendar.state.loadingLevel) { // avoid initial empty state while pending
4030 calendar.afterSizingTriggers._eventsPositioned = [null]; // fire once
4031 }
4032 };
4033 DateComponent.prototype.triggerWillRemoveSegs = function (segs, isMirrors) {
4034 var calendar = this.calendar;
4035 for (var _i = 0, segs_2 = segs; _i < segs_2.length; _i++) {
4036 var seg = segs_2[_i];
4037 calendar.trigger('eventElRemove', seg.el);
4038 }
4039 if (this.hasPublicHandlers('eventDestroy')) {
4040 for (var _a = 0, segs_3 = segs; _a < segs_3.length; _a++) {
4041 var seg = segs_3[_a];
4042 this.publiclyTrigger('eventDestroy', [
4043 {
4044 event: new EventApi(calendar, seg.eventRange.def, seg.eventRange.instance),
4045 isMirror: isMirrors,
4046 el: seg.el,
4047 view: this // safe to cast because this method is only called on context.view
4048 }
4049 ]);
4050 }
4051 }
4052 };
4053 // Pointer Interaction Utils
4054 // -----------------------------------------------------------------------------------------------------------------
4055 DateComponent.prototype.isValidSegDownEl = function (el) {
4056 return !this.props.eventDrag && // HACK
4057 !this.props.eventResize && // HACK
4058 !elementClosest(el, '.fc-mirror') &&
4059 (this.isPopover() || !this.isInPopover(el));
4060 // ^above line ensures we don't detect a seg interaction within a nested component.
4061 // it's a HACK because it only supports a popover as the nested component.
4062 };
4063 DateComponent.prototype.isValidDateDownEl = function (el) {
4064 var segEl = elementClosest(el, this.fgSegSelector);
4065 return (!segEl || segEl.classList.contains('fc-mirror')) &&
4066 !elementClosest(el, '.fc-more') && // a "more.." link
4067 !elementClosest(el, 'a[data-goto]') && // a clickable nav link
4068 !this.isInPopover(el);
4069 };
4070 DateComponent.prototype.isPopover = function () {
4071 return this.el.classList.contains('fc-popover');
4072 };
4073 DateComponent.prototype.isInPopover = function (el) {
4074 return Boolean(elementClosest(el, '.fc-popover'));
4075 };
4076 return DateComponent;
4077}(Component));
4078DateComponent.prototype.fgSegSelector = '.fc-event-container > *';
4079DateComponent.prototype.bgSegSelector = '.fc-bgevent:not(.fc-nonbusiness)';
4080
4081var uid$1 = 0;
4082function createPlugin(input) {
4083 return {
4084 id: String(uid$1++),
4085 deps: input.deps || [],
4086 reducers: input.reducers || [],
4087 eventDefParsers: input.eventDefParsers || [],
4088 isDraggableTransformers: input.isDraggableTransformers || [],
4089 eventDragMutationMassagers: input.eventDragMutationMassagers || [],
4090 eventDefMutationAppliers: input.eventDefMutationAppliers || [],
4091 dateSelectionTransformers: input.dateSelectionTransformers || [],
4092 datePointTransforms: input.datePointTransforms || [],
4093 dateSpanTransforms: input.dateSpanTransforms || [],
4094 views: input.views || {},
4095 viewPropsTransformers: input.viewPropsTransformers || [],
4096 isPropsValid: input.isPropsValid || null,
4097 externalDefTransforms: input.externalDefTransforms || [],
4098 eventResizeJoinTransforms: input.eventResizeJoinTransforms || [],
4099 viewContainerModifiers: input.viewContainerModifiers || [],
4100 eventDropTransformers: input.eventDropTransformers || [],
4101 componentInteractions: input.componentInteractions || [],
4102 calendarInteractions: input.calendarInteractions || [],
4103 themeClasses: input.themeClasses || {},
4104 eventSourceDefs: input.eventSourceDefs || [],
4105 cmdFormatter: input.cmdFormatter,
4106 recurringTypes: input.recurringTypes || [],
4107 namedTimeZonedImpl: input.namedTimeZonedImpl,
4108 defaultView: input.defaultView || '',
4109 elementDraggingImpl: input.elementDraggingImpl,
4110 optionChangeHandlers: input.optionChangeHandlers || {}
4111 };
4112}
4113var PluginSystem = /** @class */ (function () {
4114 function PluginSystem() {
4115 this.hooks = {
4116 reducers: [],
4117 eventDefParsers: [],
4118 isDraggableTransformers: [],
4119 eventDragMutationMassagers: [],
4120 eventDefMutationAppliers: [],
4121 dateSelectionTransformers: [],
4122 datePointTransforms: [],
4123 dateSpanTransforms: [],
4124 views: {},
4125 viewPropsTransformers: [],
4126 isPropsValid: null,
4127 externalDefTransforms: [],
4128 eventResizeJoinTransforms: [],
4129 viewContainerModifiers: [],
4130 eventDropTransformers: [],
4131 componentInteractions: [],
4132 calendarInteractions: [],
4133 themeClasses: {},
4134 eventSourceDefs: [],
4135 cmdFormatter: null,
4136 recurringTypes: [],
4137 namedTimeZonedImpl: null,
4138 defaultView: '',
4139 elementDraggingImpl: null,
4140 optionChangeHandlers: {}
4141 };
4142 this.addedHash = {};
4143 }
4144 PluginSystem.prototype.add = function (plugin) {
4145 if (!this.addedHash[plugin.id]) {
4146 this.addedHash[plugin.id] = true;
4147 for (var _i = 0, _a = plugin.deps; _i < _a.length; _i++) {
4148 var dep = _a[_i];
4149 this.add(dep);
4150 }
4151 this.hooks = combineHooks(this.hooks, plugin);
4152 }
4153 };
4154 return PluginSystem;
4155}());
4156function combineHooks(hooks0, hooks1) {
4157 return {
4158 reducers: hooks0.reducers.concat(hooks1.reducers),
4159 eventDefParsers: hooks0.eventDefParsers.concat(hooks1.eventDefParsers),
4160 isDraggableTransformers: hooks0.isDraggableTransformers.concat(hooks1.isDraggableTransformers),
4161 eventDragMutationMassagers: hooks0.eventDragMutationMassagers.concat(hooks1.eventDragMutationMassagers),
4162 eventDefMutationAppliers: hooks0.eventDefMutationAppliers.concat(hooks1.eventDefMutationAppliers),
4163 dateSelectionTransformers: hooks0.dateSelectionTransformers.concat(hooks1.dateSelectionTransformers),
4164 datePointTransforms: hooks0.datePointTransforms.concat(hooks1.datePointTransforms),
4165 dateSpanTransforms: hooks0.dateSpanTransforms.concat(hooks1.dateSpanTransforms),
4166 views: __assign({}, hooks0.views, hooks1.views),
4167 viewPropsTransformers: hooks0.viewPropsTransformers.concat(hooks1.viewPropsTransformers),
4168 isPropsValid: hooks1.isPropsValid || hooks0.isPropsValid,
4169 externalDefTransforms: hooks0.externalDefTransforms.concat(hooks1.externalDefTransforms),
4170 eventResizeJoinTransforms: hooks0.eventResizeJoinTransforms.concat(hooks1.eventResizeJoinTransforms),
4171 viewContainerModifiers: hooks0.viewContainerModifiers.concat(hooks1.viewContainerModifiers),
4172 eventDropTransformers: hooks0.eventDropTransformers.concat(hooks1.eventDropTransformers),
4173 calendarInteractions: hooks0.calendarInteractions.concat(hooks1.calendarInteractions),
4174 componentInteractions: hooks0.componentInteractions.concat(hooks1.componentInteractions),
4175 themeClasses: __assign({}, hooks0.themeClasses, hooks1.themeClasses),
4176 eventSourceDefs: hooks0.eventSourceDefs.concat(hooks1.eventSourceDefs),
4177 cmdFormatter: hooks1.cmdFormatter || hooks0.cmdFormatter,
4178 recurringTypes: hooks0.recurringTypes.concat(hooks1.recurringTypes),
4179 namedTimeZonedImpl: hooks1.namedTimeZonedImpl || hooks0.namedTimeZonedImpl,
4180 defaultView: hooks0.defaultView || hooks1.defaultView,
4181 elementDraggingImpl: hooks0.elementDraggingImpl || hooks1.elementDraggingImpl,
4182 optionChangeHandlers: __assign({}, hooks0.optionChangeHandlers, hooks1.optionChangeHandlers)
4183 };
4184}
4185
4186var eventSourceDef = {
4187 ignoreRange: true,
4188 parseMeta: function (raw) {
4189 if (Array.isArray(raw)) { // short form
4190 return raw;
4191 }
4192 else if (Array.isArray(raw.events)) {
4193 return raw.events;
4194 }
4195 return null;
4196 },
4197 fetch: function (arg, success) {
4198 success({
4199 rawEvents: arg.eventSource.meta
4200 });
4201 }
4202};
4203var ArrayEventSourcePlugin = createPlugin({
4204 eventSourceDefs: [eventSourceDef]
4205});
4206
4207var eventSourceDef$1 = {
4208 parseMeta: function (raw) {
4209 if (typeof raw === 'function') { // short form
4210 return raw;
4211 }
4212 else if (typeof raw.events === 'function') {
4213 return raw.events;
4214 }
4215 return null;
4216 },
4217 fetch: function (arg, success, failure) {
4218 var dateEnv = arg.calendar.dateEnv;
4219 var func = arg.eventSource.meta;
4220 unpromisify(func.bind(null, {
4221 start: dateEnv.toDate(arg.range.start),
4222 end: dateEnv.toDate(arg.range.end),
4223 startStr: dateEnv.formatIso(arg.range.start),
4224 endStr: dateEnv.formatIso(arg.range.end),
4225 timeZone: dateEnv.timeZone
4226 }), function (rawEvents) {
4227 success({ rawEvents: rawEvents }); // needs an object response
4228 }, failure // send errorObj directly to failure callback
4229 );
4230 }
4231};
4232var FuncEventSourcePlugin = createPlugin({
4233 eventSourceDefs: [eventSourceDef$1]
4234});
4235
4236function requestJson(method, url, params, successCallback, failureCallback) {
4237 method = method.toUpperCase();
4238 var body = null;
4239 if (method === 'GET') {
4240 url = injectQueryStringParams(url, params);
4241 }
4242 else {
4243 body = encodeParams(params);
4244 }
4245 var xhr = new XMLHttpRequest();
4246 xhr.open(method, url, true);
4247 if (method !== 'GET') {
4248 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
4249 }
4250 xhr.onload = function () {
4251 if (xhr.status >= 200 && xhr.status < 400) {
4252 try {
4253 var res = JSON.parse(xhr.responseText);
4254 successCallback(res, xhr);
4255 }
4256 catch (err) {
4257 failureCallback('Failure parsing JSON', xhr);
4258 }
4259 }
4260 else {
4261 failureCallback('Request failed', xhr);
4262 }
4263 };
4264 xhr.onerror = function () {
4265 failureCallback('Request failed', xhr);
4266 };
4267 xhr.send(body);
4268}
4269function injectQueryStringParams(url, params) {
4270 return url +
4271 (url.indexOf('?') === -1 ? '?' : '&') +
4272 encodeParams(params);
4273}
4274function encodeParams(params) {
4275 var parts = [];
4276 for (var key in params) {
4277 parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(params[key]));
4278 }
4279 return parts.join('&');
4280}
4281
4282var eventSourceDef$2 = {
4283 parseMeta: function (raw) {
4284 if (typeof raw === 'string') { // short form
4285 raw = { url: raw };
4286 }
4287 else if (!raw || typeof raw !== 'object' || !raw.url) {
4288 return null;
4289 }
4290 return {
4291 url: raw.url,
4292 method: (raw.method || 'GET').toUpperCase(),
4293 extraParams: raw.extraParams,
4294 startParam: raw.startParam,
4295 endParam: raw.endParam,
4296 timeZoneParam: raw.timeZoneParam
4297 };
4298 },
4299 fetch: function (arg, success, failure) {
4300 var meta = arg.eventSource.meta;
4301 var requestParams = buildRequestParams(meta, arg.range, arg.calendar);
4302 requestJson(meta.method, meta.url, requestParams, function (rawEvents, xhr) {
4303 success({ rawEvents: rawEvents, xhr: xhr });
4304 }, function (errorMessage, xhr) {
4305 failure({ message: errorMessage, xhr: xhr });
4306 });
4307 }
4308};
4309var JsonFeedEventSourcePlugin = createPlugin({
4310 eventSourceDefs: [eventSourceDef$2]
4311});
4312function buildRequestParams(meta, range, calendar) {
4313 var dateEnv = calendar.dateEnv;
4314 var startParam;
4315 var endParam;
4316 var timeZoneParam;
4317 var customRequestParams;
4318 var params = {};
4319 startParam = meta.startParam;
4320 if (startParam == null) {
4321 startParam = calendar.opt('startParam');
4322 }
4323 endParam = meta.endParam;
4324 if (endParam == null) {
4325 endParam = calendar.opt('endParam');
4326 }
4327 timeZoneParam = meta.timeZoneParam;
4328 if (timeZoneParam == null) {
4329 timeZoneParam = calendar.opt('timeZoneParam');
4330 }
4331 // retrieve any outbound GET/POST data from the options
4332 if (typeof meta.extraParams === 'function') {
4333 // supplied as a function that returns a key/value object
4334 customRequestParams = meta.extraParams();
4335 }
4336 else {
4337 // probably supplied as a straight key/value object
4338 customRequestParams = meta.extraParams || {};
4339 }
4340 __assign(params, customRequestParams);
4341 params[startParam] = dateEnv.formatIso(range.start);
4342 params[endParam] = dateEnv.formatIso(range.end);
4343 if (dateEnv.timeZone !== 'local') {
4344 params[timeZoneParam] = dateEnv.timeZone;
4345 }
4346 return params;
4347}
4348
4349var recurring = {
4350 parse: function (rawEvent, leftoverProps, dateEnv) {
4351 var createMarker = dateEnv.createMarker.bind(dateEnv);
4352 var processors = {
4353 daysOfWeek: null,
4354 startTime: createDuration,
4355 endTime: createDuration,
4356 startRecur: createMarker,
4357 endRecur: createMarker
4358 };
4359 var props = refineProps(rawEvent, processors, {}, leftoverProps);
4360 var anyValid = false;
4361 for (var propName in props) {
4362 if (props[propName] != null) {
4363 anyValid = true;
4364 break;
4365 }
4366 }
4367 if (anyValid) {
4368 var duration = null;
4369 if ('duration' in leftoverProps) {
4370 duration = createDuration(leftoverProps.duration);
4371 delete leftoverProps.duration;
4372 }
4373 if (!duration && props.startTime && props.endTime) {
4374 duration = subtractDurations(props.endTime, props.startTime);
4375 }
4376 return {
4377 allDayGuess: Boolean(!props.startTime && !props.endTime),
4378 duration: duration,
4379 typeData: props // doesn't need endTime anymore but oh well
4380 };
4381 }
4382 return null;
4383 },
4384 expand: function (typeData, framingRange, dateEnv) {
4385 var clippedFramingRange = intersectRanges(framingRange, { start: typeData.startRecur, end: typeData.endRecur });
4386 if (clippedFramingRange) {
4387 return expandRanges(typeData.daysOfWeek, typeData.startTime, clippedFramingRange, dateEnv);
4388 }
4389 else {
4390 return [];
4391 }
4392 }
4393};
4394var SimpleRecurrencePlugin = createPlugin({
4395 recurringTypes: [recurring]
4396});
4397function expandRanges(daysOfWeek, startTime, framingRange, dateEnv) {
4398 var dowHash = daysOfWeek ? arrayToHash(daysOfWeek) : null;
4399 var dayMarker = startOfDay(framingRange.start);
4400 var endMarker = framingRange.end;
4401 var instanceStarts = [];
4402 while (dayMarker < endMarker) {
4403 var instanceStart
4404 // if everyday, or this particular day-of-week
4405 = void 0;
4406 // if everyday, or this particular day-of-week
4407 if (!dowHash || dowHash[dayMarker.getUTCDay()]) {
4408 if (startTime) {
4409 instanceStart = dateEnv.add(dayMarker, startTime);
4410 }
4411 else {
4412 instanceStart = dayMarker;
4413 }
4414 instanceStarts.push(instanceStart);
4415 }
4416 dayMarker = addDays(dayMarker, 1);
4417 }
4418 return instanceStarts;
4419}
4420
4421var DefaultOptionChangeHandlers = createPlugin({
4422 optionChangeHandlers: {
4423 events: function (events, calendar, deepEqual) {
4424 handleEventSources([events], calendar, deepEqual);
4425 },
4426 eventSources: handleEventSources,
4427 plugins: handlePlugins
4428 }
4429});
4430function handleEventSources(inputs, calendar, deepEqual) {
4431 var unfoundSources = hashValuesToArray(calendar.state.eventSources);
4432 var newInputs = [];
4433 for (var _i = 0, inputs_1 = inputs; _i < inputs_1.length; _i++) {
4434 var input = inputs_1[_i];
4435 var inputFound = false;
4436 for (var i = 0; i < unfoundSources.length; i++) {
4437 if (deepEqual(unfoundSources[i]._raw, input)) {
4438 unfoundSources.splice(i, 1); // delete
4439 inputFound = true;
4440 break;
4441 }
4442 }
4443 if (!inputFound) {
4444 newInputs.push(input);
4445 }
4446 }
4447 for (var _a = 0, unfoundSources_1 = unfoundSources; _a < unfoundSources_1.length; _a++) {
4448 var unfoundSource = unfoundSources_1[_a];
4449 calendar.dispatch({
4450 type: 'REMOVE_EVENT_SOURCE',
4451 sourceId: unfoundSource.sourceId
4452 });
4453 }
4454 for (var _b = 0, newInputs_1 = newInputs; _b < newInputs_1.length; _b++) {
4455 var newInput = newInputs_1[_b];
4456 calendar.addEventSource(newInput);
4457 }
4458}
4459// shortcoming: won't remove plugins
4460function handlePlugins(inputs, calendar) {
4461 calendar.addPluginInputs(inputs); // will gracefully handle duplicates
4462}
4463
4464var config = {}; // TODO: make these options
4465var globalDefaults = {
4466 defaultRangeSeparator: ' - ',
4467 titleRangeSeparator: ' \u2013 ',
4468 defaultTimedEventDuration: '01:00:00',
4469 defaultAllDayEventDuration: { day: 1 },
4470 forceEventDuration: false,
4471 nextDayThreshold: '00:00:00',
4472 // display
4473 columnHeader: true,
4474 defaultView: '',
4475 aspectRatio: 1.35,
4476 header: {
4477 left: 'title',
4478 center: '',
4479 right: 'today prev,next'
4480 },
4481 weekends: true,
4482 weekNumbers: false,
4483 weekNumberCalculation: 'local',
4484 editable: false,
4485 // nowIndicator: false,
4486 scrollTime: '06:00:00',
4487 minTime: '00:00:00',
4488 maxTime: '24:00:00',
4489 showNonCurrentDates: true,
4490 // event ajax
4491 lazyFetching: true,
4492 startParam: 'start',
4493 endParam: 'end',
4494 timeZoneParam: 'timeZone',
4495 timeZone: 'local',
4496 // allDayDefault: undefined,
4497 // locale
4498 locales: [],
4499 locale: '',
4500 // dir: will get this from the default locale
4501 // buttonIcons: null,
4502 // allows setting a min-height to the event segment to prevent short events overlapping each other
4503 timeGridEventMinHeight: 0,
4504 themeSystem: 'standard',
4505 // eventResizableFromStart: false,
4506 dragRevertDuration: 500,
4507 dragScroll: true,
4508 allDayMaintainDuration: false,
4509 // selectable: false,
4510 unselectAuto: true,
4511 // selectMinDistance: 0,
4512 dropAccept: '*',
4513 eventOrder: 'start,-duration,allDay,title',
4514 // ^ if start tie, longer events go before shorter. final tie-breaker is title text
4515 // rerenderDelay: null,
4516 eventLimit: false,
4517 eventLimitClick: 'popover',
4518 dayPopoverFormat: { month: 'long', day: 'numeric', year: 'numeric' },
4519 handleWindowResize: true,
4520 windowResizeDelay: 100,
4521 longPressDelay: 1000,
4522 eventDragMinDistance: 5 // only applies to mouse
4523};
4524var rtlDefaults = {
4525 header: {
4526 left: 'next,prev today',
4527 center: '',
4528 right: 'title'
4529 },
4530 buttonIcons: {
4531 // TODO: make RTL support the responibility of the theme
4532 prev: 'fc-icon-chevron-right',
4533 next: 'fc-icon-chevron-left',
4534 prevYear: 'fc-icon-chevrons-right',
4535 nextYear: 'fc-icon-chevrons-left'
4536 }
4537};
4538var complexOptions = [
4539 'header',
4540 'footer',
4541 'buttonText',
4542 'buttonIcons'
4543];
4544// Merges an array of option objects into a single object
4545function mergeOptions(optionObjs) {
4546 return mergeProps(optionObjs, complexOptions);
4547}
4548// TODO: move this stuff to a "plugin"-related file...
4549var INTERNAL_PLUGINS = [
4550 ArrayEventSourcePlugin,
4551 FuncEventSourcePlugin,
4552 JsonFeedEventSourcePlugin,
4553 SimpleRecurrencePlugin,
4554 DefaultOptionChangeHandlers
4555];
4556function refinePluginDefs(pluginInputs) {
4557 var plugins = [];
4558 for (var _i = 0, pluginInputs_1 = pluginInputs; _i < pluginInputs_1.length; _i++) {
4559 var pluginInput = pluginInputs_1[_i];
4560 if (typeof pluginInput === 'string') {
4561 var globalName = 'FullCalendar' + capitaliseFirstLetter(pluginInput);
4562 if (!window[globalName]) {
4563 console.warn('Plugin file not loaded for ' + pluginInput);
4564 }
4565 else {
4566 plugins.push(window[globalName].default); // is an ES6 module
4567 }
4568 }
4569 else {
4570 plugins.push(pluginInput);
4571 }
4572 }
4573 return INTERNAL_PLUGINS.concat(plugins);
4574}
4575
4576var RAW_EN_LOCALE = {
4577 code: 'en',
4578 week: {
4579 dow: 0,
4580 doy: 4 // 4 days need to be within the year to be considered the first week
4581 },
4582 dir: 'ltr',
4583 buttonText: {
4584 prev: 'prev',
4585 next: 'next',
4586 prevYear: 'prev year',
4587 nextYear: 'next year',
4588 year: 'year',
4589 today: 'today',
4590 month: 'month',
4591 week: 'week',
4592 day: 'day',
4593 list: 'list'
4594 },
4595 weekLabel: 'W',
4596 allDayText: 'all-day',
4597 eventLimitText: 'more',
4598 noEventsMessage: 'No events to display'
4599};
4600function parseRawLocales(explicitRawLocales) {
4601 var defaultCode = explicitRawLocales.length > 0 ? explicitRawLocales[0].code : 'en';
4602 var globalArray = window['FullCalendarLocalesAll'] || []; // from locales-all.js
4603 var globalObject = window['FullCalendarLocales'] || {}; // from locales/*.js. keys are meaningless
4604 var allRawLocales = globalArray.concat(// globalArray is low prio
4605 hashValuesToArray(globalObject), // medium prio
4606 explicitRawLocales // highest prio
4607 );
4608 var rawLocaleMap = {
4609 en: RAW_EN_LOCALE // necessary?
4610 };
4611 for (var _i = 0, allRawLocales_1 = allRawLocales; _i < allRawLocales_1.length; _i++) {
4612 var rawLocale = allRawLocales_1[_i];
4613 rawLocaleMap[rawLocale.code] = rawLocale;
4614 }
4615 return {
4616 map: rawLocaleMap,
4617 defaultCode: defaultCode
4618 };
4619}
4620function buildLocale(inputSingular, available) {
4621 if (typeof inputSingular === 'object' && !Array.isArray(inputSingular)) {
4622 return parseLocale(inputSingular.code, [inputSingular.code], inputSingular);
4623 }
4624 else {
4625 return queryLocale(inputSingular, available);
4626 }
4627}
4628function queryLocale(codeArg, available) {
4629 var codes = [].concat(codeArg || []); // will convert to array
4630 var raw = queryRawLocale(codes, available) || RAW_EN_LOCALE;
4631 return parseLocale(codeArg, codes, raw);
4632}
4633function queryRawLocale(codes, available) {
4634 for (var i = 0; i < codes.length; i++) {
4635 var parts = codes[i].toLocaleLowerCase().split('-');
4636 for (var j = parts.length; j > 0; j--) {
4637 var simpleId = parts.slice(0, j).join('-');
4638 if (available[simpleId]) {
4639 return available[simpleId];
4640 }
4641 }
4642 }
4643 return null;
4644}
4645function parseLocale(codeArg, codes, raw) {
4646 var merged = mergeProps([RAW_EN_LOCALE, raw], ['buttonText']);
4647 delete merged.code; // don't want this part of the options
4648 var week = merged.week;
4649 delete merged.week;
4650 return {
4651 codeArg: codeArg,
4652 codes: codes,
4653 week: week,
4654 simpleNumberFormat: new Intl.NumberFormat(codeArg),
4655 options: merged
4656 };
4657}
4658
4659var OptionsManager = /** @class */ (function () {
4660 function OptionsManager(overrides) {
4661 this.overrides = __assign({}, overrides); // make a copy
4662 this.dynamicOverrides = {};
4663 this.compute();
4664 }
4665 OptionsManager.prototype.mutate = function (updates, removals, isDynamic) {
4666 var overrideHash = isDynamic ? this.dynamicOverrides : this.overrides;
4667 __assign(overrideHash, updates);
4668 for (var _i = 0, removals_1 = removals; _i < removals_1.length; _i++) {
4669 var propName = removals_1[_i];
4670 delete overrideHash[propName];
4671 }
4672 this.compute();
4673 };
4674 // Computes the flattened options hash for the calendar and assigns to `this.options`.
4675 // Assumes this.overrides and this.dynamicOverrides have already been initialized.
4676 OptionsManager.prototype.compute = function () {
4677 // TODO: not a very efficient system
4678 var locales = firstDefined(// explicit locale option given?
4679 this.dynamicOverrides.locales, this.overrides.locales, globalDefaults.locales);
4680 var locale = firstDefined(// explicit locales option given?
4681 this.dynamicOverrides.locale, this.overrides.locale, globalDefaults.locale);
4682 var available = parseRawLocales(locales);
4683 var localeDefaults = buildLocale(locale || available.defaultCode, available.map).options;
4684 var dir = firstDefined(// based on options computed so far, is direction RTL?
4685 this.dynamicOverrides.dir, this.overrides.dir, localeDefaults.dir);
4686 var dirDefaults = dir === 'rtl' ? rtlDefaults : {};
4687 this.dirDefaults = dirDefaults;
4688 this.localeDefaults = localeDefaults;
4689 this.computed = mergeOptions([
4690 globalDefaults,
4691 dirDefaults,
4692 localeDefaults,
4693 this.overrides,
4694 this.dynamicOverrides
4695 ]);
4696 };
4697 return OptionsManager;
4698}());
4699
4700var calendarSystemClassMap = {};
4701function registerCalendarSystem(name, theClass) {
4702 calendarSystemClassMap[name] = theClass;
4703}
4704function createCalendarSystem(name) {
4705 return new calendarSystemClassMap[name]();
4706}
4707var GregorianCalendarSystem = /** @class */ (function () {
4708 function GregorianCalendarSystem() {
4709 }
4710 GregorianCalendarSystem.prototype.getMarkerYear = function (d) {
4711 return d.getUTCFullYear();
4712 };
4713 GregorianCalendarSystem.prototype.getMarkerMonth = function (d) {
4714 return d.getUTCMonth();
4715 };
4716 GregorianCalendarSystem.prototype.getMarkerDay = function (d) {
4717 return d.getUTCDate();
4718 };
4719 GregorianCalendarSystem.prototype.arrayToMarker = function (arr) {
4720 return arrayToUtcDate(arr);
4721 };
4722 GregorianCalendarSystem.prototype.markerToArray = function (marker) {
4723 return dateToUtcArray(marker);
4724 };
4725 return GregorianCalendarSystem;
4726}());
4727registerCalendarSystem('gregory', GregorianCalendarSystem);
4728
4729var ISO_RE = /^\s*(\d{4})(-(\d{2})(-(\d{2})([T ](\d{2}):(\d{2})(:(\d{2})(\.(\d+))?)?(Z|(([-+])(\d{2})(:?(\d{2}))?))?)?)?)?$/;
4730function parse(str) {
4731 var m = ISO_RE.exec(str);
4732 if (m) {
4733 var marker = new Date(Date.UTC(Number(m[1]), m[3] ? Number(m[3]) - 1 : 0, Number(m[5] || 1), Number(m[7] || 0), Number(m[8] || 0), Number(m[10] || 0), m[12] ? Number('0.' + m[12]) * 1000 : 0));
4734 if (isValidDate(marker)) {
4735 var timeZoneOffset = null;
4736 if (m[13]) {
4737 timeZoneOffset = (m[15] === '-' ? -1 : 1) * (Number(m[16] || 0) * 60 +
4738 Number(m[18] || 0));
4739 }
4740 return {
4741 marker: marker,
4742 isTimeUnspecified: !m[6],
4743 timeZoneOffset: timeZoneOffset
4744 };
4745 }
4746 }
4747 return null;
4748}
4749
4750var DateEnv = /** @class */ (function () {
4751 function DateEnv(settings) {
4752 var timeZone = this.timeZone = settings.timeZone;
4753 var isNamedTimeZone = timeZone !== 'local' && timeZone !== 'UTC';
4754 if (settings.namedTimeZoneImpl && isNamedTimeZone) {
4755 this.namedTimeZoneImpl = new settings.namedTimeZoneImpl(timeZone);
4756 }
4757 this.canComputeOffset = Boolean(!isNamedTimeZone || this.namedTimeZoneImpl);
4758 this.calendarSystem = createCalendarSystem(settings.calendarSystem);
4759 this.locale = settings.locale;
4760 this.weekDow = settings.locale.week.dow;
4761 this.weekDoy = settings.locale.week.doy;
4762 if (settings.weekNumberCalculation === 'ISO') {
4763 this.weekDow = 1;
4764 this.weekDoy = 4;
4765 }
4766 if (typeof settings.firstDay === 'number') {
4767 this.weekDow = settings.firstDay;
4768 }
4769 if (typeof settings.weekNumberCalculation === 'function') {
4770 this.weekNumberFunc = settings.weekNumberCalculation;
4771 }
4772 this.weekLabel = settings.weekLabel != null ? settings.weekLabel : settings.locale.options.weekLabel;
4773 this.cmdFormatter = settings.cmdFormatter;
4774 }
4775 // Creating / Parsing
4776 DateEnv.prototype.createMarker = function (input) {
4777 var meta = this.createMarkerMeta(input);
4778 if (meta === null) {
4779 return null;
4780 }
4781 return meta.marker;
4782 };
4783 DateEnv.prototype.createNowMarker = function () {
4784 if (this.canComputeOffset) {
4785 return this.timestampToMarker(new Date().valueOf());
4786 }
4787 else {
4788 // if we can't compute the current date val for a timezone,
4789 // better to give the current local date vals than UTC
4790 return arrayToUtcDate(dateToLocalArray(new Date()));
4791 }
4792 };
4793 DateEnv.prototype.createMarkerMeta = function (input) {
4794 if (typeof input === 'string') {
4795 return this.parse(input);
4796 }
4797 var marker = null;
4798 if (typeof input === 'number') {
4799 marker = this.timestampToMarker(input);
4800 }
4801 else if (input instanceof Date) {
4802 input = input.valueOf();
4803 if (!isNaN(input)) {
4804 marker = this.timestampToMarker(input);
4805 }
4806 }
4807 else if (Array.isArray(input)) {
4808 marker = arrayToUtcDate(input);
4809 }
4810 if (marker === null || !isValidDate(marker)) {
4811 return null;
4812 }
4813 return { marker: marker, isTimeUnspecified: false, forcedTzo: null };
4814 };
4815 DateEnv.prototype.parse = function (s) {
4816 var parts = parse(s);
4817 if (parts === null) {
4818 return null;
4819 }
4820 var marker = parts.marker;
4821 var forcedTzo = null;
4822 if (parts.timeZoneOffset !== null) {
4823 if (this.canComputeOffset) {
4824 marker = this.timestampToMarker(marker.valueOf() - parts.timeZoneOffset * 60 * 1000);
4825 }
4826 else {
4827 forcedTzo = parts.timeZoneOffset;
4828 }
4829 }
4830 return { marker: marker, isTimeUnspecified: parts.isTimeUnspecified, forcedTzo: forcedTzo };
4831 };
4832 // Accessors
4833 DateEnv.prototype.getYear = function (marker) {
4834 return this.calendarSystem.getMarkerYear(marker);
4835 };
4836 DateEnv.prototype.getMonth = function (marker) {
4837 return this.calendarSystem.getMarkerMonth(marker);
4838 };
4839 // Adding / Subtracting
4840 DateEnv.prototype.add = function (marker, dur) {
4841 var a = this.calendarSystem.markerToArray(marker);
4842 a[0] += dur.years;
4843 a[1] += dur.months;
4844 a[2] += dur.days;
4845 a[6] += dur.milliseconds;
4846 return this.calendarSystem.arrayToMarker(a);
4847 };
4848 DateEnv.prototype.subtract = function (marker, dur) {
4849 var a = this.calendarSystem.markerToArray(marker);
4850 a[0] -= dur.years;
4851 a[1] -= dur.months;
4852 a[2] -= dur.days;
4853 a[6] -= dur.milliseconds;
4854 return this.calendarSystem.arrayToMarker(a);
4855 };
4856 DateEnv.prototype.addYears = function (marker, n) {
4857 var a = this.calendarSystem.markerToArray(marker);
4858 a[0] += n;
4859 return this.calendarSystem.arrayToMarker(a);
4860 };
4861 DateEnv.prototype.addMonths = function (marker, n) {
4862 var a = this.calendarSystem.markerToArray(marker);
4863 a[1] += n;
4864 return this.calendarSystem.arrayToMarker(a);
4865 };
4866 // Diffing Whole Units
4867 DateEnv.prototype.diffWholeYears = function (m0, m1) {
4868 var calendarSystem = this.calendarSystem;
4869 if (timeAsMs(m0) === timeAsMs(m1) &&
4870 calendarSystem.getMarkerDay(m0) === calendarSystem.getMarkerDay(m1) &&
4871 calendarSystem.getMarkerMonth(m0) === calendarSystem.getMarkerMonth(m1)) {
4872 return calendarSystem.getMarkerYear(m1) - calendarSystem.getMarkerYear(m0);
4873 }
4874 return null;
4875 };
4876 DateEnv.prototype.diffWholeMonths = function (m0, m1) {
4877 var calendarSystem = this.calendarSystem;
4878 if (timeAsMs(m0) === timeAsMs(m1) &&
4879 calendarSystem.getMarkerDay(m0) === calendarSystem.getMarkerDay(m1)) {
4880 return (calendarSystem.getMarkerMonth(m1) - calendarSystem.getMarkerMonth(m0)) +
4881 (calendarSystem.getMarkerYear(m1) - calendarSystem.getMarkerYear(m0)) * 12;
4882 }
4883 return null;
4884 };
4885 // Range / Duration
4886 DateEnv.prototype.greatestWholeUnit = function (m0, m1) {
4887 var n = this.diffWholeYears(m0, m1);
4888 if (n !== null) {
4889 return { unit: 'year', value: n };
4890 }
4891 n = this.diffWholeMonths(m0, m1);
4892 if (n !== null) {
4893 return { unit: 'month', value: n };
4894 }
4895 n = diffWholeWeeks(m0, m1);
4896 if (n !== null) {
4897 return { unit: 'week', value: n };
4898 }
4899 n = diffWholeDays(m0, m1);
4900 if (n !== null) {
4901 return { unit: 'day', value: n };
4902 }
4903 n = diffHours(m0, m1);
4904 if (isInt(n)) {
4905 return { unit: 'hour', value: n };
4906 }
4907 n = diffMinutes(m0, m1);
4908 if (isInt(n)) {
4909 return { unit: 'minute', value: n };
4910 }
4911 n = diffSeconds(m0, m1);
4912 if (isInt(n)) {
4913 return { unit: 'second', value: n };
4914 }
4915 return { unit: 'millisecond', value: m1.valueOf() - m0.valueOf() };
4916 };
4917 DateEnv.prototype.countDurationsBetween = function (m0, m1, d) {
4918 // TODO: can use greatestWholeUnit
4919 var diff;
4920 if (d.years) {
4921 diff = this.diffWholeYears(m0, m1);
4922 if (diff !== null) {
4923 return diff / asRoughYears(d);
4924 }
4925 }
4926 if (d.months) {
4927 diff = this.diffWholeMonths(m0, m1);
4928 if (diff !== null) {
4929 return diff / asRoughMonths(d);
4930 }
4931 }
4932 if (d.days) {
4933 diff = diffWholeDays(m0, m1);
4934 if (diff !== null) {
4935 return diff / asRoughDays(d);
4936 }
4937 }
4938 return (m1.valueOf() - m0.valueOf()) / asRoughMs(d);
4939 };
4940 // Start-Of
4941 DateEnv.prototype.startOf = function (m, unit) {
4942 if (unit === 'year') {
4943 return this.startOfYear(m);
4944 }
4945 else if (unit === 'month') {
4946 return this.startOfMonth(m);
4947 }
4948 else if (unit === 'week') {
4949 return this.startOfWeek(m);
4950 }
4951 else if (unit === 'day') {
4952 return startOfDay(m);
4953 }
4954 else if (unit === 'hour') {
4955 return startOfHour(m);
4956 }
4957 else if (unit === 'minute') {
4958 return startOfMinute(m);
4959 }
4960 else if (unit === 'second') {
4961 return startOfSecond(m);
4962 }
4963 };
4964 DateEnv.prototype.startOfYear = function (m) {
4965 return this.calendarSystem.arrayToMarker([
4966 this.calendarSystem.getMarkerYear(m)
4967 ]);
4968 };
4969 DateEnv.prototype.startOfMonth = function (m) {
4970 return this.calendarSystem.arrayToMarker([
4971 this.calendarSystem.getMarkerYear(m),
4972 this.calendarSystem.getMarkerMonth(m)
4973 ]);
4974 };
4975 DateEnv.prototype.startOfWeek = function (m) {
4976 return this.calendarSystem.arrayToMarker([
4977 this.calendarSystem.getMarkerYear(m),
4978 this.calendarSystem.getMarkerMonth(m),
4979 m.getUTCDate() - ((m.getUTCDay() - this.weekDow + 7) % 7)
4980 ]);
4981 };
4982 // Week Number
4983 DateEnv.prototype.computeWeekNumber = function (marker) {
4984 if (this.weekNumberFunc) {
4985 return this.weekNumberFunc(this.toDate(marker));
4986 }
4987 else {
4988 return weekOfYear(marker, this.weekDow, this.weekDoy);
4989 }
4990 };
4991 // TODO: choke on timeZoneName: long
4992 DateEnv.prototype.format = function (marker, formatter, dateOptions) {
4993 if (dateOptions === void 0) { dateOptions = {}; }
4994 return formatter.format({
4995 marker: marker,
4996 timeZoneOffset: dateOptions.forcedTzo != null ?
4997 dateOptions.forcedTzo :
4998 this.offsetForMarker(marker)
4999 }, this);
5000 };
…文件过长,仅显示前 5000 行