UNPKG

929 kBJavaScriptView Raw
1/**
2 * vis-graph3d - data
3 * http://visjs.org/
4 *
5 * Create interactive, animated 3d graphs. Surfaces, lines, dots and block styling out of the box.
6 *
7 * @version 5.3.2
8 * @date 2019-11-08T16:17:57Z
9 *
10 * @copyright (c) 2011-2017 Almende B.V, http://almende.com
11 * @copyright (c) 2018-2019 visjs contributors, https://github.com/visjs
12 *
13 * @license
14 * vis.js is dual licensed under both
15 *
16 * 1. The Apache 2.0 License
17 * http://www.apache.org/licenses/LICENSE-2.0
18 *
19 * and
20 *
21 * 2. The MIT License
22 * http://opensource.org/licenses/MIT
23 *
24 * vis.js may be distributed under either license.
25 */
26
27var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
28
29function commonjsRequire() {
30 throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
31}
32
33function createCommonjsModule(fn, module) {
34 return module = {
35 exports: {}
36 }, fn(module, module.exports), module.exports;
37}
38
39var check = function (it) {
40 return it && it.Math == Math && it;
41}; // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
42
43
44var global_1 = // eslint-disable-next-line no-undef
45check(typeof globalThis == 'object' && globalThis) || check(typeof window == 'object' && window) || check(typeof self == 'object' && self) || check(typeof commonjsGlobal == 'object' && commonjsGlobal) || // eslint-disable-next-line no-new-func
46Function('return this')();
47
48var fails = function (exec) {
49 try {
50 return !!exec();
51 } catch (error) {
52 return true;
53 }
54}; // Thank's IE8 for his funny defineProperty
55
56
57var descriptors = !fails(function () {
58 return Object.defineProperty({}, 'a', {
59 get: function () {
60 return 7;
61 }
62 }).a != 7;
63});
64var nativePropertyIsEnumerable = {}.propertyIsEnumerable;
65var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; // Nashorn ~ JDK8 bug
66
67var NASHORN_BUG = getOwnPropertyDescriptor && !nativePropertyIsEnumerable.call({
68 1: 2
69}, 1); // `Object.prototype.propertyIsEnumerable` method implementation
70// https://tc39.github.io/ecma262/#sec-object.prototype.propertyisenumerable
71
72var f = NASHORN_BUG ? function propertyIsEnumerable(V) {
73 var descriptor = getOwnPropertyDescriptor(this, V);
74 return !!descriptor && descriptor.enumerable;
75} : nativePropertyIsEnumerable;
76var objectPropertyIsEnumerable = {
77 f: f
78};
79
80var createPropertyDescriptor = function (bitmap, value) {
81 return {
82 enumerable: !(bitmap & 1),
83 configurable: !(bitmap & 2),
84 writable: !(bitmap & 4),
85 value: value
86 };
87};
88
89var toString = {}.toString;
90
91var classofRaw = function (it) {
92 return toString.call(it).slice(8, -1);
93};
94
95var split = ''.split; // fallback for non-array-like ES3 and non-enumerable old V8 strings
96
97var indexedObject = fails(function () {
98 // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
99 // eslint-disable-next-line no-prototype-builtins
100 return !Object('z').propertyIsEnumerable(0);
101}) ? function (it) {
102 return classofRaw(it) == 'String' ? split.call(it, '') : Object(it);
103} : Object; // `RequireObjectCoercible` abstract operation
104// https://tc39.github.io/ecma262/#sec-requireobjectcoercible
105
106var requireObjectCoercible = function (it) {
107 if (it == undefined) throw TypeError("Can't call method on " + it);
108 return it;
109}; // toObject with fallback for non-array-like ES3 strings
110
111
112var toIndexedObject = function (it) {
113 return indexedObject(requireObjectCoercible(it));
114};
115
116var isObject = function (it) {
117 return typeof it === 'object' ? it !== null : typeof it === 'function';
118}; // `ToPrimitive` abstract operation
119// https://tc39.github.io/ecma262/#sec-toprimitive
120// instead of the ES6 spec version, we didn't implement @@toPrimitive case
121// and the second argument - flag - preferred type is a string
122
123
124var toPrimitive = function (input, PREFERRED_STRING) {
125 if (!isObject(input)) return input;
126 var fn, val;
127 if (PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
128 if (typeof (fn = input.valueOf) == 'function' && !isObject(val = fn.call(input))) return val;
129 if (!PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
130 throw TypeError("Can't convert object to primitive value");
131};
132
133var hasOwnProperty = {}.hasOwnProperty;
134
135var has = function (it, key) {
136 return hasOwnProperty.call(it, key);
137};
138
139var document$1 = global_1.document; // typeof document.createElement is 'object' in old IE
140
141var EXISTS = isObject(document$1) && isObject(document$1.createElement);
142
143var documentCreateElement = function (it) {
144 return EXISTS ? document$1.createElement(it) : {};
145}; // Thank's IE8 for his funny defineProperty
146
147
148var ie8DomDefine = !descriptors && !fails(function () {
149 return Object.defineProperty(documentCreateElement('div'), 'a', {
150 get: function () {
151 return 7;
152 }
153 }).a != 7;
154});
155var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; // `Object.getOwnPropertyDescriptor` method
156// https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor
157
158var f$1 = descriptors ? nativeGetOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
159 O = toIndexedObject(O);
160 P = toPrimitive(P, true);
161 if (ie8DomDefine) try {
162 return nativeGetOwnPropertyDescriptor(O, P);
163 } catch (error) {
164 /* empty */
165 }
166 if (has(O, P)) return createPropertyDescriptor(!objectPropertyIsEnumerable.f.call(O, P), O[P]);
167};
168var objectGetOwnPropertyDescriptor = {
169 f: f$1
170};
171var replacement = /#|\.prototype\./;
172
173var isForced = function (feature, detection) {
174 var value = data[normalize(feature)];
175 return value == POLYFILL ? true : value == NATIVE ? false : typeof detection == 'function' ? fails(detection) : !!detection;
176};
177
178var normalize = isForced.normalize = function (string) {
179 return String(string).replace(replacement, '.').toLowerCase();
180};
181
182var data = isForced.data = {};
183var NATIVE = isForced.NATIVE = 'N';
184var POLYFILL = isForced.POLYFILL = 'P';
185var isForced_1 = isForced;
186var path = {};
187
188var aFunction = function (it) {
189 if (typeof it != 'function') {
190 throw TypeError(String(it) + ' is not a function');
191 }
192
193 return it;
194}; // optional / simple context binding
195
196
197var bindContext = function (fn, that, length) {
198 aFunction(fn);
199 if (that === undefined) return fn;
200
201 switch (length) {
202 case 0:
203 return function () {
204 return fn.call(that);
205 };
206
207 case 1:
208 return function (a) {
209 return fn.call(that, a);
210 };
211
212 case 2:
213 return function (a, b) {
214 return fn.call(that, a, b);
215 };
216
217 case 3:
218 return function (a, b, c) {
219 return fn.call(that, a, b, c);
220 };
221 }
222
223 return function ()
224 /* ...args */
225 {
226 return fn.apply(that, arguments);
227 };
228};
229
230var anObject = function (it) {
231 if (!isObject(it)) {
232 throw TypeError(String(it) + ' is not an object');
233 }
234
235 return it;
236};
237
238var nativeDefineProperty = Object.defineProperty; // `Object.defineProperty` method
239// https://tc39.github.io/ecma262/#sec-object.defineproperty
240
241var f$2 = descriptors ? nativeDefineProperty : function defineProperty(O, P, Attributes) {
242 anObject(O);
243 P = toPrimitive(P, true);
244 anObject(Attributes);
245 if (ie8DomDefine) try {
246 return nativeDefineProperty(O, P, Attributes);
247 } catch (error) {
248 /* empty */
249 }
250 if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported');
251 if ('value' in Attributes) O[P] = Attributes.value;
252 return O;
253};
254var objectDefineProperty = {
255 f: f$2
256};
257var createNonEnumerableProperty = descriptors ? function (object, key, value) {
258 return objectDefineProperty.f(object, key, createPropertyDescriptor(1, value));
259} : function (object, key, value) {
260 object[key] = value;
261 return object;
262};
263var getOwnPropertyDescriptor$1 = objectGetOwnPropertyDescriptor.f;
264
265var wrapConstructor = function (NativeConstructor) {
266 var Wrapper = function (a, b, c) {
267 if (this instanceof NativeConstructor) {
268 switch (arguments.length) {
269 case 0:
270 return new NativeConstructor();
271
272 case 1:
273 return new NativeConstructor(a);
274
275 case 2:
276 return new NativeConstructor(a, b);
277 }
278
279 return new NativeConstructor(a, b, c);
280 }
281
282 return NativeConstructor.apply(this, arguments);
283 };
284
285 Wrapper.prototype = NativeConstructor.prototype;
286 return Wrapper;
287};
288/*
289 options.target - name of the target object
290 options.global - target is the global object
291 options.stat - export as static methods of target
292 options.proto - export as prototype methods of target
293 options.real - real prototype method for the `pure` version
294 options.forced - export even if the native feature is available
295 options.bind - bind methods to the target, required for the `pure` version
296 options.wrap - wrap constructors to preventing global pollution, required for the `pure` version
297 options.unsafe - use the simple assignment of property instead of delete + defineProperty
298 options.sham - add a flag to not completely full polyfills
299 options.enumerable - export as enumerable property
300 options.noTargetGet - prevent calling a getter on target
301*/
302
303
304var _export = function (options, source) {
305 var TARGET = options.target;
306 var GLOBAL = options.global;
307 var STATIC = options.stat;
308 var PROTO = options.proto;
309 var nativeSource = GLOBAL ? global_1 : STATIC ? global_1[TARGET] : (global_1[TARGET] || {}).prototype;
310 var target = GLOBAL ? path : path[TARGET] || (path[TARGET] = {});
311 var targetPrototype = target.prototype;
312 var FORCED, USE_NATIVE, VIRTUAL_PROTOTYPE;
313 var key, sourceProperty, targetProperty, nativeProperty, resultProperty, descriptor;
314
315 for (key in source) {
316 FORCED = isForced_1(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced); // contains in native
317
318 USE_NATIVE = !FORCED && nativeSource && has(nativeSource, key);
319 targetProperty = target[key];
320 if (USE_NATIVE) if (options.noTargetGet) {
321 descriptor = getOwnPropertyDescriptor$1(nativeSource, key);
322 nativeProperty = descriptor && descriptor.value;
323 } else nativeProperty = nativeSource[key]; // export native or implementation
324
325 sourceProperty = USE_NATIVE && nativeProperty ? nativeProperty : source[key];
326 if (USE_NATIVE && typeof targetProperty === typeof sourceProperty) continue; // bind timers to global for call from export context
327
328 if (options.bind && USE_NATIVE) resultProperty = bindContext(sourceProperty, global_1); // wrap global constructors for prevent changs in this version
329 else if (options.wrap && USE_NATIVE) resultProperty = wrapConstructor(sourceProperty); // make static versions for prototype methods
330 else if (PROTO && typeof sourceProperty == 'function') resultProperty = bindContext(Function.call, sourceProperty); // default case
331 else resultProperty = sourceProperty; // add a flag to not completely full polyfills
332
333 if (options.sham || sourceProperty && sourceProperty.sham || targetProperty && targetProperty.sham) {
334 createNonEnumerableProperty(resultProperty, 'sham', true);
335 }
336
337 target[key] = resultProperty;
338
339 if (PROTO) {
340 VIRTUAL_PROTOTYPE = TARGET + 'Prototype';
341
342 if (!has(path, VIRTUAL_PROTOTYPE)) {
343 createNonEnumerableProperty(path, VIRTUAL_PROTOTYPE, {});
344 } // export virtual prototype methods
345
346
347 path[VIRTUAL_PROTOTYPE][key] = sourceProperty; // export real prototype methods
348
349 if (options.real && targetPrototype && !targetPrototype[key]) {
350 createNonEnumerableProperty(targetPrototype, key, sourceProperty);
351 }
352 }
353 }
354}; // `Object.defineProperty` method
355// https://tc39.github.io/ecma262/#sec-object.defineproperty
356
357
358_export({
359 target: 'Object',
360 stat: true,
361 forced: !descriptors,
362 sham: !descriptors
363}, {
364 defineProperty: objectDefineProperty.f
365});
366
367var defineProperty_1 = createCommonjsModule(function (module) {
368 var Object = path.Object;
369
370 var defineProperty = module.exports = function defineProperty(it, key, desc) {
371 return Object.defineProperty(it, key, desc);
372 };
373
374 if (Object.defineProperty.sham) defineProperty.sham = true;
375});
376var defineProperty = defineProperty_1;
377var defineProperty$1 = defineProperty;
378var ceil = Math.ceil;
379var floor = Math.floor; // `ToInteger` abstract operation
380// https://tc39.github.io/ecma262/#sec-tointeger
381
382var toInteger = function (argument) {
383 return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor : ceil)(argument);
384};
385
386var min = Math.min; // `ToLength` abstract operation
387// https://tc39.github.io/ecma262/#sec-tolength
388
389var toLength = function (argument) {
390 return argument > 0 ? min(toInteger(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
391};
392
393var max = Math.max;
394var min$1 = Math.min; // Helper for a popular repeating case of the spec:
395// Let integer be ? ToInteger(index).
396// If integer < 0, let result be max((length + integer), 0); else let result be min(length, length).
397
398var toAbsoluteIndex = function (index, length) {
399 var integer = toInteger(index);
400 return integer < 0 ? max(integer + length, 0) : min$1(integer, length);
401}; // `Array.prototype.{ indexOf, includes }` methods implementation
402
403
404var createMethod = function (IS_INCLUDES) {
405 return function ($this, el, fromIndex) {
406 var O = toIndexedObject($this);
407 var length = toLength(O.length);
408 var index = toAbsoluteIndex(fromIndex, length);
409 var value; // Array#includes uses SameValueZero equality algorithm
410 // eslint-disable-next-line no-self-compare
411
412 if (IS_INCLUDES && el != el) while (length > index) {
413 value = O[index++]; // eslint-disable-next-line no-self-compare
414
415 if (value != value) return true; // Array#indexOf ignores holes, Array#includes - not
416 } else for (; length > index; index++) {
417 if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
418 }
419 return !IS_INCLUDES && -1;
420 };
421};
422
423var arrayIncludes = {
424 // `Array.prototype.includes` method
425 // https://tc39.github.io/ecma262/#sec-array.prototype.includes
426 includes: createMethod(true),
427 // `Array.prototype.indexOf` method
428 // https://tc39.github.io/ecma262/#sec-array.prototype.indexof
429 indexOf: createMethod(false)
430};
431var hiddenKeys = {};
432var indexOf = arrayIncludes.indexOf;
433
434var objectKeysInternal = function (object, names) {
435 var O = toIndexedObject(object);
436 var i = 0;
437 var result = [];
438 var key;
439
440 for (key in O) !has(hiddenKeys, key) && has(O, key) && result.push(key); // Don't enum bug & hidden keys
441
442
443 while (names.length > i) if (has(O, key = names[i++])) {
444 ~indexOf(result, key) || result.push(key);
445 }
446
447 return result;
448}; // IE8- don't enum bug keys
449
450
451var enumBugKeys = ['constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf']; // `Object.keys` method
452// https://tc39.github.io/ecma262/#sec-object.keys
453
454var objectKeys = Object.keys || function keys(O) {
455 return objectKeysInternal(O, enumBugKeys);
456}; // `Object.defineProperties` method
457// https://tc39.github.io/ecma262/#sec-object.defineproperties
458
459
460var objectDefineProperties = descriptors ? Object.defineProperties : function defineProperties(O, Properties) {
461 anObject(O);
462 var keys = objectKeys(Properties);
463 var length = keys.length;
464 var index = 0;
465 var key;
466
467 while (length > index) objectDefineProperty.f(O, key = keys[index++], Properties[key]);
468
469 return O;
470}; // `Object.defineProperties` method
471// https://tc39.github.io/ecma262/#sec-object.defineproperties
472
473_export({
474 target: 'Object',
475 stat: true,
476 forced: !descriptors,
477 sham: !descriptors
478}, {
479 defineProperties: objectDefineProperties
480});
481
482var defineProperties_1 = createCommonjsModule(function (module) {
483 var Object = path.Object;
484
485 var defineProperties = module.exports = function defineProperties(T, D) {
486 return Object.defineProperties(T, D);
487 };
488
489 if (Object.defineProperties.sham) defineProperties.sham = true;
490});
491var defineProperties = defineProperties_1;
492var defineProperties$1 = defineProperties;
493
494var aFunction$1 = function (variable) {
495 return typeof variable == 'function' ? variable : undefined;
496};
497
498var getBuiltIn = function (namespace, method) {
499 return arguments.length < 2 ? aFunction$1(path[namespace]) || aFunction$1(global_1[namespace]) : path[namespace] && path[namespace][method] || global_1[namespace] && global_1[namespace][method];
500};
501
502var hiddenKeys$1 = enumBugKeys.concat('length', 'prototype'); // `Object.getOwnPropertyNames` method
503// https://tc39.github.io/ecma262/#sec-object.getownpropertynames
504
505var f$3 = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
506 return objectKeysInternal(O, hiddenKeys$1);
507};
508
509var objectGetOwnPropertyNames = {
510 f: f$3
511};
512var f$4 = Object.getOwnPropertySymbols;
513var objectGetOwnPropertySymbols = {
514 f: f$4
515}; // all object keys, includes non-enumerable and symbols
516
517var ownKeys = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {
518 var keys = objectGetOwnPropertyNames.f(anObject(it));
519 var getOwnPropertySymbols = objectGetOwnPropertySymbols.f;
520 return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys;
521};
522
523var createProperty = function (object, key, value) {
524 var propertyKey = toPrimitive(key);
525 if (propertyKey in object) objectDefineProperty.f(object, propertyKey, createPropertyDescriptor(0, value));else object[propertyKey] = value;
526}; // `Object.getOwnPropertyDescriptors` method
527// https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptors
528
529
530_export({
531 target: 'Object',
532 stat: true,
533 sham: !descriptors
534}, {
535 getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object) {
536 var O = toIndexedObject(object);
537 var getOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f;
538 var keys = ownKeys(O);
539 var result = {};
540 var index = 0;
541 var key, descriptor;
542
543 while (keys.length > index) {
544 descriptor = getOwnPropertyDescriptor(O, key = keys[index++]);
545 if (descriptor !== undefined) createProperty(result, key, descriptor);
546 }
547
548 return result;
549 }
550});
551
552var getOwnPropertyDescriptors = path.Object.getOwnPropertyDescriptors;
553var getOwnPropertyDescriptors$1 = getOwnPropertyDescriptors;
554var getOwnPropertyDescriptors$2 = getOwnPropertyDescriptors$1;
555var nativeGetOwnPropertyDescriptor$1 = objectGetOwnPropertyDescriptor.f;
556var FAILS_ON_PRIMITIVES = fails(function () {
557 nativeGetOwnPropertyDescriptor$1(1);
558});
559var FORCED = !descriptors || FAILS_ON_PRIMITIVES; // `Object.getOwnPropertyDescriptor` method
560// https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor
561
562_export({
563 target: 'Object',
564 stat: true,
565 forced: FORCED,
566 sham: !descriptors
567}, {
568 getOwnPropertyDescriptor: function getOwnPropertyDescriptor(it, key) {
569 return nativeGetOwnPropertyDescriptor$1(toIndexedObject(it), key);
570 }
571});
572
573var getOwnPropertyDescriptor_1 = createCommonjsModule(function (module) {
574 var Object = path.Object;
575
576 var getOwnPropertyDescriptor = module.exports = function getOwnPropertyDescriptor(it, key) {
577 return Object.getOwnPropertyDescriptor(it, key);
578 };
579
580 if (Object.getOwnPropertyDescriptor.sham) getOwnPropertyDescriptor.sham = true;
581});
582var getOwnPropertyDescriptor$2 = getOwnPropertyDescriptor_1;
583var getOwnPropertyDescriptor$3 = getOwnPropertyDescriptor$2;
584var nativeSymbol = !!Object.getOwnPropertySymbols && !fails(function () {
585 // Chrome 38 Symbol has incorrect toString conversion
586 // eslint-disable-next-line no-undef
587 return !String(Symbol());
588}); // `IsArray` abstract operation
589// https://tc39.github.io/ecma262/#sec-isarray
590
591var isArray = Array.isArray || function isArray(arg) {
592 return classofRaw(arg) == 'Array';
593}; // `ToObject` abstract operation
594// https://tc39.github.io/ecma262/#sec-toobject
595
596
597var toObject = function (argument) {
598 return Object(requireObjectCoercible(argument));
599};
600
601var html = getBuiltIn('document', 'documentElement');
602
603var setGlobal = function (key, value) {
604 try {
605 createNonEnumerableProperty(global_1, key, value);
606 } catch (error) {
607 global_1[key] = value;
608 }
609
610 return value;
611};
612
613var SHARED = '__core-js_shared__';
614var store = global_1[SHARED] || setGlobal(SHARED, {});
615var sharedStore = store;
616var shared = createCommonjsModule(function (module) {
617 (module.exports = function (key, value) {
618 return sharedStore[key] || (sharedStore[key] = value !== undefined ? value : {});
619 })('versions', []).push({
620 version: '3.3.6',
621 mode: 'pure',
622 copyright: '© 2019 Denis Pushkarev (zloirock.ru)'
623 });
624});
625var id = 0;
626var postfix = Math.random();
627
628var uid = function (key) {
629 return 'Symbol(' + String(key === undefined ? '' : key) + ')_' + (++id + postfix).toString(36);
630};
631
632var keys = shared('keys');
633
634var sharedKey = function (key) {
635 return keys[key] || (keys[key] = uid(key));
636};
637
638var IE_PROTO = sharedKey('IE_PROTO');
639var PROTOTYPE = 'prototype';
640
641var Empty = function () {
642 /* empty */
643}; // Create object with fake `null` prototype: use iframe Object with cleared prototype
644
645
646var createDict = function () {
647 // Thrash, waste and sodomy: IE GC bug
648 var iframe = documentCreateElement('iframe');
649 var length = enumBugKeys.length;
650 var lt = '<';
651 var script = 'script';
652 var gt = '>';
653 var js = 'java' + script + ':';
654 var iframeDocument;
655 iframe.style.display = 'none';
656 html.appendChild(iframe);
657 iframe.src = String(js);
658 iframeDocument = iframe.contentWindow.document;
659 iframeDocument.open();
660 iframeDocument.write(lt + script + gt + 'document.F=Object' + lt + '/' + script + gt);
661 iframeDocument.close();
662 createDict = iframeDocument.F;
663
664 while (length--) delete createDict[PROTOTYPE][enumBugKeys[length]];
665
666 return createDict();
667}; // `Object.create` method
668// https://tc39.github.io/ecma262/#sec-object.create
669
670
671var objectCreate = Object.create || function create(O, Properties) {
672 var result;
673
674 if (O !== null) {
675 Empty[PROTOTYPE] = anObject(O);
676 result = new Empty();
677 Empty[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf polyfill
678
679 result[IE_PROTO] = O;
680 } else result = createDict();
681
682 return Properties === undefined ? result : objectDefineProperties(result, Properties);
683};
684
685hiddenKeys[IE_PROTO] = true;
686var nativeGetOwnPropertyNames = objectGetOwnPropertyNames.f;
687var toString$1 = {}.toString;
688var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames ? Object.getOwnPropertyNames(window) : [];
689
690var getWindowNames = function (it) {
691 try {
692 return nativeGetOwnPropertyNames(it);
693 } catch (error) {
694 return windowNames.slice();
695 }
696}; // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
697
698
699var f$5 = function getOwnPropertyNames(it) {
700 return windowNames && toString$1.call(it) == '[object Window]' ? getWindowNames(it) : nativeGetOwnPropertyNames(toIndexedObject(it));
701};
702
703var objectGetOwnPropertyNamesExternal = {
704 f: f$5
705};
706
707var redefine = function (target, key, value, options) {
708 if (options && options.enumerable) target[key] = value;else createNonEnumerableProperty(target, key, value);
709};
710
711var Symbol$1 = global_1.Symbol;
712var store$1 = shared('wks');
713
714var wellKnownSymbol = function (name) {
715 return store$1[name] || (store$1[name] = nativeSymbol && Symbol$1[name] || (nativeSymbol ? Symbol$1 : uid)('Symbol.' + name));
716};
717
718var f$6 = wellKnownSymbol;
719var wrappedWellKnownSymbol = {
720 f: f$6
721};
722var defineProperty$2 = objectDefineProperty.f;
723
724var defineWellKnownSymbol = function (NAME) {
725 var Symbol = path.Symbol || (path.Symbol = {});
726 if (!has(Symbol, NAME)) defineProperty$2(Symbol, NAME, {
727 value: wrappedWellKnownSymbol.f(NAME)
728 });
729};
730
731var TO_STRING_TAG = wellKnownSymbol('toStringTag'); // ES3 wrong here
732
733var CORRECT_ARGUMENTS = classofRaw(function () {
734 return arguments;
735}()) == 'Arguments'; // fallback for IE11 Script Access Denied error
736
737var tryGet = function (it, key) {
738 try {
739 return it[key];
740 } catch (error) {
741 /* empty */
742 }
743}; // getting tag from ES6+ `Object.prototype.toString`
744
745
746var classof = function (it) {
747 var O, tag, result;
748 return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case
749 : typeof (tag = tryGet(O = Object(it), TO_STRING_TAG)) == 'string' ? tag // builtinTag case
750 : CORRECT_ARGUMENTS ? classofRaw(O) // ES3 arguments fallback
751 : (result = classofRaw(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : result;
752};
753
754var TO_STRING_TAG$1 = wellKnownSymbol('toStringTag');
755var test = {};
756test[TO_STRING_TAG$1] = 'z'; // `Object.prototype.toString` method implementation
757// https://tc39.github.io/ecma262/#sec-object.prototype.tostring
758
759var objectToString = String(test) !== '[object z]' ? function toString() {
760 return '[object ' + classof(this) + ']';
761} : test.toString;
762var defineProperty$3 = objectDefineProperty.f;
763var TO_STRING_TAG$2 = wellKnownSymbol('toStringTag');
764var METHOD_REQUIRED = objectToString !== {}.toString;
765
766var setToStringTag = function (it, TAG, STATIC, SET_METHOD) {
767 if (it) {
768 var target = STATIC ? it : it.prototype;
769
770 if (!has(target, TO_STRING_TAG$2)) {
771 defineProperty$3(target, TO_STRING_TAG$2, {
772 configurable: true,
773 value: TAG
774 });
775 }
776
777 if (SET_METHOD && METHOD_REQUIRED) {
778 createNonEnumerableProperty(target, 'toString', objectToString);
779 }
780 }
781};
782
783var functionToString = shared('native-function-to-string', Function.toString);
784var WeakMap = global_1.WeakMap;
785var nativeWeakMap = typeof WeakMap === 'function' && /native code/.test(functionToString.call(WeakMap));
786var WeakMap$1 = global_1.WeakMap;
787var set, get, has$1;
788
789var enforce = function (it) {
790 return has$1(it) ? get(it) : set(it, {});
791};
792
793var getterFor = function (TYPE) {
794 return function (it) {
795 var state;
796
797 if (!isObject(it) || (state = get(it)).type !== TYPE) {
798 throw TypeError('Incompatible receiver, ' + TYPE + ' required');
799 }
800
801 return state;
802 };
803};
804
805if (nativeWeakMap) {
806 var store$2 = new WeakMap$1();
807 var wmget = store$2.get;
808 var wmhas = store$2.has;
809 var wmset = store$2.set;
810
811 set = function (it, metadata) {
812 wmset.call(store$2, it, metadata);
813 return metadata;
814 };
815
816 get = function (it) {
817 return wmget.call(store$2, it) || {};
818 };
819
820 has$1 = function (it) {
821 return wmhas.call(store$2, it);
822 };
823} else {
824 var STATE = sharedKey('state');
825 hiddenKeys[STATE] = true;
826
827 set = function (it, metadata) {
828 createNonEnumerableProperty(it, STATE, metadata);
829 return metadata;
830 };
831
832 get = function (it) {
833 return has(it, STATE) ? it[STATE] : {};
834 };
835
836 has$1 = function (it) {
837 return has(it, STATE);
838 };
839}
840
841var internalState = {
842 set: set,
843 get: get,
844 has: has$1,
845 enforce: enforce,
846 getterFor: getterFor
847};
848var SPECIES = wellKnownSymbol('species'); // `ArraySpeciesCreate` abstract operation
849// https://tc39.github.io/ecma262/#sec-arrayspeciescreate
850
851var arraySpeciesCreate = function (originalArray, length) {
852 var C;
853
854 if (isArray(originalArray)) {
855 C = originalArray.constructor; // cross-realm fallback
856
857 if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined;else if (isObject(C)) {
858 C = C[SPECIES];
859 if (C === null) C = undefined;
860 }
861 }
862
863 return new (C === undefined ? Array : C)(length === 0 ? 0 : length);
864};
865
866var push = [].push; // `Array.prototype.{ forEach, map, filter, some, every, find, findIndex }` methods implementation
867
868var createMethod$1 = function (TYPE) {
869 var IS_MAP = TYPE == 1;
870 var IS_FILTER = TYPE == 2;
871 var IS_SOME = TYPE == 3;
872 var IS_EVERY = TYPE == 4;
873 var IS_FIND_INDEX = TYPE == 6;
874 var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;
875 return function ($this, callbackfn, that, specificCreate) {
876 var O = toObject($this);
877 var self = indexedObject(O);
878 var boundFunction = bindContext(callbackfn, that, 3);
879 var length = toLength(self.length);
880 var index = 0;
881 var create = specificCreate || arraySpeciesCreate;
882 var target = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined;
883 var value, result;
884
885 for (; length > index; index++) if (NO_HOLES || index in self) {
886 value = self[index];
887 result = boundFunction(value, index, O);
888
889 if (TYPE) {
890 if (IS_MAP) target[index] = result; // map
891 else if (result) switch (TYPE) {
892 case 3:
893 return true;
894 // some
895
896 case 5:
897 return value;
898 // find
899
900 case 6:
901 return index;
902 // findIndex
903
904 case 2:
905 push.call(target, value);
906 // filter
907 } else if (IS_EVERY) return false; // every
908 }
909 }
910
911 return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : target;
912 };
913};
914
915var arrayIteration = {
916 // `Array.prototype.forEach` method
917 // https://tc39.github.io/ecma262/#sec-array.prototype.foreach
918 forEach: createMethod$1(0),
919 // `Array.prototype.map` method
920 // https://tc39.github.io/ecma262/#sec-array.prototype.map
921 map: createMethod$1(1),
922 // `Array.prototype.filter` method
923 // https://tc39.github.io/ecma262/#sec-array.prototype.filter
924 filter: createMethod$1(2),
925 // `Array.prototype.some` method
926 // https://tc39.github.io/ecma262/#sec-array.prototype.some
927 some: createMethod$1(3),
928 // `Array.prototype.every` method
929 // https://tc39.github.io/ecma262/#sec-array.prototype.every
930 every: createMethod$1(4),
931 // `Array.prototype.find` method
932 // https://tc39.github.io/ecma262/#sec-array.prototype.find
933 find: createMethod$1(5),
934 // `Array.prototype.findIndex` method
935 // https://tc39.github.io/ecma262/#sec-array.prototype.findIndex
936 findIndex: createMethod$1(6)
937};
938var $forEach = arrayIteration.forEach;
939var HIDDEN = sharedKey('hidden');
940var SYMBOL = 'Symbol';
941var PROTOTYPE$1 = 'prototype';
942var TO_PRIMITIVE = wellKnownSymbol('toPrimitive');
943var setInternalState = internalState.set;
944var getInternalState = internalState.getterFor(SYMBOL);
945var ObjectPrototype = Object[PROTOTYPE$1];
946var $Symbol = global_1.Symbol;
947var JSON$1 = global_1.JSON;
948var nativeJSONStringify = JSON$1 && JSON$1.stringify;
949var nativeGetOwnPropertyDescriptor$2 = objectGetOwnPropertyDescriptor.f;
950var nativeDefineProperty$1 = objectDefineProperty.f;
951var nativeGetOwnPropertyNames$1 = objectGetOwnPropertyNamesExternal.f;
952var nativePropertyIsEnumerable$1 = objectPropertyIsEnumerable.f;
953var AllSymbols = shared('symbols');
954var ObjectPrototypeSymbols = shared('op-symbols');
955var StringToSymbolRegistry = shared('string-to-symbol-registry');
956var SymbolToStringRegistry = shared('symbol-to-string-registry');
957var WellKnownSymbolsStore = shared('wks');
958var QObject = global_1.QObject; // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
959
960var USE_SETTER = !QObject || !QObject[PROTOTYPE$1] || !QObject[PROTOTYPE$1].findChild; // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
961
962var setSymbolDescriptor = descriptors && fails(function () {
963 return objectCreate(nativeDefineProperty$1({}, 'a', {
964 get: function () {
965 return nativeDefineProperty$1(this, 'a', {
966 value: 7
967 }).a;
968 }
969 })).a != 7;
970}) ? function (O, P, Attributes) {
971 var ObjectPrototypeDescriptor = nativeGetOwnPropertyDescriptor$2(ObjectPrototype, P);
972 if (ObjectPrototypeDescriptor) delete ObjectPrototype[P];
973 nativeDefineProperty$1(O, P, Attributes);
974
975 if (ObjectPrototypeDescriptor && O !== ObjectPrototype) {
976 nativeDefineProperty$1(ObjectPrototype, P, ObjectPrototypeDescriptor);
977 }
978} : nativeDefineProperty$1;
979
980var wrap = function (tag, description) {
981 var symbol = AllSymbols[tag] = objectCreate($Symbol[PROTOTYPE$1]);
982 setInternalState(symbol, {
983 type: SYMBOL,
984 tag: tag,
985 description: description
986 });
987 if (!descriptors) symbol.description = description;
988 return symbol;
989};
990
991var isSymbol = nativeSymbol && typeof $Symbol.iterator == 'symbol' ? function (it) {
992 return typeof it == 'symbol';
993} : function (it) {
994 return Object(it) instanceof $Symbol;
995};
996
997var $defineProperty = function defineProperty(O, P, Attributes) {
998 if (O === ObjectPrototype) $defineProperty(ObjectPrototypeSymbols, P, Attributes);
999 anObject(O);
1000 var key = toPrimitive(P, true);
1001 anObject(Attributes);
1002
1003 if (has(AllSymbols, key)) {
1004 if (!Attributes.enumerable) {
1005 if (!has(O, HIDDEN)) nativeDefineProperty$1(O, HIDDEN, createPropertyDescriptor(1, {}));
1006 O[HIDDEN][key] = true;
1007 } else {
1008 if (has(O, HIDDEN) && O[HIDDEN][key]) O[HIDDEN][key] = false;
1009 Attributes = objectCreate(Attributes, {
1010 enumerable: createPropertyDescriptor(0, false)
1011 });
1012 }
1013
1014 return setSymbolDescriptor(O, key, Attributes);
1015 }
1016
1017 return nativeDefineProperty$1(O, key, Attributes);
1018};
1019
1020var $defineProperties = function defineProperties(O, Properties) {
1021 anObject(O);
1022 var properties = toIndexedObject(Properties);
1023 var keys = objectKeys(properties).concat($getOwnPropertySymbols(properties));
1024 $forEach(keys, function (key) {
1025 if (!descriptors || $propertyIsEnumerable.call(properties, key)) $defineProperty(O, key, properties[key]);
1026 });
1027 return O;
1028};
1029
1030var $create = function create(O, Properties) {
1031 return Properties === undefined ? objectCreate(O) : $defineProperties(objectCreate(O), Properties);
1032};
1033
1034var $propertyIsEnumerable = function propertyIsEnumerable(V) {
1035 var P = toPrimitive(V, true);
1036 var enumerable = nativePropertyIsEnumerable$1.call(this, P);
1037 if (this === ObjectPrototype && has(AllSymbols, P) && !has(ObjectPrototypeSymbols, P)) return false;
1038 return enumerable || !has(this, P) || !has(AllSymbols, P) || has(this, HIDDEN) && this[HIDDEN][P] ? enumerable : true;
1039};
1040
1041var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(O, P) {
1042 var it = toIndexedObject(O);
1043 var key = toPrimitive(P, true);
1044 if (it === ObjectPrototype && has(AllSymbols, key) && !has(ObjectPrototypeSymbols, key)) return;
1045 var descriptor = nativeGetOwnPropertyDescriptor$2(it, key);
1046
1047 if (descriptor && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) {
1048 descriptor.enumerable = true;
1049 }
1050
1051 return descriptor;
1052};
1053
1054var $getOwnPropertyNames = function getOwnPropertyNames(O) {
1055 var names = nativeGetOwnPropertyNames$1(toIndexedObject(O));
1056 var result = [];
1057 $forEach(names, function (key) {
1058 if (!has(AllSymbols, key) && !has(hiddenKeys, key)) result.push(key);
1059 });
1060 return result;
1061};
1062
1063var $getOwnPropertySymbols = function getOwnPropertySymbols(O) {
1064 var IS_OBJECT_PROTOTYPE = O === ObjectPrototype;
1065 var names = nativeGetOwnPropertyNames$1(IS_OBJECT_PROTOTYPE ? ObjectPrototypeSymbols : toIndexedObject(O));
1066 var result = [];
1067 $forEach(names, function (key) {
1068 if (has(AllSymbols, key) && (!IS_OBJECT_PROTOTYPE || has(ObjectPrototype, key))) {
1069 result.push(AllSymbols[key]);
1070 }
1071 });
1072 return result;
1073}; // `Symbol` constructor
1074// https://tc39.github.io/ecma262/#sec-symbol-constructor
1075
1076
1077if (!nativeSymbol) {
1078 $Symbol = function Symbol() {
1079 if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor');
1080 var description = !arguments.length || arguments[0] === undefined ? undefined : String(arguments[0]);
1081 var tag = uid(description);
1082
1083 var setter = function (value) {
1084 if (this === ObjectPrototype) setter.call(ObjectPrototypeSymbols, value);
1085 if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false;
1086 setSymbolDescriptor(this, tag, createPropertyDescriptor(1, value));
1087 };
1088
1089 if (descriptors && USE_SETTER) setSymbolDescriptor(ObjectPrototype, tag, {
1090 configurable: true,
1091 set: setter
1092 });
1093 return wrap(tag, description);
1094 };
1095
1096 redefine($Symbol[PROTOTYPE$1], 'toString', function toString() {
1097 return getInternalState(this).tag;
1098 });
1099 objectPropertyIsEnumerable.f = $propertyIsEnumerable;
1100 objectDefineProperty.f = $defineProperty;
1101 objectGetOwnPropertyDescriptor.f = $getOwnPropertyDescriptor;
1102 objectGetOwnPropertyNames.f = objectGetOwnPropertyNamesExternal.f = $getOwnPropertyNames;
1103 objectGetOwnPropertySymbols.f = $getOwnPropertySymbols;
1104
1105 if (descriptors) {
1106 // https://github.com/tc39/proposal-Symbol-description
1107 nativeDefineProperty$1($Symbol[PROTOTYPE$1], 'description', {
1108 configurable: true,
1109 get: function description() {
1110 return getInternalState(this).description;
1111 }
1112 });
1113 }
1114
1115 wrappedWellKnownSymbol.f = function (name) {
1116 return wrap(wellKnownSymbol(name), name);
1117 };
1118}
1119
1120_export({
1121 global: true,
1122 wrap: true,
1123 forced: !nativeSymbol,
1124 sham: !nativeSymbol
1125}, {
1126 Symbol: $Symbol
1127});
1128
1129$forEach(objectKeys(WellKnownSymbolsStore), function (name) {
1130 defineWellKnownSymbol(name);
1131});
1132
1133_export({
1134 target: SYMBOL,
1135 stat: true,
1136 forced: !nativeSymbol
1137}, {
1138 // `Symbol.for` method
1139 // https://tc39.github.io/ecma262/#sec-symbol.for
1140 'for': function (key) {
1141 var string = String(key);
1142 if (has(StringToSymbolRegistry, string)) return StringToSymbolRegistry[string];
1143 var symbol = $Symbol(string);
1144 StringToSymbolRegistry[string] = symbol;
1145 SymbolToStringRegistry[symbol] = string;
1146 return symbol;
1147 },
1148 // `Symbol.keyFor` method
1149 // https://tc39.github.io/ecma262/#sec-symbol.keyfor
1150 keyFor: function keyFor(sym) {
1151 if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol');
1152 if (has(SymbolToStringRegistry, sym)) return SymbolToStringRegistry[sym];
1153 },
1154 useSetter: function () {
1155 USE_SETTER = true;
1156 },
1157 useSimple: function () {
1158 USE_SETTER = false;
1159 }
1160});
1161
1162_export({
1163 target: 'Object',
1164 stat: true,
1165 forced: !nativeSymbol,
1166 sham: !descriptors
1167}, {
1168 // `Object.create` method
1169 // https://tc39.github.io/ecma262/#sec-object.create
1170 create: $create,
1171 // `Object.defineProperty` method
1172 // https://tc39.github.io/ecma262/#sec-object.defineproperty
1173 defineProperty: $defineProperty,
1174 // `Object.defineProperties` method
1175 // https://tc39.github.io/ecma262/#sec-object.defineproperties
1176 defineProperties: $defineProperties,
1177 // `Object.getOwnPropertyDescriptor` method
1178 // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptors
1179 getOwnPropertyDescriptor: $getOwnPropertyDescriptor
1180});
1181
1182_export({
1183 target: 'Object',
1184 stat: true,
1185 forced: !nativeSymbol
1186}, {
1187 // `Object.getOwnPropertyNames` method
1188 // https://tc39.github.io/ecma262/#sec-object.getownpropertynames
1189 getOwnPropertyNames: $getOwnPropertyNames,
1190 // `Object.getOwnPropertySymbols` method
1191 // https://tc39.github.io/ecma262/#sec-object.getownpropertysymbols
1192 getOwnPropertySymbols: $getOwnPropertySymbols
1193}); // Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives
1194// https://bugs.chromium.org/p/v8/issues/detail?id=3443
1195
1196
1197_export({
1198 target: 'Object',
1199 stat: true,
1200 forced: fails(function () {
1201 objectGetOwnPropertySymbols.f(1);
1202 })
1203}, {
1204 getOwnPropertySymbols: function getOwnPropertySymbols(it) {
1205 return objectGetOwnPropertySymbols.f(toObject(it));
1206 }
1207}); // `JSON.stringify` method behavior with symbols
1208// https://tc39.github.io/ecma262/#sec-json.stringify
1209
1210
1211JSON$1 && _export({
1212 target: 'JSON',
1213 stat: true,
1214 forced: !nativeSymbol || fails(function () {
1215 var symbol = $Symbol(); // MS Edge converts symbol values to JSON as {}
1216
1217 return nativeJSONStringify([symbol]) != '[null]' // WebKit converts symbol values to JSON as null
1218 || nativeJSONStringify({
1219 a: symbol
1220 }) != '{}' // V8 throws on boxed symbols
1221 || nativeJSONStringify(Object(symbol)) != '{}';
1222 })
1223}, {
1224 stringify: function stringify(it) {
1225 var args = [it];
1226 var index = 1;
1227 var replacer, $replacer;
1228
1229 while (arguments.length > index) args.push(arguments[index++]);
1230
1231 $replacer = replacer = args[1];
1232 if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined
1233
1234 if (!isArray(replacer)) replacer = function (key, value) {
1235 if (typeof $replacer == 'function') value = $replacer.call(this, key, value);
1236 if (!isSymbol(value)) return value;
1237 };
1238 args[1] = replacer;
1239 return nativeJSONStringify.apply(JSON$1, args);
1240 }
1241}); // `Symbol.prototype[@@toPrimitive]` method
1242// https://tc39.github.io/ecma262/#sec-symbol.prototype-@@toprimitive
1243
1244if (!$Symbol[PROTOTYPE$1][TO_PRIMITIVE]) {
1245 createNonEnumerableProperty($Symbol[PROTOTYPE$1], TO_PRIMITIVE, $Symbol[PROTOTYPE$1].valueOf);
1246} // `Symbol.prototype[@@toStringTag]` property
1247// https://tc39.github.io/ecma262/#sec-symbol.prototype-@@tostringtag
1248
1249
1250setToStringTag($Symbol, SYMBOL);
1251hiddenKeys[HIDDEN] = true;
1252var getOwnPropertySymbols = path.Object.getOwnPropertySymbols;
1253var getOwnPropertySymbols$1 = getOwnPropertySymbols;
1254var getOwnPropertySymbols$2 = getOwnPropertySymbols$1;
1255var iterators = {};
1256var correctPrototypeGetter = !fails(function () {
1257 function F() {
1258 /* empty */
1259 }
1260
1261 F.prototype.constructor = null;
1262 return Object.getPrototypeOf(new F()) !== F.prototype;
1263});
1264var IE_PROTO$1 = sharedKey('IE_PROTO');
1265var ObjectPrototype$1 = Object.prototype; // `Object.getPrototypeOf` method
1266// https://tc39.github.io/ecma262/#sec-object.getprototypeof
1267
1268var objectGetPrototypeOf = correctPrototypeGetter ? Object.getPrototypeOf : function (O) {
1269 O = toObject(O);
1270 if (has(O, IE_PROTO$1)) return O[IE_PROTO$1];
1271
1272 if (typeof O.constructor == 'function' && O instanceof O.constructor) {
1273 return O.constructor.prototype;
1274 }
1275
1276 return O instanceof Object ? ObjectPrototype$1 : null;
1277};
1278var ITERATOR = wellKnownSymbol('iterator');
1279var BUGGY_SAFARI_ITERATORS = false; // `%IteratorPrototype%` object
1280// https://tc39.github.io/ecma262/#sec-%iteratorprototype%-object
1281
1282var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator;
1283
1284if ([].keys) {
1285 arrayIterator = [].keys(); // Safari 8 has buggy iterators w/o `next`
1286
1287 if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true;else {
1288 PrototypeOfArrayIteratorPrototype = objectGetPrototypeOf(objectGetPrototypeOf(arrayIterator));
1289 if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype;
1290 }
1291}
1292
1293if (IteratorPrototype == undefined) IteratorPrototype = {};
1294var iteratorsCore = {
1295 IteratorPrototype: IteratorPrototype,
1296 BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS
1297};
1298var IteratorPrototype$1 = iteratorsCore.IteratorPrototype;
1299
1300var returnThis = function () {
1301 return this;
1302};
1303
1304var createIteratorConstructor = function (IteratorConstructor, NAME, next) {
1305 var TO_STRING_TAG = NAME + ' Iterator';
1306 IteratorConstructor.prototype = objectCreate(IteratorPrototype$1, {
1307 next: createPropertyDescriptor(1, next)
1308 });
1309 setToStringTag(IteratorConstructor, TO_STRING_TAG, false, true);
1310 iterators[TO_STRING_TAG] = returnThis;
1311 return IteratorConstructor;
1312};
1313
1314var aPossiblePrototype = function (it) {
1315 if (!isObject(it) && it !== null) {
1316 throw TypeError("Can't set " + String(it) + ' as a prototype');
1317 }
1318
1319 return it;
1320}; // `Object.setPrototypeOf` method
1321// https://tc39.github.io/ecma262/#sec-object.setprototypeof
1322// Works with __proto__ only. Old v8 can't work with null proto objects.
1323
1324/* eslint-disable no-proto */
1325
1326
1327var objectSetPrototypeOf = Object.setPrototypeOf || ('__proto__' in {} ? function () {
1328 var CORRECT_SETTER = false;
1329 var test = {};
1330 var setter;
1331
1332 try {
1333 setter = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').set;
1334 setter.call(test, []);
1335 CORRECT_SETTER = test instanceof Array;
1336 } catch (error) {
1337 /* empty */
1338 }
1339
1340 return function setPrototypeOf(O, proto) {
1341 anObject(O);
1342 aPossiblePrototype(proto);
1343 if (CORRECT_SETTER) setter.call(O, proto);else O.__proto__ = proto;
1344 return O;
1345 };
1346}() : undefined);
1347var IteratorPrototype$2 = iteratorsCore.IteratorPrototype;
1348var BUGGY_SAFARI_ITERATORS$1 = iteratorsCore.BUGGY_SAFARI_ITERATORS;
1349var ITERATOR$1 = wellKnownSymbol('iterator');
1350var KEYS = 'keys';
1351var VALUES = 'values';
1352var ENTRIES = 'entries';
1353
1354var returnThis$1 = function () {
1355 return this;
1356};
1357
1358var defineIterator = function (Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) {
1359 createIteratorConstructor(IteratorConstructor, NAME, next);
1360
1361 var getIterationMethod = function (KIND) {
1362 if (KIND === DEFAULT && defaultIterator) return defaultIterator;
1363 if (!BUGGY_SAFARI_ITERATORS$1 && KIND in IterablePrototype) return IterablePrototype[KIND];
1364
1365 switch (KIND) {
1366 case KEYS:
1367 return function keys() {
1368 return new IteratorConstructor(this, KIND);
1369 };
1370
1371 case VALUES:
1372 return function values() {
1373 return new IteratorConstructor(this, KIND);
1374 };
1375
1376 case ENTRIES:
1377 return function entries() {
1378 return new IteratorConstructor(this, KIND);
1379 };
1380 }
1381
1382 return function () {
1383 return new IteratorConstructor(this);
1384 };
1385 };
1386
1387 var TO_STRING_TAG = NAME + ' Iterator';
1388 var INCORRECT_VALUES_NAME = false;
1389 var IterablePrototype = Iterable.prototype;
1390 var nativeIterator = IterablePrototype[ITERATOR$1] || IterablePrototype['@@iterator'] || DEFAULT && IterablePrototype[DEFAULT];
1391 var defaultIterator = !BUGGY_SAFARI_ITERATORS$1 && nativeIterator || getIterationMethod(DEFAULT);
1392 var anyNativeIterator = NAME == 'Array' ? IterablePrototype.entries || nativeIterator : nativeIterator;
1393 var CurrentIteratorPrototype, methods, KEY; // fix native
1394
1395 if (anyNativeIterator) {
1396 CurrentIteratorPrototype = objectGetPrototypeOf(anyNativeIterator.call(new Iterable()));
1397
1398 if (IteratorPrototype$2 !== Object.prototype && CurrentIteratorPrototype.next) {
1399 // Set @@toStringTag to native iterators
1400 setToStringTag(CurrentIteratorPrototype, TO_STRING_TAG, true, true);
1401 iterators[TO_STRING_TAG] = returnThis$1;
1402 }
1403 } // fix Array#{values, @@iterator}.name in V8 / FF
1404
1405
1406 if (DEFAULT == VALUES && nativeIterator && nativeIterator.name !== VALUES) {
1407 INCORRECT_VALUES_NAME = true;
1408
1409 defaultIterator = function values() {
1410 return nativeIterator.call(this);
1411 };
1412 } // define iterator
1413
1414
1415 if (FORCED && IterablePrototype[ITERATOR$1] !== defaultIterator) {
1416 createNonEnumerableProperty(IterablePrototype, ITERATOR$1, defaultIterator);
1417 }
1418
1419 iterators[NAME] = defaultIterator; // export additional methods
1420
1421 if (DEFAULT) {
1422 methods = {
1423 values: getIterationMethod(VALUES),
1424 keys: IS_SET ? defaultIterator : getIterationMethod(KEYS),
1425 entries: getIterationMethod(ENTRIES)
1426 };
1427 if (FORCED) for (KEY in methods) {
1428 if (BUGGY_SAFARI_ITERATORS$1 || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) {
1429 redefine(IterablePrototype, KEY, methods[KEY]);
1430 }
1431 } else _export({
1432 target: NAME,
1433 proto: true,
1434 forced: BUGGY_SAFARI_ITERATORS$1 || INCORRECT_VALUES_NAME
1435 }, methods);
1436 }
1437
1438 return methods;
1439};
1440
1441var ARRAY_ITERATOR = 'Array Iterator';
1442var setInternalState$1 = internalState.set;
1443var getInternalState$1 = internalState.getterFor(ARRAY_ITERATOR); // `Array.prototype.entries` method
1444// https://tc39.github.io/ecma262/#sec-array.prototype.entries
1445// `Array.prototype.keys` method
1446// https://tc39.github.io/ecma262/#sec-array.prototype.keys
1447// `Array.prototype.values` method
1448// https://tc39.github.io/ecma262/#sec-array.prototype.values
1449// `Array.prototype[@@iterator]` method
1450// https://tc39.github.io/ecma262/#sec-array.prototype-@@iterator
1451// `CreateArrayIterator` internal method
1452// https://tc39.github.io/ecma262/#sec-createarrayiterator
1453
1454var es_array_iterator = defineIterator(Array, 'Array', function (iterated, kind) {
1455 setInternalState$1(this, {
1456 type: ARRAY_ITERATOR,
1457 target: toIndexedObject(iterated),
1458 // target
1459 index: 0,
1460 // next index
1461 kind: kind // kind
1462
1463 }); // `%ArrayIteratorPrototype%.next` method
1464 // https://tc39.github.io/ecma262/#sec-%arrayiteratorprototype%.next
1465}, function () {
1466 var state = getInternalState$1(this);
1467 var target = state.target;
1468 var kind = state.kind;
1469 var index = state.index++;
1470
1471 if (!target || index >= target.length) {
1472 state.target = undefined;
1473 return {
1474 value: undefined,
1475 done: true
1476 };
1477 }
1478
1479 if (kind == 'keys') return {
1480 value: index,
1481 done: false
1482 };
1483 if (kind == 'values') return {
1484 value: target[index],
1485 done: false
1486 };
1487 return {
1488 value: [index, target[index]],
1489 done: false
1490 };
1491}, 'values'); // argumentsList[@@iterator] is %ArrayProto_values%
1492// https://tc39.github.io/ecma262/#sec-createunmappedargumentsobject
1493// https://tc39.github.io/ecma262/#sec-createmappedargumentsobject
1494
1495iterators.Arguments = iterators.Array; // iterable DOM collections
1496// flag - `iterable` interface - 'entries', 'keys', 'values', 'forEach' methods
1497
1498var domIterables = {
1499 CSSRuleList: 0,
1500 CSSStyleDeclaration: 0,
1501 CSSValueList: 0,
1502 ClientRectList: 0,
1503 DOMRectList: 0,
1504 DOMStringList: 0,
1505 DOMTokenList: 1,
1506 DataTransferItemList: 0,
1507 FileList: 0,
1508 HTMLAllCollection: 0,
1509 HTMLCollection: 0,
1510 HTMLFormElement: 0,
1511 HTMLSelectElement: 0,
1512 MediaList: 0,
1513 MimeTypeArray: 0,
1514 NamedNodeMap: 0,
1515 NodeList: 1,
1516 PaintRequestList: 0,
1517 Plugin: 0,
1518 PluginArray: 0,
1519 SVGLengthList: 0,
1520 SVGNumberList: 0,
1521 SVGPathSegList: 0,
1522 SVGPointList: 0,
1523 SVGStringList: 0,
1524 SVGTransformList: 0,
1525 SourceBufferList: 0,
1526 StyleSheetList: 0,
1527 TextTrackCueList: 0,
1528 TextTrackList: 0,
1529 TouchList: 0
1530};
1531var TO_STRING_TAG$3 = wellKnownSymbol('toStringTag');
1532
1533for (var COLLECTION_NAME in domIterables) {
1534 var Collection = global_1[COLLECTION_NAME];
1535 var CollectionPrototype = Collection && Collection.prototype;
1536
1537 if (CollectionPrototype && !CollectionPrototype[TO_STRING_TAG$3]) {
1538 createNonEnumerableProperty(CollectionPrototype, TO_STRING_TAG$3, COLLECTION_NAME);
1539 }
1540
1541 iterators[COLLECTION_NAME] = iterators.Array;
1542} // `String.prototype.{ codePointAt, at }` methods implementation
1543
1544
1545var createMethod$2 = function (CONVERT_TO_STRING) {
1546 return function ($this, pos) {
1547 var S = String(requireObjectCoercible($this));
1548 var position = toInteger(pos);
1549 var size = S.length;
1550 var first, second;
1551 if (position < 0 || position >= size) return CONVERT_TO_STRING ? '' : undefined;
1552 first = S.charCodeAt(position);
1553 return first < 0xD800 || first > 0xDBFF || position + 1 === size || (second = S.charCodeAt(position + 1)) < 0xDC00 || second > 0xDFFF ? CONVERT_TO_STRING ? S.charAt(position) : first : CONVERT_TO_STRING ? S.slice(position, position + 2) : (first - 0xD800 << 10) + (second - 0xDC00) + 0x10000;
1554 };
1555};
1556
1557var stringMultibyte = {
1558 // `String.prototype.codePointAt` method
1559 // https://tc39.github.io/ecma262/#sec-string.prototype.codepointat
1560 codeAt: createMethod$2(false),
1561 // `String.prototype.at` method
1562 // https://github.com/mathiasbynens/String.prototype.at
1563 charAt: createMethod$2(true)
1564};
1565var charAt = stringMultibyte.charAt;
1566var STRING_ITERATOR = 'String Iterator';
1567var setInternalState$2 = internalState.set;
1568var getInternalState$2 = internalState.getterFor(STRING_ITERATOR); // `String.prototype[@@iterator]` method
1569// https://tc39.github.io/ecma262/#sec-string.prototype-@@iterator
1570
1571defineIterator(String, 'String', function (iterated) {
1572 setInternalState$2(this, {
1573 type: STRING_ITERATOR,
1574 string: String(iterated),
1575 index: 0
1576 }); // `%StringIteratorPrototype%.next` method
1577 // https://tc39.github.io/ecma262/#sec-%stringiteratorprototype%.next
1578}, function next() {
1579 var state = getInternalState$2(this);
1580 var string = state.string;
1581 var index = state.index;
1582 var point;
1583 if (index >= string.length) return {
1584 value: undefined,
1585 done: true
1586 };
1587 point = charAt(string, index);
1588 state.index += point.length;
1589 return {
1590 value: point,
1591 done: false
1592 };
1593});
1594var ITERATOR$2 = wellKnownSymbol('iterator');
1595
1596var getIteratorMethod = function (it) {
1597 if (it != undefined) return it[ITERATOR$2] || it['@@iterator'] || iterators[classof(it)];
1598};
1599
1600var getIterator = function (it) {
1601 var iteratorMethod = getIteratorMethod(it);
1602
1603 if (typeof iteratorMethod != 'function') {
1604 throw TypeError(String(it) + ' is not iterable');
1605 }
1606
1607 return anObject(iteratorMethod.call(it));
1608};
1609
1610var getIterator$1 = getIterator;
1611var getIterator$2 = getIterator$1; // `Object.create` method
1612// https://tc39.github.io/ecma262/#sec-object.create
1613
1614_export({
1615 target: 'Object',
1616 stat: true,
1617 sham: !descriptors
1618}, {
1619 create: objectCreate
1620});
1621
1622var Object$1 = path.Object;
1623
1624var create = function create(P, D) {
1625 return Object$1.create(P, D);
1626};
1627
1628var create$1 = create;
1629var create$2 = create$1;
1630var defineProperty$4 = defineProperty_1;
1631var defineProperty$5 = defineProperty$4;
1632
1633function _defineProperty(obj, key, value) {
1634 if (key in obj) {
1635 defineProperty$5(obj, key, {
1636 value: value,
1637 enumerable: true,
1638 configurable: true,
1639 writable: true
1640 });
1641 } else {
1642 obj[key] = value;
1643 }
1644
1645 return obj;
1646}
1647
1648var defineProperty$6 = _defineProperty;
1649var FAILS_ON_PRIMITIVES$1 = fails(function () {
1650 objectKeys(1);
1651}); // `Object.keys` method
1652// https://tc39.github.io/ecma262/#sec-object.keys
1653
1654_export({
1655 target: 'Object',
1656 stat: true,
1657 forced: FAILS_ON_PRIMITIVES$1
1658}, {
1659 keys: function keys(it) {
1660 return objectKeys(toObject(it));
1661 }
1662});
1663
1664var keys$1 = path.Object.keys;
1665var keys$2 = keys$1;
1666var keys$3 = keys$2; // a string of all valid unicode whitespaces
1667// eslint-disable-next-line max-len
1668
1669var whitespaces = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF';
1670var whitespace = '[' + whitespaces + ']';
1671var ltrim = RegExp('^' + whitespace + whitespace + '*');
1672var rtrim = RegExp(whitespace + whitespace + '*$'); // `String.prototype.{ trim, trimStart, trimEnd, trimLeft, trimRight }` methods implementation
1673
1674var createMethod$3 = function (TYPE) {
1675 return function ($this) {
1676 var string = String(requireObjectCoercible($this));
1677 if (TYPE & 1) string = string.replace(ltrim, '');
1678 if (TYPE & 2) string = string.replace(rtrim, '');
1679 return string;
1680 };
1681};
1682
1683var stringTrim = {
1684 // `String.prototype.{ trimLeft, trimStart }` methods
1685 // https://tc39.github.io/ecma262/#sec-string.prototype.trimstart
1686 start: createMethod$3(1),
1687 // `String.prototype.{ trimRight, trimEnd }` methods
1688 // https://tc39.github.io/ecma262/#sec-string.prototype.trimend
1689 end: createMethod$3(2),
1690 // `String.prototype.trim` method
1691 // https://tc39.github.io/ecma262/#sec-string.prototype.trim
1692 trim: createMethod$3(3)
1693};
1694var non = '\u200B\u0085\u180E'; // check that a method works with the correct list
1695// of whitespaces and has a correct name
1696
1697var forcedStringTrimMethod = function (METHOD_NAME) {
1698 return fails(function () {
1699 return !!whitespaces[METHOD_NAME]() || non[METHOD_NAME]() != non || whitespaces[METHOD_NAME].name !== METHOD_NAME;
1700 });
1701};
1702
1703var $trim = stringTrim.trim; // `String.prototype.trim` method
1704// https://tc39.github.io/ecma262/#sec-string.prototype.trim
1705
1706_export({
1707 target: 'String',
1708 proto: true,
1709 forced: forcedStringTrimMethod('trim')
1710}, {
1711 trim: function trim() {
1712 return $trim(this);
1713 }
1714});
1715
1716var entryVirtual = function (CONSTRUCTOR) {
1717 return path[CONSTRUCTOR + 'Prototype'];
1718};
1719
1720var trim = entryVirtual('String').trim;
1721var StringPrototype = String.prototype;
1722
1723var trim_1 = function (it) {
1724 var own = it.trim;
1725 return typeof it === 'string' || it === StringPrototype || it instanceof String && own === StringPrototype.trim ? trim : own;
1726};
1727
1728var trim$1 = trim_1;
1729var trim$2 = trim$1;
1730
1731var sloppyArrayMethod = function (METHOD_NAME, argument) {
1732 var method = [][METHOD_NAME];
1733 return !method || !fails(function () {
1734 // eslint-disable-next-line no-useless-call,no-throw-literal
1735 method.call(null, argument || function () {
1736 throw 1;
1737 }, 1);
1738 });
1739};
1740
1741var $forEach$1 = arrayIteration.forEach; // `Array.prototype.forEach` method implementation
1742// https://tc39.github.io/ecma262/#sec-array.prototype.foreach
1743
1744var arrayForEach = sloppyArrayMethod('forEach') ? function forEach(callbackfn
1745/* , thisArg */
1746) {
1747 return $forEach$1(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
1748} : [].forEach; // `Array.prototype.forEach` method
1749// https://tc39.github.io/ecma262/#sec-array.prototype.foreach
1750
1751_export({
1752 target: 'Array',
1753 proto: true,
1754 forced: [].forEach != arrayForEach
1755}, {
1756 forEach: arrayForEach
1757});
1758
1759var forEach = entryVirtual('Array').forEach;
1760var forEach$1 = forEach;
1761var ArrayPrototype = Array.prototype;
1762var DOMIterables = {
1763 DOMTokenList: true,
1764 NodeList: true
1765};
1766
1767var forEach_1 = function (it) {
1768 var own = it.forEach;
1769 return it === ArrayPrototype || it instanceof Array && own === ArrayPrototype.forEach // eslint-disable-next-line no-prototype-builtins
1770 || DOMIterables.hasOwnProperty(classof(it)) ? forEach$1 : own;
1771};
1772
1773var forEach$2 = forEach_1;
1774var userAgent = getBuiltIn('navigator', 'userAgent') || '';
1775var process = global_1.process;
1776var versions = process && process.versions;
1777var v8 = versions && versions.v8;
1778var match, version;
1779
1780if (v8) {
1781 match = v8.split('.');
1782 version = match[0] + match[1];
1783} else if (userAgent) {
1784 match = userAgent.match(/Edge\/(\d+)/);
1785
1786 if (!match || match[1] >= 74) {
1787 match = userAgent.match(/Chrome\/(\d+)/);
1788 if (match) version = match[1];
1789 }
1790}
1791
1792var v8Version = version && +version;
1793var SPECIES$1 = wellKnownSymbol('species');
1794
1795var arrayMethodHasSpeciesSupport = function (METHOD_NAME) {
1796 // We can't use this feature detection in V8 since it causes
1797 // deoptimization and serious performance degradation
1798 // https://github.com/zloirock/core-js/issues/677
1799 return v8Version >= 51 || !fails(function () {
1800 var array = [];
1801 var constructor = array.constructor = {};
1802
1803 constructor[SPECIES$1] = function () {
1804 return {
1805 foo: 1
1806 };
1807 };
1808
1809 return array[METHOD_NAME](Boolean).foo !== 1;
1810 });
1811};
1812
1813var $map = arrayIteration.map; // `Array.prototype.map` method
1814// https://tc39.github.io/ecma262/#sec-array.prototype.map
1815// with adding support of @@species
1816
1817_export({
1818 target: 'Array',
1819 proto: true,
1820 forced: !arrayMethodHasSpeciesSupport('map')
1821}, {
1822 map: function map(callbackfn
1823 /* , thisArg */
1824 ) {
1825 return $map(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
1826 }
1827});
1828
1829var map = entryVirtual('Array').map;
1830var ArrayPrototype$1 = Array.prototype;
1831
1832var map_1 = function (it) {
1833 var own = it.map;
1834 return it === ArrayPrototype$1 || it instanceof Array && own === ArrayPrototype$1.map ? map : own;
1835};
1836
1837var map$1 = map_1;
1838var map$2 = map$1;
1839var trim$3 = stringTrim.trim;
1840var nativeParseInt = global_1.parseInt;
1841var hex = /^[+-]?0[Xx]/;
1842var FORCED$1 = nativeParseInt(whitespaces + '08') !== 8 || nativeParseInt(whitespaces + '0x16') !== 22; // `parseInt` method
1843// https://tc39.github.io/ecma262/#sec-parseint-string-radix
1844
1845var _parseInt = FORCED$1 ? function parseInt(string, radix) {
1846 var S = trim$3(String(string));
1847 return nativeParseInt(S, radix >>> 0 || (hex.test(S) ? 16 : 10));
1848} : nativeParseInt; // `parseInt` method
1849// https://tc39.github.io/ecma262/#sec-parseint-string-radix
1850
1851
1852_export({
1853 global: true,
1854 forced: parseInt != _parseInt
1855}, {
1856 parseInt: _parseInt
1857});
1858
1859var _parseInt$1 = path.parseInt;
1860var _parseInt$2 = _parseInt$1;
1861var _parseInt$3 = _parseInt$2;
1862var propertyIsEnumerable = objectPropertyIsEnumerable.f; // `Object.{ entries, values }` methods implementation
1863
1864var createMethod$4 = function (TO_ENTRIES) {
1865 return function (it) {
1866 var O = toIndexedObject(it);
1867 var keys = objectKeys(O);
1868 var length = keys.length;
1869 var i = 0;
1870 var result = [];
1871 var key;
1872
1873 while (length > i) {
1874 key = keys[i++];
1875
1876 if (!descriptors || propertyIsEnumerable.call(O, key)) {
1877 result.push(TO_ENTRIES ? [key, O[key]] : O[key]);
1878 }
1879 }
1880
1881 return result;
1882 };
1883};
1884
1885var objectToArray = {
1886 // `Object.entries` method
1887 // https://tc39.github.io/ecma262/#sec-object.entries
1888 entries: createMethod$4(true),
1889 // `Object.values` method
1890 // https://tc39.github.io/ecma262/#sec-object.values
1891 values: createMethod$4(false)
1892};
1893var $values = objectToArray.values; // `Object.values` method
1894// https://tc39.github.io/ecma262/#sec-object.values
1895
1896_export({
1897 target: 'Object',
1898 stat: true
1899}, {
1900 values: function values(O) {
1901 return $values(O);
1902 }
1903});
1904
1905var values = path.Object.values;
1906var values$1 = values;
1907var values$2 = values$1;
1908var $filter = arrayIteration.filter; // `Array.prototype.filter` method
1909// https://tc39.github.io/ecma262/#sec-array.prototype.filter
1910// with adding support of @@species
1911
1912_export({
1913 target: 'Array',
1914 proto: true,
1915 forced: !arrayMethodHasSpeciesSupport('filter')
1916}, {
1917 filter: function filter(callbackfn
1918 /* , thisArg */
1919 ) {
1920 return $filter(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
1921 }
1922});
1923
1924var filter = entryVirtual('Array').filter;
1925var ArrayPrototype$2 = Array.prototype;
1926
1927var filter_1 = function (it) {
1928 var own = it.filter;
1929 return it === ArrayPrototype$2 || it instanceof Array && own === ArrayPrototype$2.filter ? filter : own;
1930};
1931
1932var filter$1 = filter_1;
1933var filter$2 = filter$1;
1934var IS_CONCAT_SPREADABLE = wellKnownSymbol('isConcatSpreadable');
1935var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF;
1936var MAXIMUM_ALLOWED_INDEX_EXCEEDED = 'Maximum allowed index exceeded'; // We can't use this feature detection in V8 since it causes
1937// deoptimization and serious performance degradation
1938// https://github.com/zloirock/core-js/issues/679
1939
1940var IS_CONCAT_SPREADABLE_SUPPORT = v8Version >= 51 || !fails(function () {
1941 var array = [];
1942 array[IS_CONCAT_SPREADABLE] = false;
1943 return array.concat()[0] !== array;
1944});
1945var SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('concat');
1946
1947var isConcatSpreadable = function (O) {
1948 if (!isObject(O)) return false;
1949 var spreadable = O[IS_CONCAT_SPREADABLE];
1950 return spreadable !== undefined ? !!spreadable : isArray(O);
1951};
1952
1953var FORCED$2 = !IS_CONCAT_SPREADABLE_SUPPORT || !SPECIES_SUPPORT; // `Array.prototype.concat` method
1954// https://tc39.github.io/ecma262/#sec-array.prototype.concat
1955// with adding support of @@isConcatSpreadable and @@species
1956
1957_export({
1958 target: 'Array',
1959 proto: true,
1960 forced: FORCED$2
1961}, {
1962 concat: function concat(arg) {
1963 // eslint-disable-line no-unused-vars
1964 var O = toObject(this);
1965 var A = arraySpeciesCreate(O, 0);
1966 var n = 0;
1967 var i, k, length, len, E;
1968
1969 for (i = -1, length = arguments.length; i < length; i++) {
1970 E = i === -1 ? O : arguments[i];
1971
1972 if (isConcatSpreadable(E)) {
1973 len = toLength(E.length);
1974 if (n + len > MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED);
1975
1976 for (k = 0; k < len; k++, n++) if (k in E) createProperty(A, n, E[k]);
1977 } else {
1978 if (n >= MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED);
1979 createProperty(A, n++, E);
1980 }
1981 }
1982
1983 A.length = n;
1984 return A;
1985 }
1986});
1987
1988var concat = entryVirtual('Array').concat;
1989var ArrayPrototype$3 = Array.prototype;
1990
1991var concat_1 = function (it) {
1992 var own = it.concat;
1993 return it === ArrayPrototype$3 || it instanceof Array && own === ArrayPrototype$3.concat ? concat : own;
1994};
1995
1996var concat$1 = concat_1;
1997var concat$2 = concat$1; // `Array.isArray` method
1998// https://tc39.github.io/ecma262/#sec-array.isarray
1999
2000_export({
2001 target: 'Array',
2002 stat: true
2003}, {
2004 isArray: isArray
2005});
2006
2007var isArray$1 = path.Array.isArray;
2008var isArray$2 = isArray$1;
2009var isArray$3 = isArray$2;
2010
2011function _arrayWithoutHoles(arr) {
2012 if (isArray$3(arr)) {
2013 for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
2014 arr2[i] = arr[i];
2015 }
2016
2017 return arr2;
2018 }
2019}
2020
2021var arrayWithoutHoles = _arrayWithoutHoles; // call something on iterator step with safe closing on error
2022
2023var callWithSafeIterationClosing = function (iterator, fn, value, ENTRIES) {
2024 try {
2025 return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value); // 7.4.6 IteratorClose(iterator, completion)
2026 } catch (error) {
2027 var returnMethod = iterator['return'];
2028 if (returnMethod !== undefined) anObject(returnMethod.call(iterator));
2029 throw error;
2030 }
2031};
2032
2033var ITERATOR$3 = wellKnownSymbol('iterator');
2034var ArrayPrototype$4 = Array.prototype; // check on default Array iterator
2035
2036var isArrayIteratorMethod = function (it) {
2037 return it !== undefined && (iterators.Array === it || ArrayPrototype$4[ITERATOR$3] === it);
2038}; // `Array.from` method implementation
2039// https://tc39.github.io/ecma262/#sec-array.from
2040
2041
2042var arrayFrom = function from(arrayLike
2043/* , mapfn = undefined, thisArg = undefined */
2044) {
2045 var O = toObject(arrayLike);
2046 var C = typeof this == 'function' ? this : Array;
2047 var argumentsLength = arguments.length;
2048 var mapfn = argumentsLength > 1 ? arguments[1] : undefined;
2049 var mapping = mapfn !== undefined;
2050 var index = 0;
2051 var iteratorMethod = getIteratorMethod(O);
2052 var length, result, step, iterator, next;
2053 if (mapping) mapfn = bindContext(mapfn, argumentsLength > 2 ? arguments[2] : undefined, 2); // if the target is not iterable or it's an array with the default iterator - use a simple case
2054
2055 if (iteratorMethod != undefined && !(C == Array && isArrayIteratorMethod(iteratorMethod))) {
2056 iterator = iteratorMethod.call(O);
2057 next = iterator.next;
2058 result = new C();
2059
2060 for (; !(step = next.call(iterator)).done; index++) {
2061 createProperty(result, index, mapping ? callWithSafeIterationClosing(iterator, mapfn, [step.value, index], true) : step.value);
2062 }
2063 } else {
2064 length = toLength(O.length);
2065 result = new C(length);
2066
2067 for (; length > index; index++) {
2068 createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]);
2069 }
2070 }
2071
2072 result.length = index;
2073 return result;
2074};
2075
2076var ITERATOR$4 = wellKnownSymbol('iterator');
2077var SAFE_CLOSING = false;
2078
2079try {
2080 var called = 0;
2081 var iteratorWithReturn = {
2082 next: function () {
2083 return {
2084 done: !!called++
2085 };
2086 },
2087 'return': function () {
2088 SAFE_CLOSING = true;
2089 }
2090 };
2091
2092 iteratorWithReturn[ITERATOR$4] = function () {
2093 return this;
2094 }; // eslint-disable-next-line no-throw-literal
2095
2096
2097 Array.from(iteratorWithReturn, function () {
2098 throw 2;
2099 });
2100} catch (error) {
2101 /* empty */
2102}
2103
2104var checkCorrectnessOfIteration = function (exec, SKIP_CLOSING) {
2105 if (!SKIP_CLOSING && !SAFE_CLOSING) return false;
2106 var ITERATION_SUPPORT = false;
2107
2108 try {
2109 var object = {};
2110
2111 object[ITERATOR$4] = function () {
2112 return {
2113 next: function () {
2114 return {
2115 done: ITERATION_SUPPORT = true
2116 };
2117 }
2118 };
2119 };
2120
2121 exec(object);
2122 } catch (error) {
2123 /* empty */
2124 }
2125
2126 return ITERATION_SUPPORT;
2127};
2128
2129var INCORRECT_ITERATION = !checkCorrectnessOfIteration(function (iterable) {
2130 Array.from(iterable);
2131}); // `Array.from` method
2132// https://tc39.github.io/ecma262/#sec-array.from
2133
2134_export({
2135 target: 'Array',
2136 stat: true,
2137 forced: INCORRECT_ITERATION
2138}, {
2139 from: arrayFrom
2140});
2141
2142var from_1 = path.Array.from;
2143var from_1$1 = from_1;
2144var from_1$2 = from_1$1;
2145var ITERATOR$5 = wellKnownSymbol('iterator');
2146
2147var isIterable = function (it) {
2148 var O = Object(it);
2149 return O[ITERATOR$5] !== undefined || '@@iterator' in O // eslint-disable-next-line no-prototype-builtins
2150 || iterators.hasOwnProperty(classof(O));
2151};
2152
2153var isIterable$1 = isIterable;
2154var isIterable$2 = isIterable$1;
2155
2156function _iterableToArray(iter) {
2157 if (isIterable$2(Object(iter)) || Object.prototype.toString.call(iter) === "[object Arguments]") return from_1$2(iter);
2158}
2159
2160var iterableToArray = _iterableToArray;
2161
2162function _nonIterableSpread() {
2163 throw new TypeError("Invalid attempt to spread non-iterable instance");
2164}
2165
2166var nonIterableSpread = _nonIterableSpread;
2167
2168function _toConsumableArray(arr) {
2169 return arrayWithoutHoles(arr) || iterableToArray(arr) || nonIterableSpread();
2170}
2171
2172var toConsumableArray = _toConsumableArray;
2173var SPECIES$2 = wellKnownSymbol('species');
2174var nativeSlice = [].slice;
2175var max$1 = Math.max; // `Array.prototype.slice` method
2176// https://tc39.github.io/ecma262/#sec-array.prototype.slice
2177// fallback for not array-like ES3 strings and DOM objects
2178
2179_export({
2180 target: 'Array',
2181 proto: true,
2182 forced: !arrayMethodHasSpeciesSupport('slice')
2183}, {
2184 slice: function slice(start, end) {
2185 var O = toIndexedObject(this);
2186 var length = toLength(O.length);
2187 var k = toAbsoluteIndex(start, length);
2188 var fin = toAbsoluteIndex(end === undefined ? length : end, length); // inline `ArraySpeciesCreate` for usage native `Array#slice` where it's possible
2189
2190 var Constructor, result, n;
2191
2192 if (isArray(O)) {
2193 Constructor = O.constructor; // cross-realm fallback
2194
2195 if (typeof Constructor == 'function' && (Constructor === Array || isArray(Constructor.prototype))) {
2196 Constructor = undefined;
2197 } else if (isObject(Constructor)) {
2198 Constructor = Constructor[SPECIES$2];
2199 if (Constructor === null) Constructor = undefined;
2200 }
2201
2202 if (Constructor === Array || Constructor === undefined) {
2203 return nativeSlice.call(O, k, fin);
2204 }
2205 }
2206
2207 result = new (Constructor === undefined ? Array : Constructor)(max$1(fin - k, 0));
2208
2209 for (n = 0; k < fin; k++, n++) if (k in O) createProperty(result, n, O[k]);
2210
2211 result.length = n;
2212 return result;
2213 }
2214});
2215
2216var slice = entryVirtual('Array').slice;
2217var ArrayPrototype$5 = Array.prototype;
2218
2219var slice_1 = function (it) {
2220 var own = it.slice;
2221 return it === ArrayPrototype$5 || it instanceof Array && own === ArrayPrototype$5.slice ? slice : own;
2222};
2223
2224var slice$1 = slice_1;
2225var slice$2 = slice$1;
2226var FAILS_ON_PRIMITIVES$2 = fails(function () {
2227 objectGetPrototypeOf(1);
2228}); // `Object.getPrototypeOf` method
2229// https://tc39.github.io/ecma262/#sec-object.getprototypeof
2230
2231_export({
2232 target: 'Object',
2233 stat: true,
2234 forced: FAILS_ON_PRIMITIVES$2,
2235 sham: !correctPrototypeGetter
2236}, {
2237 getPrototypeOf: function getPrototypeOf(it) {
2238 return objectGetPrototypeOf(toObject(it));
2239 }
2240});
2241
2242var getPrototypeOf = path.Object.getPrototypeOf;
2243var getPrototypeOf$1 = getPrototypeOf;
2244var getPrototypeOf$2 = getPrototypeOf$1;
2245var $indexOf = arrayIncludes.indexOf;
2246var nativeIndexOf = [].indexOf;
2247var NEGATIVE_ZERO = !!nativeIndexOf && 1 / [1].indexOf(1, -0) < 0;
2248var SLOPPY_METHOD = sloppyArrayMethod('indexOf'); // `Array.prototype.indexOf` method
2249// https://tc39.github.io/ecma262/#sec-array.prototype.indexof
2250
2251_export({
2252 target: 'Array',
2253 proto: true,
2254 forced: NEGATIVE_ZERO || SLOPPY_METHOD
2255}, {
2256 indexOf: function indexOf(searchElement
2257 /* , fromIndex = 0 */
2258 ) {
2259 return NEGATIVE_ZERO // convert -0 to +0
2260 ? nativeIndexOf.apply(this, arguments) || 0 : $indexOf(this, searchElement, arguments.length > 1 ? arguments[1] : undefined);
2261 }
2262});
2263
2264var indexOf$1 = entryVirtual('Array').indexOf;
2265var ArrayPrototype$6 = Array.prototype;
2266
2267var indexOf_1 = function (it) {
2268 var own = it.indexOf;
2269 return it === ArrayPrototype$6 || it instanceof Array && own === ArrayPrototype$6.indexOf ? indexOf$1 : own;
2270};
2271
2272var indexOf$2 = indexOf_1;
2273var indexOf$3 = indexOf$2;
2274var isArray$4 = isArray$1;
2275var isArray$5 = isArray$4;
2276var nativeAssign = Object.assign; // `Object.assign` method
2277// https://tc39.github.io/ecma262/#sec-object.assign
2278// should work with symbols and should have deterministic property order (V8 bug)
2279
2280var objectAssign = !nativeAssign || fails(function () {
2281 var A = {};
2282 var B = {}; // eslint-disable-next-line no-undef
2283
2284 var symbol = Symbol();
2285 var alphabet = 'abcdefghijklmnopqrst';
2286 A[symbol] = 7;
2287 alphabet.split('').forEach(function (chr) {
2288 B[chr] = chr;
2289 });
2290 return nativeAssign({}, A)[symbol] != 7 || objectKeys(nativeAssign({}, B)).join('') != alphabet;
2291}) ? function assign(target, source) {
2292 // eslint-disable-line no-unused-vars
2293 var T = toObject(target);
2294 var argumentsLength = arguments.length;
2295 var index = 1;
2296 var getOwnPropertySymbols = objectGetOwnPropertySymbols.f;
2297 var propertyIsEnumerable = objectPropertyIsEnumerable.f;
2298
2299 while (argumentsLength > index) {
2300 var S = indexedObject(arguments[index++]);
2301 var keys = getOwnPropertySymbols ? objectKeys(S).concat(getOwnPropertySymbols(S)) : objectKeys(S);
2302 var length = keys.length;
2303 var j = 0;
2304 var key;
2305
2306 while (length > j) {
2307 key = keys[j++];
2308 if (!descriptors || propertyIsEnumerable.call(S, key)) T[key] = S[key];
2309 }
2310 }
2311
2312 return T;
2313} : nativeAssign; // `Object.assign` method
2314// https://tc39.github.io/ecma262/#sec-object.assign
2315
2316_export({
2317 target: 'Object',
2318 stat: true,
2319 forced: Object.assign !== objectAssign
2320}, {
2321 assign: objectAssign
2322});
2323
2324var assign = path.Object.assign;
2325var assign$1 = assign;
2326var assign$2 = assign$1; // `Symbol.iterator` well-known symbol
2327// https://tc39.github.io/ecma262/#sec-symbol.iterator
2328
2329defineWellKnownSymbol('iterator');
2330var iterator = wrappedWellKnownSymbol.f('iterator');
2331var iterator$1 = iterator;
2332var iterator$2 = iterator$1; // `Symbol.asyncIterator` well-known symbol
2333// https://tc39.github.io/ecma262/#sec-symbol.asynciterator
2334
2335defineWellKnownSymbol('asyncIterator'); // `Symbol.hasInstance` well-known symbol
2336// https://tc39.github.io/ecma262/#sec-symbol.hasinstance
2337
2338defineWellKnownSymbol('hasInstance'); // `Symbol.isConcatSpreadable` well-known symbol
2339// https://tc39.github.io/ecma262/#sec-symbol.isconcatspreadable
2340
2341defineWellKnownSymbol('isConcatSpreadable'); // `Symbol.match` well-known symbol
2342// https://tc39.github.io/ecma262/#sec-symbol.match
2343
2344defineWellKnownSymbol('match'); // `Symbol.matchAll` well-known symbol
2345
2346defineWellKnownSymbol('matchAll'); // `Symbol.replace` well-known symbol
2347// https://tc39.github.io/ecma262/#sec-symbol.replace
2348
2349defineWellKnownSymbol('replace'); // `Symbol.search` well-known symbol
2350// https://tc39.github.io/ecma262/#sec-symbol.search
2351
2352defineWellKnownSymbol('search'); // `Symbol.species` well-known symbol
2353// https://tc39.github.io/ecma262/#sec-symbol.species
2354
2355defineWellKnownSymbol('species'); // `Symbol.split` well-known symbol
2356// https://tc39.github.io/ecma262/#sec-symbol.split
2357
2358defineWellKnownSymbol('split'); // `Symbol.toPrimitive` well-known symbol
2359// https://tc39.github.io/ecma262/#sec-symbol.toprimitive
2360
2361defineWellKnownSymbol('toPrimitive'); // `Symbol.toStringTag` well-known symbol
2362// https://tc39.github.io/ecma262/#sec-symbol.tostringtag
2363
2364defineWellKnownSymbol('toStringTag'); // `Symbol.unscopables` well-known symbol
2365// https://tc39.github.io/ecma262/#sec-symbol.unscopables
2366
2367defineWellKnownSymbol('unscopables'); // Math[@@toStringTag] property
2368// https://tc39.github.io/ecma262/#sec-math-@@tostringtag
2369
2370setToStringTag(Math, 'Math', true); // JSON[@@toStringTag] property
2371// https://tc39.github.io/ecma262/#sec-json-@@tostringtag
2372
2373setToStringTag(global_1.JSON, 'JSON', true);
2374var symbol = path.Symbol; // `Symbol.asyncDispose` well-known symbol
2375// https://github.com/tc39/proposal-using-statement
2376
2377defineWellKnownSymbol('asyncDispose'); // `Symbol.dispose` well-known symbol
2378// https://github.com/tc39/proposal-using-statement
2379
2380defineWellKnownSymbol('dispose'); // `Symbol.observable` well-known symbol
2381// https://github.com/tc39/proposal-observable
2382
2383defineWellKnownSymbol('observable'); // `Symbol.patternMatch` well-known symbol
2384// https://github.com/tc39/proposal-pattern-matching
2385
2386defineWellKnownSymbol('patternMatch'); // TODO: remove from `core-js@4`
2387
2388defineWellKnownSymbol('replaceAll');
2389var symbol$1 = symbol;
2390var symbol$2 = symbol$1;
2391
2392var _typeof_1 = createCommonjsModule(function (module) {
2393 function _typeof2(obj) {
2394 if (typeof symbol$2 === "function" && typeof iterator$2 === "symbol") {
2395 _typeof2 = function _typeof2(obj) {
2396 return typeof obj;
2397 };
2398 } else {
2399 _typeof2 = function _typeof2(obj) {
2400 return obj && typeof symbol$2 === "function" && obj.constructor === symbol$2 && obj !== symbol$2.prototype ? "symbol" : typeof obj;
2401 };
2402 }
2403
2404 return _typeof2(obj);
2405 }
2406
2407 function _typeof(obj) {
2408 if (typeof symbol$2 === "function" && _typeof2(iterator$2) === "symbol") {
2409 module.exports = _typeof = function _typeof(obj) {
2410 return _typeof2(obj);
2411 };
2412 } else {
2413 module.exports = _typeof = function _typeof(obj) {
2414 return obj && typeof symbol$2 === "function" && obj.constructor === symbol$2 && obj !== symbol$2.prototype ? "symbol" : _typeof2(obj);
2415 };
2416 }
2417
2418 return _typeof(obj);
2419 }
2420
2421 module.exports = _typeof;
2422});
2423
2424var trim$4 = stringTrim.trim;
2425var nativeParseFloat = global_1.parseFloat;
2426var FORCED$3 = 1 / nativeParseFloat(whitespaces + '-0') !== -Infinity; // `parseFloat` method
2427// https://tc39.github.io/ecma262/#sec-parsefloat-string
2428
2429var _parseFloat = FORCED$3 ? function parseFloat(string) {
2430 var trimmedString = trim$4(String(string));
2431 var result = nativeParseFloat(trimmedString);
2432 return result === 0 && trimmedString.charAt(0) == '-' ? -0 : result;
2433} : nativeParseFloat; // `parseFloat` method
2434// https://tc39.github.io/ecma262/#sec-parsefloat-string
2435
2436
2437_export({
2438 global: true,
2439 forced: parseFloat != _parseFloat
2440}, {
2441 parseFloat: _parseFloat
2442});
2443
2444var _parseFloat$1 = path.parseFloat;
2445var _parseFloat$2 = _parseFloat$1;
2446var _parseFloat$3 = _parseFloat$2; // `Date.now` method
2447// https://tc39.github.io/ecma262/#sec-date.now
2448
2449_export({
2450 target: 'Date',
2451 stat: true
2452}, {
2453 now: function now() {
2454 return new Date().getTime();
2455 }
2456});
2457
2458var now = path.Date.now;
2459var now$1 = now;
2460var now$2 = now$1;
2461var nativeSort = [].sort;
2462var test$1 = [1, 2, 3]; // IE8-
2463
2464var FAILS_ON_UNDEFINED = fails(function () {
2465 test$1.sort(undefined);
2466}); // V8 bug
2467
2468var FAILS_ON_NULL = fails(function () {
2469 test$1.sort(null);
2470}); // Old WebKit
2471
2472var SLOPPY_METHOD$1 = sloppyArrayMethod('sort');
2473var FORCED$4 = FAILS_ON_UNDEFINED || !FAILS_ON_NULL || SLOPPY_METHOD$1; // `Array.prototype.sort` method
2474// https://tc39.github.io/ecma262/#sec-array.prototype.sort
2475
2476_export({
2477 target: 'Array',
2478 proto: true,
2479 forced: FORCED$4
2480}, {
2481 sort: function sort(comparefn) {
2482 return comparefn === undefined ? nativeSort.call(toObject(this)) : nativeSort.call(toObject(this), aFunction(comparefn));
2483 }
2484});
2485
2486var sort = entryVirtual('Array').sort;
2487var ArrayPrototype$7 = Array.prototype;
2488
2489var sort_1 = function (it) {
2490 var own = it.sort;
2491 return it === ArrayPrototype$7 || it instanceof Array && own === ArrayPrototype$7.sort ? sort : own;
2492};
2493
2494var sort$1 = sort_1;
2495var sort$2 = sort$1;
2496var nativeIsFrozen = Object.isFrozen;
2497var FAILS_ON_PRIMITIVES$3 = fails(function () {
2498 nativeIsFrozen(1);
2499}); // `Object.isFrozen` method
2500// https://tc39.github.io/ecma262/#sec-object.isfrozen
2501
2502_export({
2503 target: 'Object',
2504 stat: true,
2505 forced: FAILS_ON_PRIMITIVES$3
2506}, {
2507 isFrozen: function isFrozen(it) {
2508 return isObject(it) ? nativeIsFrozen ? nativeIsFrozen(it) : false : true;
2509 }
2510});
2511
2512var isFrozen = path.Object.isFrozen;
2513var isFrozen$1 = isFrozen;
2514var isFrozen$2 = isFrozen$1;
2515var $some = arrayIteration.some; // `Array.prototype.some` method
2516// https://tc39.github.io/ecma262/#sec-array.prototype.some
2517
2518_export({
2519 target: 'Array',
2520 proto: true,
2521 forced: sloppyArrayMethod('some')
2522}, {
2523 some: function some(callbackfn
2524 /* , thisArg */
2525 ) {
2526 return $some(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
2527 }
2528});
2529
2530var some = entryVirtual('Array').some;
2531var ArrayPrototype$8 = Array.prototype;
2532
2533var some_1 = function (it) {
2534 var own = it.some;
2535 return it === ArrayPrototype$8 || it instanceof Array && own === ArrayPrototype$8.some ? some : own;
2536};
2537
2538var some$1 = some_1;
2539var some$2 = some$1;
2540var nativeGetOwnPropertyNames$2 = objectGetOwnPropertyNamesExternal.f;
2541var FAILS_ON_PRIMITIVES$4 = fails(function () {
2542 return !Object.getOwnPropertyNames(1);
2543}); // `Object.getOwnPropertyNames` method
2544// https://tc39.github.io/ecma262/#sec-object.getownpropertynames
2545
2546_export({
2547 target: 'Object',
2548 stat: true,
2549 forced: FAILS_ON_PRIMITIVES$4
2550}, {
2551 getOwnPropertyNames: nativeGetOwnPropertyNames$2
2552});
2553
2554var Object$2 = path.Object;
2555
2556var getOwnPropertyNames = function getOwnPropertyNames(it) {
2557 return Object$2.getOwnPropertyNames(it);
2558};
2559
2560var getOwnPropertyNames$1 = getOwnPropertyNames;
2561var getOwnPropertyNames$2 = getOwnPropertyNames$1;
2562var moment = createCommonjsModule(function (module, exports) {
2563 (function (global, factory) {
2564 module.exports = factory();
2565 })(commonjsGlobal, function () {
2566 var hookCallback;
2567
2568 function hooks() {
2569 return hookCallback.apply(null, arguments);
2570 } // This is done to register the method called with moment()
2571 // without creating circular dependencies.
2572
2573
2574 function setHookCallback(callback) {
2575 hookCallback = callback;
2576 }
2577
2578 function isArray(input) {
2579 return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]';
2580 }
2581
2582 function isObject(input) {
2583 // IE8 will treat undefined and null as object if it wasn't for
2584 // input != null
2585 return input != null && Object.prototype.toString.call(input) === '[object Object]';
2586 }
2587
2588 function isObjectEmpty(obj) {
2589 if (getOwnPropertyNames$2) {
2590 return getOwnPropertyNames$2(obj).length === 0;
2591 } else {
2592 var k;
2593
2594 for (k in obj) {
2595 if (obj.hasOwnProperty(k)) {
2596 return false;
2597 }
2598 }
2599
2600 return true;
2601 }
2602 }
2603
2604 function isUndefined(input) {
2605 return input === void 0;
2606 }
2607
2608 function isNumber(input) {
2609 return typeof input === 'number' || Object.prototype.toString.call(input) === '[object Number]';
2610 }
2611
2612 function isDate(input) {
2613 return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
2614 }
2615
2616 function map(arr, fn) {
2617 var res = [],
2618 i;
2619
2620 for (i = 0; i < arr.length; ++i) {
2621 res.push(fn(arr[i], i));
2622 }
2623
2624 return res;
2625 }
2626
2627 function hasOwnProp(a, b) {
2628 return Object.prototype.hasOwnProperty.call(a, b);
2629 }
2630
2631 function extend(a, b) {
2632 for (var i in b) {
2633 if (hasOwnProp(b, i)) {
2634 a[i] = b[i];
2635 }
2636 }
2637
2638 if (hasOwnProp(b, 'toString')) {
2639 a.toString = b.toString;
2640 }
2641
2642 if (hasOwnProp(b, 'valueOf')) {
2643 a.valueOf = b.valueOf;
2644 }
2645
2646 return a;
2647 }
2648
2649 function createUTC(input, format, locale, strict) {
2650 return createLocalOrUTC(input, format, locale, strict, true).utc();
2651 }
2652
2653 function defaultParsingFlags() {
2654 // We need to deep clone this object.
2655 return {
2656 empty: false,
2657 unusedTokens: [],
2658 unusedInput: [],
2659 overflow: -2,
2660 charsLeftOver: 0,
2661 nullInput: false,
2662 invalidMonth: null,
2663 invalidFormat: false,
2664 userInvalidated: false,
2665 iso: false,
2666 parsedDateParts: [],
2667 meridiem: null,
2668 rfc2822: false,
2669 weekdayMismatch: false
2670 };
2671 }
2672
2673 function getParsingFlags(m) {
2674 if (m._pf == null) {
2675 m._pf = defaultParsingFlags();
2676 }
2677
2678 return m._pf;
2679 }
2680
2681 var some;
2682
2683 if (some$2(Array.prototype)) {
2684 some = some$2(Array.prototype);
2685 } else {
2686 some = function some(fun) {
2687 var t = Object(this);
2688 var len = t.length >>> 0;
2689
2690 for (var i = 0; i < len; i++) {
2691 if (i in t && fun.call(this, t[i], i, t)) {
2692 return true;
2693 }
2694 }
2695
2696 return false;
2697 };
2698 }
2699
2700 function isValid(m) {
2701 if (m._isValid == null) {
2702 var flags = getParsingFlags(m);
2703 var parsedParts = some.call(flags.parsedDateParts, function (i) {
2704 return i != null;
2705 });
2706 var isNowValid = !isNaN(m._d.getTime()) && flags.overflow < 0 && !flags.empty && !flags.invalidMonth && !flags.invalidWeekday && !flags.weekdayMismatch && !flags.nullInput && !flags.invalidFormat && !flags.userInvalidated && (!flags.meridiem || flags.meridiem && parsedParts);
2707
2708 if (m._strict) {
2709 isNowValid = isNowValid && flags.charsLeftOver === 0 && flags.unusedTokens.length === 0 && flags.bigHour === undefined;
2710 }
2711
2712 if (isFrozen$2 == null || !isFrozen$2(m)) {
2713 m._isValid = isNowValid;
2714 } else {
2715 return isNowValid;
2716 }
2717 }
2718
2719 return m._isValid;
2720 }
2721
2722 function createInvalid(flags) {
2723 var m = createUTC(NaN);
2724
2725 if (flags != null) {
2726 extend(getParsingFlags(m), flags);
2727 } else {
2728 getParsingFlags(m).userInvalidated = true;
2729 }
2730
2731 return m;
2732 } // Plugins that add properties should also add the key here (null value),
2733 // so we can properly clone ourselves.
2734
2735
2736 var momentProperties = hooks.momentProperties = [];
2737
2738 function copyConfig(to, from) {
2739 var i, prop, val;
2740
2741 if (!isUndefined(from._isAMomentObject)) {
2742 to._isAMomentObject = from._isAMomentObject;
2743 }
2744
2745 if (!isUndefined(from._i)) {
2746 to._i = from._i;
2747 }
2748
2749 if (!isUndefined(from._f)) {
2750 to._f = from._f;
2751 }
2752
2753 if (!isUndefined(from._l)) {
2754 to._l = from._l;
2755 }
2756
2757 if (!isUndefined(from._strict)) {
2758 to._strict = from._strict;
2759 }
2760
2761 if (!isUndefined(from._tzm)) {
2762 to._tzm = from._tzm;
2763 }
2764
2765 if (!isUndefined(from._isUTC)) {
2766 to._isUTC = from._isUTC;
2767 }
2768
2769 if (!isUndefined(from._offset)) {
2770 to._offset = from._offset;
2771 }
2772
2773 if (!isUndefined(from._pf)) {
2774 to._pf = getParsingFlags(from);
2775 }
2776
2777 if (!isUndefined(from._locale)) {
2778 to._locale = from._locale;
2779 }
2780
2781 if (momentProperties.length > 0) {
2782 for (i = 0; i < momentProperties.length; i++) {
2783 prop = momentProperties[i];
2784 val = from[prop];
2785
2786 if (!isUndefined(val)) {
2787 to[prop] = val;
2788 }
2789 }
2790 }
2791
2792 return to;
2793 }
2794
2795 var updateInProgress = false; // Moment prototype object
2796
2797 function Moment(config) {
2798 copyConfig(this, config);
2799 this._d = new Date(config._d != null ? config._d.getTime() : NaN);
2800
2801 if (!this.isValid()) {
2802 this._d = new Date(NaN);
2803 } // Prevent infinite loop in case updateOffset creates new moment
2804 // objects.
2805
2806
2807 if (updateInProgress === false) {
2808 updateInProgress = true;
2809 hooks.updateOffset(this);
2810 updateInProgress = false;
2811 }
2812 }
2813
2814 function isMoment(obj) {
2815 return obj instanceof Moment || obj != null && obj._isAMomentObject != null;
2816 }
2817
2818 function absFloor(number) {
2819 if (number < 0) {
2820 // -0 -> 0
2821 return Math.ceil(number) || 0;
2822 } else {
2823 return Math.floor(number);
2824 }
2825 }
2826
2827 function toInt(argumentForCoercion) {
2828 var coercedNumber = +argumentForCoercion,
2829 value = 0;
2830
2831 if (coercedNumber !== 0 && isFinite(coercedNumber)) {
2832 value = absFloor(coercedNumber);
2833 }
2834
2835 return value;
2836 } // compare two arrays, return the number of differences
2837
2838
2839 function compareArrays(array1, array2, dontConvert) {
2840 var len = Math.min(array1.length, array2.length),
2841 lengthDiff = Math.abs(array1.length - array2.length),
2842 diffs = 0,
2843 i;
2844
2845 for (i = 0; i < len; i++) {
2846 if (dontConvert && array1[i] !== array2[i] || !dontConvert && toInt(array1[i]) !== toInt(array2[i])) {
2847 diffs++;
2848 }
2849 }
2850
2851 return diffs + lengthDiff;
2852 }
2853
2854 function warn(msg) {
2855 if (hooks.suppressDeprecationWarnings === false && typeof console !== 'undefined' && console.warn) {
2856 console.warn('Deprecation warning: ' + msg);
2857 }
2858 }
2859
2860 function deprecate(msg, fn) {
2861 var firstTime = true;
2862 return extend(function () {
2863 if (hooks.deprecationHandler != null) {
2864 hooks.deprecationHandler(null, msg);
2865 }
2866
2867 if (firstTime) {
2868 var args = [];
2869 var arg;
2870
2871 for (var i = 0; i < arguments.length; i++) {
2872 arg = '';
2873
2874 if (_typeof_1(arguments[i]) === 'object') {
2875 arg += '\n[' + i + '] ';
2876
2877 for (var key in arguments[0]) {
2878 arg += key + ': ' + arguments[0][key] + ', ';
2879 }
2880
2881 arg = slice$2(arg).call(arg, 0, -2); // Remove trailing comma and space
2882 } else {
2883 arg = arguments[i];
2884 }
2885
2886 args.push(arg);
2887 }
2888
2889 warn(msg + '\nArguments: ' + slice$2(Array.prototype).call(args).join('') + '\n' + new Error().stack);
2890 firstTime = false;
2891 }
2892
2893 return fn.apply(this, arguments);
2894 }, fn);
2895 }
2896
2897 var deprecations = {};
2898
2899 function deprecateSimple(name, msg) {
2900 if (hooks.deprecationHandler != null) {
2901 hooks.deprecationHandler(name, msg);
2902 }
2903
2904 if (!deprecations[name]) {
2905 warn(msg);
2906 deprecations[name] = true;
2907 }
2908 }
2909
2910 hooks.suppressDeprecationWarnings = false;
2911 hooks.deprecationHandler = null;
2912
2913 function isFunction(input) {
2914 return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
2915 }
2916
2917 function set(config) {
2918 var prop, i;
2919
2920 for (i in config) {
2921 prop = config[i];
2922
2923 if (isFunction(prop)) {
2924 this[i] = prop;
2925 } else {
2926 this['_' + i] = prop;
2927 }
2928 }
2929
2930 this._config = config; // Lenient ordinal parsing accepts just a number in addition to
2931 // number + (possibly) stuff coming from _dayOfMonthOrdinalParse.
2932 // TODO: Remove "ordinalParse" fallback in next major release.
2933
2934 this._dayOfMonthOrdinalParseLenient = new RegExp((this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + '|' + /\d{1,2}/.source);
2935 }
2936
2937 function mergeConfigs(parentConfig, childConfig) {
2938 var res = extend({}, parentConfig),
2939 prop;
2940
2941 for (prop in childConfig) {
2942 if (hasOwnProp(childConfig, prop)) {
2943 if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
2944 res[prop] = {};
2945 extend(res[prop], parentConfig[prop]);
2946 extend(res[prop], childConfig[prop]);
2947 } else if (childConfig[prop] != null) {
2948 res[prop] = childConfig[prop];
2949 } else {
2950 delete res[prop];
2951 }
2952 }
2953 }
2954
2955 for (prop in parentConfig) {
2956 if (hasOwnProp(parentConfig, prop) && !hasOwnProp(childConfig, prop) && isObject(parentConfig[prop])) {
2957 // make sure changes to properties don't modify parent config
2958 res[prop] = extend({}, res[prop]);
2959 }
2960 }
2961
2962 return res;
2963 }
2964
2965 function Locale(config) {
2966 if (config != null) {
2967 this.set(config);
2968 }
2969 }
2970
2971 var keys;
2972
2973 if (keys$3) {
2974 keys = keys$3;
2975 } else {
2976 keys = function keys(obj) {
2977 var i,
2978 res = [];
2979
2980 for (i in obj) {
2981 if (hasOwnProp(obj, i)) {
2982 res.push(i);
2983 }
2984 }
2985
2986 return res;
2987 };
2988 }
2989
2990 var defaultCalendar = {
2991 sameDay: '[Today at] LT',
2992 nextDay: '[Tomorrow at] LT',
2993 nextWeek: 'dddd [at] LT',
2994 lastDay: '[Yesterday at] LT',
2995 lastWeek: '[Last] dddd [at] LT',
2996 sameElse: 'L'
2997 };
2998
2999 function calendar(key, mom, now) {
3000 var output = this._calendar[key] || this._calendar['sameElse'];
3001 return isFunction(output) ? output.call(mom, now) : output;
3002 }
3003
3004 var defaultLongDateFormat = {
3005 LTS: 'h:mm:ss A',
3006 LT: 'h:mm A',
3007 L: 'MM/DD/YYYY',
3008 LL: 'MMMM D, YYYY',
3009 LLL: 'MMMM D, YYYY h:mm A',
3010 LLLL: 'dddd, MMMM D, YYYY h:mm A'
3011 };
3012
3013 function longDateFormat(key) {
3014 var format = this._longDateFormat[key],
3015 formatUpper = this._longDateFormat[key.toUpperCase()];
3016
3017 if (format || !formatUpper) {
3018 return format;
3019 }
3020
3021 this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) {
3022 return slice$2(val).call(val, 1);
3023 });
3024 return this._longDateFormat[key];
3025 }
3026
3027 var defaultInvalidDate = 'Invalid date';
3028
3029 function invalidDate() {
3030 return this._invalidDate;
3031 }
3032
3033 var defaultOrdinal = '%d';
3034 var defaultDayOfMonthOrdinalParse = /\d{1,2}/;
3035
3036 function ordinal(number) {
3037 return this._ordinal.replace('%d', number);
3038 }
3039
3040 var defaultRelativeTime = {
3041 future: 'in %s',
3042 past: '%s ago',
3043 s: 'a few seconds',
3044 ss: '%d seconds',
3045 m: 'a minute',
3046 mm: '%d minutes',
3047 h: 'an hour',
3048 hh: '%d hours',
3049 d: 'a day',
3050 dd: '%d days',
3051 M: 'a month',
3052 MM: '%d months',
3053 y: 'a year',
3054 yy: '%d years'
3055 };
3056
3057 function relativeTime(number, withoutSuffix, string, isFuture) {
3058 var output = this._relativeTime[string];
3059 return isFunction(output) ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number);
3060 }
3061
3062 function pastFuture(diff, output) {
3063 var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
3064 return isFunction(format) ? format(output) : format.replace(/%s/i, output);
3065 }
3066
3067 var aliases = {};
3068
3069 function addUnitAlias(unit, shorthand) {
3070 var lowerCase = unit.toLowerCase();
3071 aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
3072 }
3073
3074 function normalizeUnits(units) {
3075 return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined;
3076 }
3077
3078 function normalizeObjectUnits(inputObject) {
3079 var normalizedInput = {},
3080 normalizedProp,
3081 prop;
3082
3083 for (prop in inputObject) {
3084 if (hasOwnProp(inputObject, prop)) {
3085 normalizedProp = normalizeUnits(prop);
3086
3087 if (normalizedProp) {
3088 normalizedInput[normalizedProp] = inputObject[prop];
3089 }
3090 }
3091 }
3092
3093 return normalizedInput;
3094 }
3095
3096 var priorities = {};
3097
3098 function addUnitPriority(unit, priority) {
3099 priorities[unit] = priority;
3100 }
3101
3102 function getPrioritizedUnits(unitsObj) {
3103 var units = [];
3104
3105 for (var u in unitsObj) {
3106 units.push({
3107 unit: u,
3108 priority: priorities[u]
3109 });
3110 }
3111
3112 sort$2(units).call(units, function (a, b) {
3113 return a.priority - b.priority;
3114 });
3115 return units;
3116 }
3117
3118 function zeroFill(number, targetLength, forceSign) {
3119 var absNumber = '' + Math.abs(number),
3120 zerosToFill = targetLength - absNumber.length,
3121 sign = number >= 0;
3122 return (sign ? forceSign ? '+' : '' : '-') + Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber;
3123 }
3124
3125 var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g;
3126 var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;
3127 var formatFunctions = {};
3128 var formatTokenFunctions = {}; // token: 'M'
3129 // padded: ['MM', 2]
3130 // ordinal: 'Mo'
3131 // callback: function () { this.month() + 1 }
3132
3133 function addFormatToken(token, padded, ordinal, callback) {
3134 var func = callback;
3135
3136 if (typeof callback === 'string') {
3137 func = function func() {
3138 return this[callback]();
3139 };
3140 }
3141
3142 if (token) {
3143 formatTokenFunctions[token] = func;
3144 }
3145
3146 if (padded) {
3147 formatTokenFunctions[padded[0]] = function () {
3148 return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
3149 };
3150 }
3151
3152 if (ordinal) {
3153 formatTokenFunctions[ordinal] = function () {
3154 return this.localeData().ordinal(func.apply(this, arguments), token);
3155 };
3156 }
3157 }
3158
3159 function removeFormattingTokens(input) {
3160 if (input.match(/\[[\s\S]/)) {
3161 return input.replace(/^\[|\]$/g, '');
3162 }
3163
3164 return input.replace(/\\/g, '');
3165 }
3166
3167 function makeFormatFunction(format) {
3168 var array = format.match(formattingTokens),
3169 i,
3170 length;
3171
3172 for (i = 0, length = array.length; i < length; i++) {
3173 if (formatTokenFunctions[array[i]]) {
3174 array[i] = formatTokenFunctions[array[i]];
3175 } else {
3176 array[i] = removeFormattingTokens(array[i]);
3177 }
3178 }
3179
3180 return function (mom) {
3181 var output = '',
3182 i;
3183
3184 for (i = 0; i < length; i++) {
3185 output += isFunction(array[i]) ? array[i].call(mom, format) : array[i];
3186 }
3187
3188 return output;
3189 };
3190 } // format date using native date object
3191
3192
3193 function formatMoment(m, format) {
3194 if (!m.isValid()) {
3195 return m.localeData().invalidDate();
3196 }
3197
3198 format = expandFormat(format, m.localeData());
3199 formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format);
3200 return formatFunctions[format](m);
3201 }
3202
3203 function expandFormat(format, locale) {
3204 var i = 5;
3205
3206 function replaceLongDateFormatTokens(input) {
3207 return locale.longDateFormat(input) || input;
3208 }
3209
3210 localFormattingTokens.lastIndex = 0;
3211
3212 while (i >= 0 && localFormattingTokens.test(format)) {
3213 format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
3214 localFormattingTokens.lastIndex = 0;
3215 i -= 1;
3216 }
3217
3218 return format;
3219 }
3220
3221 var match1 = /\d/; // 0 - 9
3222
3223 var match2 = /\d\d/; // 00 - 99
3224
3225 var match3 = /\d{3}/; // 000 - 999
3226
3227 var match4 = /\d{4}/; // 0000 - 9999
3228
3229 var match6 = /[+-]?\d{6}/; // -999999 - 999999
3230
3231 var match1to2 = /\d\d?/; // 0 - 99
3232
3233 var match3to4 = /\d\d\d\d?/; // 999 - 9999
3234
3235 var match5to6 = /\d\d\d\d\d\d?/; // 99999 - 999999
3236
3237 var match1to3 = /\d{1,3}/; // 0 - 999
3238
3239 var match1to4 = /\d{1,4}/; // 0 - 9999
3240
3241 var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999
3242
3243 var matchUnsigned = /\d+/; // 0 - inf
3244
3245 var matchSigned = /[+-]?\d+/; // -inf - inf
3246
3247 var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z
3248
3249 var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z
3250
3251 var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123
3252 // any word (or two) characters or numbers including two/three word month in arabic.
3253 // includes scottish gaelic two word and hyphenated months
3254
3255 var matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i;
3256 var regexes = {};
3257
3258 function addRegexToken(token, regex, strictRegex) {
3259 regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) {
3260 return isStrict && strictRegex ? strictRegex : regex;
3261 };
3262 }
3263
3264 function getParseRegexForToken(token, config) {
3265 if (!hasOwnProp(regexes, token)) {
3266 return new RegExp(unescapeFormat(token));
3267 }
3268
3269 return regexes[token](config._strict, config._locale);
3270 } // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
3271
3272
3273 function unescapeFormat(s) {
3274 return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
3275 return p1 || p2 || p3 || p4;
3276 }));
3277 }
3278
3279 function regexEscape(s) {
3280 return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
3281 }
3282
3283 var tokens = {};
3284
3285 function addParseToken(token, callback) {
3286 var i,
3287 func = callback;
3288
3289 if (typeof token === 'string') {
3290 token = [token];
3291 }
3292
3293 if (isNumber(callback)) {
3294 func = function func(input, array) {
3295 array[callback] = toInt(input);
3296 };
3297 }
3298
3299 for (i = 0; i < token.length; i++) {
3300 tokens[token[i]] = func;
3301 }
3302 }
3303
3304 function addWeekParseToken(token, callback) {
3305 addParseToken(token, function (input, array, config, token) {
3306 config._w = config._w || {};
3307 callback(input, config._w, config, token);
3308 });
3309 }
3310
3311 function addTimeToArrayFromToken(token, input, config) {
3312 if (input != null && hasOwnProp(tokens, token)) {
3313 tokens[token](input, config._a, config, token);
3314 }
3315 }
3316
3317 var YEAR = 0;
3318 var MONTH = 1;
3319 var DATE = 2;
3320 var HOUR = 3;
3321 var MINUTE = 4;
3322 var SECOND = 5;
3323 var MILLISECOND = 6;
3324 var WEEK = 7;
3325 var WEEKDAY = 8; // FORMATTING
3326
3327 addFormatToken('Y', 0, 0, function () {
3328 var y = this.year();
3329 return y <= 9999 ? '' + y : '+' + y;
3330 });
3331 addFormatToken(0, ['YY', 2], 0, function () {
3332 return this.year() % 100;
3333 });
3334 addFormatToken(0, ['YYYY', 4], 0, 'year');
3335 addFormatToken(0, ['YYYYY', 5], 0, 'year');
3336 addFormatToken(0, ['YYYYYY', 6, true], 0, 'year'); // ALIASES
3337
3338 addUnitAlias('year', 'y'); // PRIORITIES
3339
3340 addUnitPriority('year', 1); // PARSING
3341
3342 addRegexToken('Y', matchSigned);
3343 addRegexToken('YY', match1to2, match2);
3344 addRegexToken('YYYY', match1to4, match4);
3345 addRegexToken('YYYYY', match1to6, match6);
3346 addRegexToken('YYYYYY', match1to6, match6);
3347 addParseToken(['YYYYY', 'YYYYYY'], YEAR);
3348 addParseToken('YYYY', function (input, array) {
3349 array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
3350 });
3351 addParseToken('YY', function (input, array) {
3352 array[YEAR] = hooks.parseTwoDigitYear(input);
3353 });
3354 addParseToken('Y', function (input, array) {
3355 array[YEAR] = _parseInt$3(input, 10);
3356 }); // HELPERS
3357
3358 function daysInYear(year) {
3359 return isLeapYear(year) ? 366 : 365;
3360 }
3361
3362 function isLeapYear(year) {
3363 return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
3364 } // HOOKS
3365
3366
3367 hooks.parseTwoDigitYear = function (input) {
3368 return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
3369 }; // MOMENTS
3370
3371
3372 var getSetYear = makeGetSet('FullYear', true);
3373
3374 function getIsLeapYear() {
3375 return isLeapYear(this.year());
3376 }
3377
3378 function makeGetSet(unit, keepTime) {
3379 return function (value) {
3380 if (value != null) {
3381 set$1(this, unit, value);
3382 hooks.updateOffset(this, keepTime);
3383 return this;
3384 } else {
3385 return get(this, unit);
3386 }
3387 };
3388 }
3389
3390 function get(mom, unit) {
3391 return mom.isValid() ? mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN;
3392 }
3393
3394 function set$1(mom, unit, value) {
3395 if (mom.isValid() && !isNaN(value)) {
3396 if (unit === 'FullYear' && isLeapYear(mom.year()) && mom.month() === 1 && mom.date() === 29) {
3397 mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value, mom.month(), daysInMonth(value, mom.month()));
3398 } else {
3399 mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
3400 }
3401 }
3402 } // MOMENTS
3403
3404
3405 function stringGet(units) {
3406 units = normalizeUnits(units);
3407
3408 if (isFunction(this[units])) {
3409 return this[units]();
3410 }
3411
3412 return this;
3413 }
3414
3415 function stringSet(units, value) {
3416 if (_typeof_1(units) === 'object') {
3417 units = normalizeObjectUnits(units);
3418 var prioritized = getPrioritizedUnits(units);
3419
3420 for (var i = 0; i < prioritized.length; i++) {
3421 this[prioritized[i].unit](units[prioritized[i].unit]);
3422 }
3423 } else {
3424 units = normalizeUnits(units);
3425
3426 if (isFunction(this[units])) {
3427 return this[units](value);
3428 }
3429 }
3430
3431 return this;
3432 }
3433
3434 function mod(n, x) {
3435 return (n % x + x) % x;
3436 }
3437
3438 var indexOf;
3439
3440 if (indexOf$3(Array.prototype)) {
3441 indexOf = indexOf$3(Array.prototype);
3442 } else {
3443 indexOf = function indexOf(o) {
3444 // I know
3445 var i;
3446
3447 for (i = 0; i < this.length; ++i) {
3448 if (this[i] === o) {
3449 return i;
3450 }
3451 }
3452
3453 return -1;
3454 };
3455 }
3456
3457 function daysInMonth(year, month) {
3458 if (isNaN(year) || isNaN(month)) {
3459 return NaN;
3460 }
3461
3462 var modMonth = mod(month, 12);
3463 year += (month - modMonth) / 12;
3464 return modMonth === 1 ? isLeapYear(year) ? 29 : 28 : 31 - modMonth % 7 % 2;
3465 } // FORMATTING
3466
3467
3468 addFormatToken('M', ['MM', 2], 'Mo', function () {
3469 return this.month() + 1;
3470 });
3471 addFormatToken('MMM', 0, 0, function (format) {
3472 return this.localeData().monthsShort(this, format);
3473 });
3474 addFormatToken('MMMM', 0, 0, function (format) {
3475 return this.localeData().months(this, format);
3476 }); // ALIASES
3477
3478 addUnitAlias('month', 'M'); // PRIORITY
3479
3480 addUnitPriority('month', 8); // PARSING
3481
3482 addRegexToken('M', match1to2);
3483 addRegexToken('MM', match1to2, match2);
3484 addRegexToken('MMM', function (isStrict, locale) {
3485 return locale.monthsShortRegex(isStrict);
3486 });
3487 addRegexToken('MMMM', function (isStrict, locale) {
3488 return locale.monthsRegex(isStrict);
3489 });
3490 addParseToken(['M', 'MM'], function (input, array) {
3491 array[MONTH] = toInt(input) - 1;
3492 });
3493 addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
3494 var month = config._locale.monthsParse(input, token, config._strict); // if we didn't find a month name, mark the date as invalid.
3495
3496
3497 if (month != null) {
3498 array[MONTH] = month;
3499 } else {
3500 getParsingFlags(config).invalidMonth = input;
3501 }
3502 }); // LOCALES
3503
3504 var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/;
3505 var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_');
3506
3507 function localeMonths(m, format) {
3508 if (!m) {
3509 return isArray(this._months) ? this._months : this._months['standalone'];
3510 }
3511
3512 return isArray(this._months) ? this._months[m.month()] : this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()];
3513 }
3514
3515 var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_');
3516
3517 function localeMonthsShort(m, format) {
3518 if (!m) {
3519 return isArray(this._monthsShort) ? this._monthsShort : this._monthsShort['standalone'];
3520 }
3521
3522 return isArray(this._monthsShort) ? this._monthsShort[m.month()] : this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()];
3523 }
3524
3525 function handleStrictParse(monthName, format, strict) {
3526 var i,
3527 ii,
3528 mom,
3529 llc = monthName.toLocaleLowerCase();
3530
3531 if (!this._monthsParse) {
3532 // this is not used
3533 this._monthsParse = [];
3534 this._longMonthsParse = [];
3535 this._shortMonthsParse = [];
3536
3537 for (i = 0; i < 12; ++i) {
3538 mom = createUTC([2000, i]);
3539 this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase();
3540 this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
3541 }
3542 }
3543
3544 if (strict) {
3545 if (format === 'MMM') {
3546 ii = indexOf.call(this._shortMonthsParse, llc);
3547 return ii !== -1 ? ii : null;
3548 } else {
3549 ii = indexOf.call(this._longMonthsParse, llc);
3550 return ii !== -1 ? ii : null;
3551 }
3552 } else {
3553 if (format === 'MMM') {
3554 ii = indexOf.call(this._shortMonthsParse, llc);
3555
3556 if (ii !== -1) {
3557 return ii;
3558 }
3559
3560 ii = indexOf.call(this._longMonthsParse, llc);
3561 return ii !== -1 ? ii : null;
3562 } else {
3563 ii = indexOf.call(this._longMonthsParse, llc);
3564
3565 if (ii !== -1) {
3566 return ii;
3567 }
3568
3569 ii = indexOf.call(this._shortMonthsParse, llc);
3570 return ii !== -1 ? ii : null;
3571 }
3572 }
3573 }
3574
3575 function localeMonthsParse(monthName, format, strict) {
3576 var i, mom, regex;
3577
3578 if (this._monthsParseExact) {
3579 return handleStrictParse.call(this, monthName, format, strict);
3580 }
3581
3582 if (!this._monthsParse) {
3583 this._monthsParse = [];
3584 this._longMonthsParse = [];
3585 this._shortMonthsParse = [];
3586 } // TODO: add sorting
3587 // Sorting makes sure if one month (or abbr) is a prefix of another
3588 // see sorting in computeMonthsParse
3589
3590
3591 for (i = 0; i < 12; i++) {
3592 // make the regex if we don't have it already
3593 mom = createUTC([2000, i]);
3594
3595 if (strict && !this._longMonthsParse[i]) {
3596 this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
3597 this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
3598 }
3599
3600 if (!strict && !this._monthsParse[i]) {
3601 regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
3602 this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
3603 } // test the regex
3604
3605
3606 if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
3607 return i;
3608 } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
3609 return i;
3610 } else if (!strict && this._monthsParse[i].test(monthName)) {
3611 return i;
3612 }
3613 }
3614 } // MOMENTS
3615
3616
3617 function setMonth(mom, value) {
3618 var dayOfMonth;
3619
3620 if (!mom.isValid()) {
3621 // No op
3622 return mom;
3623 }
3624
3625 if (typeof value === 'string') {
3626 if (/^\d+$/.test(value)) {
3627 value = toInt(value);
3628 } else {
3629 value = mom.localeData().monthsParse(value); // TODO: Another silent failure?
3630
3631 if (!isNumber(value)) {
3632 return mom;
3633 }
3634 }
3635 }
3636
3637 dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
3638
3639 mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
3640
3641 return mom;
3642 }
3643
3644 function getSetMonth(value) {
3645 if (value != null) {
3646 setMonth(this, value);
3647 hooks.updateOffset(this, true);
3648 return this;
3649 } else {
3650 return get(this, 'Month');
3651 }
3652 }
3653
3654 function getDaysInMonth() {
3655 return daysInMonth(this.year(), this.month());
3656 }
3657
3658 var defaultMonthsShortRegex = matchWord;
3659
3660 function monthsShortRegex(isStrict) {
3661 if (this._monthsParseExact) {
3662 if (!hasOwnProp(this, '_monthsRegex')) {
3663 computeMonthsParse.call(this);
3664 }
3665
3666 if (isStrict) {
3667 return this._monthsShortStrictRegex;
3668 } else {
3669 return this._monthsShortRegex;
3670 }
3671 } else {
3672 if (!hasOwnProp(this, '_monthsShortRegex')) {
3673 this._monthsShortRegex = defaultMonthsShortRegex;
3674 }
3675
3676 return this._monthsShortStrictRegex && isStrict ? this._monthsShortStrictRegex : this._monthsShortRegex;
3677 }
3678 }
3679
3680 var defaultMonthsRegex = matchWord;
3681
3682 function monthsRegex(isStrict) {
3683 if (this._monthsParseExact) {
3684 if (!hasOwnProp(this, '_monthsRegex')) {
3685 computeMonthsParse.call(this);
3686 }
3687
3688 if (isStrict) {
3689 return this._monthsStrictRegex;
3690 } else {
3691 return this._monthsRegex;
3692 }
3693 } else {
3694 if (!hasOwnProp(this, '_monthsRegex')) {
3695 this._monthsRegex = defaultMonthsRegex;
3696 }
3697
3698 return this._monthsStrictRegex && isStrict ? this._monthsStrictRegex : this._monthsRegex;
3699 }
3700 }
3701
3702 function computeMonthsParse() {
3703 function cmpLenRev(a, b) {
3704 return b.length - a.length;
3705 }
3706
3707 var shortPieces = [],
3708 longPieces = [],
3709 mixedPieces = [],
3710 i,
3711 mom;
3712
3713 for (i = 0; i < 12; i++) {
3714 // make the regex if we don't have it already
3715 mom = createUTC([2000, i]);
3716 shortPieces.push(this.monthsShort(mom, ''));
3717 longPieces.push(this.months(mom, ''));
3718 mixedPieces.push(this.months(mom, ''));
3719 mixedPieces.push(this.monthsShort(mom, ''));
3720 } // Sorting makes sure if one month (or abbr) is a prefix of another it
3721 // will match the longer piece.
3722
3723
3724 sort$2(shortPieces).call(shortPieces, cmpLenRev);
3725 sort$2(longPieces).call(longPieces, cmpLenRev);
3726 sort$2(mixedPieces).call(mixedPieces, cmpLenRev);
3727
3728 for (i = 0; i < 12; i++) {
3729 shortPieces[i] = regexEscape(shortPieces[i]);
3730 longPieces[i] = regexEscape(longPieces[i]);
3731 }
3732
3733 for (i = 0; i < 24; i++) {
3734 mixedPieces[i] = regexEscape(mixedPieces[i]);
3735 }
3736
3737 this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
3738 this._monthsShortRegex = this._monthsRegex;
3739 this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
3740 this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
3741 }
3742
3743 function createDate(y, m, d, h, M, s, ms) {
3744 // can't just apply() to create a date:
3745 // https://stackoverflow.com/q/181348
3746 var date; // the date constructor remaps years 0-99 to 1900-1999
3747
3748 if (y < 100 && y >= 0) {
3749 // preserve leap years using a full 400 year cycle, then reset
3750 date = new Date(y + 400, m, d, h, M, s, ms);
3751
3752 if (isFinite(date.getFullYear())) {
3753 date.setFullYear(y);
3754 }
3755 } else {
3756 date = new Date(y, m, d, h, M, s, ms);
3757 }
3758
3759 return date;
3760 }
3761
3762 function createUTCDate(y) {
3763 var date; // the Date.UTC function remaps years 0-99 to 1900-1999
3764
3765 if (y < 100 && y >= 0) {
3766 var args = slice$2(Array.prototype).call(arguments); // preserve leap years using a full 400 year cycle, then reset
3767
3768 args[0] = y + 400;
3769 date = new Date(Date.UTC.apply(null, args));
3770
3771 if (isFinite(date.getUTCFullYear())) {
3772 date.setUTCFullYear(y);
3773 }
3774 } else {
3775 date = new Date(Date.UTC.apply(null, arguments));
3776 }
3777
3778 return date;
3779 } // start-of-first-week - start-of-year
3780
3781
3782 function firstWeekOffset(year, dow, doy) {
3783 var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
3784 fwd = 7 + dow - doy,
3785 // first-week day local weekday -- which local weekday is fwd
3786 fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
3787 return -fwdlw + fwd - 1;
3788 } // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
3789
3790
3791 function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
3792 var localWeekday = (7 + weekday - dow) % 7,
3793 weekOffset = firstWeekOffset(year, dow, doy),
3794 dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
3795 resYear,
3796 resDayOfYear;
3797
3798 if (dayOfYear <= 0) {
3799 resYear = year - 1;
3800 resDayOfYear = daysInYear(resYear) + dayOfYear;
3801 } else if (dayOfYear > daysInYear(year)) {
3802 resYear = year + 1;
3803 resDayOfYear = dayOfYear - daysInYear(year);
3804 } else {
3805 resYear = year;
3806 resDayOfYear = dayOfYear;
3807 }
3808
3809 return {
3810 year: resYear,
3811 dayOfYear: resDayOfYear
3812 };
3813 }
3814
3815 function weekOfYear(mom, dow, doy) {
3816 var weekOffset = firstWeekOffset(mom.year(), dow, doy),
3817 week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
3818 resWeek,
3819 resYear;
3820
3821 if (week < 1) {
3822 resYear = mom.year() - 1;
3823 resWeek = week + weeksInYear(resYear, dow, doy);
3824 } else if (week > weeksInYear(mom.year(), dow, doy)) {
3825 resWeek = week - weeksInYear(mom.year(), dow, doy);
3826 resYear = mom.year() + 1;
3827 } else {
3828 resYear = mom.year();
3829 resWeek = week;
3830 }
3831
3832 return {
3833 week: resWeek,
3834 year: resYear
3835 };
3836 }
3837
3838 function weeksInYear(year, dow, doy) {
3839 var weekOffset = firstWeekOffset(year, dow, doy),
3840 weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
3841 return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
3842 } // FORMATTING
3843
3844
3845 addFormatToken('w', ['ww', 2], 'wo', 'week');
3846 addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek'); // ALIASES
3847
3848 addUnitAlias('week', 'w');
3849 addUnitAlias('isoWeek', 'W'); // PRIORITIES
3850
3851 addUnitPriority('week', 5);
3852 addUnitPriority('isoWeek', 5); // PARSING
3853
3854 addRegexToken('w', match1to2);
3855 addRegexToken('ww', match1to2, match2);
3856 addRegexToken('W', match1to2);
3857 addRegexToken('WW', match1to2, match2);
3858 addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) {
3859 week[token.substr(0, 1)] = toInt(input);
3860 }); // HELPERS
3861 // LOCALES
3862
3863 function localeWeek(mom) {
3864 return weekOfYear(mom, this._week.dow, this._week.doy).week;
3865 }
3866
3867 var defaultLocaleWeek = {
3868 dow: 0,
3869 // Sunday is the first day of the week.
3870 doy: 6 // The week that contains Jan 6th is the first week of the year.
3871
3872 };
3873
3874 function localeFirstDayOfWeek() {
3875 return this._week.dow;
3876 }
3877
3878 function localeFirstDayOfYear() {
3879 return this._week.doy;
3880 } // MOMENTS
3881
3882
3883 function getSetWeek(input) {
3884 var week = this.localeData().week(this);
3885 return input == null ? week : this.add((input - week) * 7, 'd');
3886 }
3887
3888 function getSetISOWeek(input) {
3889 var week = weekOfYear(this, 1, 4).week;
3890 return input == null ? week : this.add((input - week) * 7, 'd');
3891 } // FORMATTING
3892
3893
3894 addFormatToken('d', 0, 'do', 'day');
3895 addFormatToken('dd', 0, 0, function (format) {
3896 return this.localeData().weekdaysMin(this, format);
3897 });
3898 addFormatToken('ddd', 0, 0, function (format) {
3899 return this.localeData().weekdaysShort(this, format);
3900 });
3901 addFormatToken('dddd', 0, 0, function (format) {
3902 return this.localeData().weekdays(this, format);
3903 });
3904 addFormatToken('e', 0, 0, 'weekday');
3905 addFormatToken('E', 0, 0, 'isoWeekday'); // ALIASES
3906
3907 addUnitAlias('day', 'd');
3908 addUnitAlias('weekday', 'e');
3909 addUnitAlias('isoWeekday', 'E'); // PRIORITY
3910
3911 addUnitPriority('day', 11);
3912 addUnitPriority('weekday', 11);
3913 addUnitPriority('isoWeekday', 11); // PARSING
3914
3915 addRegexToken('d', match1to2);
3916 addRegexToken('e', match1to2);
3917 addRegexToken('E', match1to2);
3918 addRegexToken('dd', function (isStrict, locale) {
3919 return locale.weekdaysMinRegex(isStrict);
3920 });
3921 addRegexToken('ddd', function (isStrict, locale) {
3922 return locale.weekdaysShortRegex(isStrict);
3923 });
3924 addRegexToken('dddd', function (isStrict, locale) {
3925 return locale.weekdaysRegex(isStrict);
3926 });
3927 addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
3928 var weekday = config._locale.weekdaysParse(input, token, config._strict); // if we didn't get a weekday name, mark the date as invalid
3929
3930
3931 if (weekday != null) {
3932 week.d = weekday;
3933 } else {
3934 getParsingFlags(config).invalidWeekday = input;
3935 }
3936 });
3937 addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
3938 week[token] = toInt(input);
3939 }); // HELPERS
3940
3941 function parseWeekday(input, locale) {
3942 if (typeof input !== 'string') {
3943 return input;
3944 }
3945
3946 if (!isNaN(input)) {
3947 return _parseInt$3(input, 10);
3948 }
3949
3950 input = locale.weekdaysParse(input);
3951
3952 if (typeof input === 'number') {
3953 return input;
3954 }
3955
3956 return null;
3957 }
3958
3959 function parseIsoWeekday(input, locale) {
3960 if (typeof input === 'string') {
3961 return locale.weekdaysParse(input) % 7 || 7;
3962 }
3963
3964 return isNaN(input) ? null : input;
3965 } // LOCALES
3966
3967
3968 function shiftWeekdays(ws, n) {
3969 var _context;
3970
3971 return concat$2(_context = slice$2(ws).call(ws, n, 7)).call(_context, slice$2(ws).call(ws, 0, n));
3972 }
3973
3974 var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_');
3975
3976 function localeWeekdays(m, format) {
3977 var weekdays = isArray(this._weekdays) ? this._weekdays : this._weekdays[m && m !== true && this._weekdays.isFormat.test(format) ? 'format' : 'standalone'];
3978 return m === true ? shiftWeekdays(weekdays, this._week.dow) : m ? weekdays[m.day()] : weekdays;
3979 }
3980
3981 var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');
3982
3983 function localeWeekdaysShort(m) {
3984 return m === true ? shiftWeekdays(this._weekdaysShort, this._week.dow) : m ? this._weekdaysShort[m.day()] : this._weekdaysShort;
3985 }
3986
3987 var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_');
3988
3989 function localeWeekdaysMin(m) {
3990 return m === true ? shiftWeekdays(this._weekdaysMin, this._week.dow) : m ? this._weekdaysMin[m.day()] : this._weekdaysMin;
3991 }
3992
3993 function handleStrictParse$1(weekdayName, format, strict) {
3994 var i,
3995 ii,
3996 mom,
3997 llc = weekdayName.toLocaleLowerCase();
3998
3999 if (!this._weekdaysParse) {
4000 this._weekdaysParse = [];
4001 this._shortWeekdaysParse = [];
4002 this._minWeekdaysParse = [];
4003
4004 for (i = 0; i < 7; ++i) {
4005 mom = createUTC([2000, 1]).day(i);
4006 this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase();
4007 this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase();
4008 this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
4009 }
4010 }
4011
4012 if (strict) {
4013 if (format === 'dddd') {
4014 ii = indexOf.call(this._weekdaysParse, llc);
4015 return ii !== -1 ? ii : null;
4016 } else if (format === 'ddd') {
4017 ii = indexOf.call(this._shortWeekdaysParse, llc);
4018 return ii !== -1 ? ii : null;
4019 } else {
4020 ii = indexOf.call(this._minWeekdaysParse, llc);
4021 return ii !== -1 ? ii : null;
4022 }
4023 } else {
4024 if (format === 'dddd') {
4025 ii = indexOf.call(this._weekdaysParse, llc);
4026
4027 if (ii !== -1) {
4028 return ii;
4029 }
4030
4031 ii = indexOf.call(this._shortWeekdaysParse, llc);
4032
4033 if (ii !== -1) {
4034 return ii;
4035 }
4036
4037 ii = indexOf.call(this._minWeekdaysParse, llc);
4038 return ii !== -1 ? ii : null;
4039 } else if (format === 'ddd') {
4040 ii = indexOf.call(this._shortWeekdaysParse, llc);
4041
4042 if (ii !== -1) {
4043 return ii;
4044 }
4045
4046 ii = indexOf.call(this._weekdaysParse, llc);
4047
4048 if (ii !== -1) {
4049 return ii;
4050 }
4051
4052 ii = indexOf.call(this._minWeekdaysParse, llc);
4053 return ii !== -1 ? ii : null;
4054 } else {
4055 ii = indexOf.call(this._minWeekdaysParse, llc);
4056
4057 if (ii !== -1) {
4058 return ii;
4059 }
4060
4061 ii = indexOf.call(this._weekdaysParse, llc);
4062
4063 if (ii !== -1) {
4064 return ii;
4065 }
4066
4067 ii = indexOf.call(this._shortWeekdaysParse, llc);
4068 return ii !== -1 ? ii : null;
4069 }
4070 }
4071 }
4072
4073 function localeWeekdaysParse(weekdayName, format, strict) {
4074 var i, mom, regex;
4075
4076 if (this._weekdaysParseExact) {
4077 return handleStrictParse$1.call(this, weekdayName, format, strict);
4078 }
4079
4080 if (!this._weekdaysParse) {
4081 this._weekdaysParse = [];
4082 this._minWeekdaysParse = [];
4083 this._shortWeekdaysParse = [];
4084 this._fullWeekdaysParse = [];
4085 }
4086
4087 for (i = 0; i < 7; i++) {
4088 // make the regex if we don't have it already
4089 mom = createUTC([2000, 1]).day(i);
4090
4091 if (strict && !this._fullWeekdaysParse[i]) {
4092 this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\\.?') + '$', 'i');
4093 this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$', 'i');
4094 this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$', 'i');
4095 }
4096
4097 if (!this._weekdaysParse[i]) {
4098 regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
4099 this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
4100 } // test the regex
4101
4102
4103 if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) {
4104 return i;
4105 } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) {
4106 return i;
4107 } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) {
4108 return i;
4109 } else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
4110 return i;
4111 }
4112 }
4113 } // MOMENTS
4114
4115
4116 function getSetDayOfWeek(input) {
4117 if (!this.isValid()) {
4118 return input != null ? this : NaN;
4119 }
4120
4121 var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
4122
4123 if (input != null) {
4124 input = parseWeekday(input, this.localeData());
4125 return this.add(input - day, 'd');
4126 } else {
4127 return day;
4128 }
4129 }
4130
4131 function getSetLocaleDayOfWeek(input) {
4132 if (!this.isValid()) {
4133 return input != null ? this : NaN;
4134 }
4135
4136 var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
4137 return input == null ? weekday : this.add(input - weekday, 'd');
4138 }
4139
4140 function getSetISODayOfWeek(input) {
4141 if (!this.isValid()) {
4142 return input != null ? this : NaN;
4143 } // behaves the same as moment#day except
4144 // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
4145 // as a setter, sunday should belong to the previous week.
4146
4147
4148 if (input != null) {
4149 var weekday = parseIsoWeekday(input, this.localeData());
4150 return this.day(this.day() % 7 ? weekday : weekday - 7);
4151 } else {
4152 return this.day() || 7;
4153 }
4154 }
4155
4156 var defaultWeekdaysRegex = matchWord;
4157
4158 function weekdaysRegex(isStrict) {
4159 if (this._weekdaysParseExact) {
4160 if (!hasOwnProp(this, '_weekdaysRegex')) {
4161 computeWeekdaysParse.call(this);
4162 }
4163
4164 if (isStrict) {
4165 return this._weekdaysStrictRegex;
4166 } else {
4167 return this._weekdaysRegex;
4168 }
4169 } else {
4170 if (!hasOwnProp(this, '_weekdaysRegex')) {
4171 this._weekdaysRegex = defaultWeekdaysRegex;
4172 }
4173
4174 return this._weekdaysStrictRegex && isStrict ? this._weekdaysStrictRegex : this._weekdaysRegex;
4175 }
4176 }
4177
4178 var defaultWeekdaysShortRegex = matchWord;
4179
4180 function weekdaysShortRegex(isStrict) {
4181 if (this._weekdaysParseExact) {
4182 if (!hasOwnProp(this, '_weekdaysRegex')) {
4183 computeWeekdaysParse.call(this);
4184 }
4185
4186 if (isStrict) {
4187 return this._weekdaysShortStrictRegex;
4188 } else {
4189 return this._weekdaysShortRegex;
4190 }
4191 } else {
4192 if (!hasOwnProp(this, '_weekdaysShortRegex')) {
4193 this._weekdaysShortRegex = defaultWeekdaysShortRegex;
4194 }
4195
4196 return this._weekdaysShortStrictRegex && isStrict ? this._weekdaysShortStrictRegex : this._weekdaysShortRegex;
4197 }
4198 }
4199
4200 var defaultWeekdaysMinRegex = matchWord;
4201
4202 function weekdaysMinRegex(isStrict) {
4203 if (this._weekdaysParseExact) {
4204 if (!hasOwnProp(this, '_weekdaysRegex')) {
4205 computeWeekdaysParse.call(this);
4206 }
4207
4208 if (isStrict) {
4209 return this._weekdaysMinStrictRegex;
4210 } else {
4211 return this._weekdaysMinRegex;
4212 }
4213 } else {
4214 if (!hasOwnProp(this, '_weekdaysMinRegex')) {
4215 this._weekdaysMinRegex = defaultWeekdaysMinRegex;
4216 }
4217
4218 return this._weekdaysMinStrictRegex && isStrict ? this._weekdaysMinStrictRegex : this._weekdaysMinRegex;
4219 }
4220 }
4221
4222 function computeWeekdaysParse() {
4223 function cmpLenRev(a, b) {
4224 return b.length - a.length;
4225 }
4226
4227 var minPieces = [],
4228 shortPieces = [],
4229 longPieces = [],
4230 mixedPieces = [],
4231 i,
4232 mom,
4233 minp,
4234 shortp,
4235 longp;
4236
4237 for (i = 0; i < 7; i++) {
4238 // make the regex if we don't have it already
4239 mom = createUTC([2000, 1]).day(i);
4240 minp = this.weekdaysMin(mom, '');
4241 shortp = this.weekdaysShort(mom, '');
4242 longp = this.weekdays(mom, '');
4243 minPieces.push(minp);
4244 shortPieces.push(shortp);
4245 longPieces.push(longp);
4246 mixedPieces.push(minp);
4247 mixedPieces.push(shortp);
4248 mixedPieces.push(longp);
4249 } // Sorting makes sure if one weekday (or abbr) is a prefix of another it
4250 // will match the longer piece.
4251
4252
4253 sort$2(minPieces).call(minPieces, cmpLenRev);
4254 sort$2(shortPieces).call(shortPieces, cmpLenRev);
4255 sort$2(longPieces).call(longPieces, cmpLenRev);
4256 sort$2(mixedPieces).call(mixedPieces, cmpLenRev);
4257
4258 for (i = 0; i < 7; i++) {
4259 shortPieces[i] = regexEscape(shortPieces[i]);
4260 longPieces[i] = regexEscape(longPieces[i]);
4261 mixedPieces[i] = regexEscape(mixedPieces[i]);
4262 }
4263
4264 this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
4265 this._weekdaysShortRegex = this._weekdaysRegex;
4266 this._weekdaysMinRegex = this._weekdaysRegex;
4267 this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
4268 this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
4269 this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i');
4270 } // FORMATTING
4271
4272
4273 function hFormat() {
4274 return this.hours() % 12 || 12;
4275 }
4276
4277 function kFormat() {
4278 return this.hours() || 24;
4279 }
4280
4281 addFormatToken('H', ['HH', 2], 0, 'hour');
4282 addFormatToken('h', ['hh', 2], 0, hFormat);
4283 addFormatToken('k', ['kk', 2], 0, kFormat);
4284 addFormatToken('hmm', 0, 0, function () {
4285 return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
4286 });
4287 addFormatToken('hmmss', 0, 0, function () {
4288 return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2);
4289 });
4290 addFormatToken('Hmm', 0, 0, function () {
4291 return '' + this.hours() + zeroFill(this.minutes(), 2);
4292 });
4293 addFormatToken('Hmmss', 0, 0, function () {
4294 return '' + this.hours() + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2);
4295 });
4296
4297 function meridiem(token, lowercase) {
4298 addFormatToken(token, 0, 0, function () {
4299 return this.localeData().meridiem(this.hours(), this.minutes(), lowercase);
4300 });
4301 }
4302
4303 meridiem('a', true);
4304 meridiem('A', false); // ALIASES
4305
4306 addUnitAlias('hour', 'h'); // PRIORITY
4307
4308 addUnitPriority('hour', 13); // PARSING
4309
4310 function matchMeridiem(isStrict, locale) {
4311 return locale._meridiemParse;
4312 }
4313
4314 addRegexToken('a', matchMeridiem);
4315 addRegexToken('A', matchMeridiem);
4316 addRegexToken('H', match1to2);
4317 addRegexToken('h', match1to2);
4318 addRegexToken('k', match1to2);
4319 addRegexToken('HH', match1to2, match2);
4320 addRegexToken('hh', match1to2, match2);
4321 addRegexToken('kk', match1to2, match2);
4322 addRegexToken('hmm', match3to4);
4323 addRegexToken('hmmss', match5to6);
4324 addRegexToken('Hmm', match3to4);
4325 addRegexToken('Hmmss', match5to6);
4326 addParseToken(['H', 'HH'], HOUR);
4327 addParseToken(['k', 'kk'], function (input, array, config) {
4328 var kInput = toInt(input);
4329 array[HOUR] = kInput === 24 ? 0 : kInput;
4330 });
4331 addParseToken(['a', 'A'], function (input, array, config) {
4332 config._isPm = config._locale.isPM(input);
4333 config._meridiem = input;
4334 });
4335 addParseToken(['h', 'hh'], function (input, array, config) {
4336 array[HOUR] = toInt(input);
4337 getParsingFlags(config).bigHour = true;
4338 });
4339 addParseToken('hmm', function (input, array, config) {
4340 var pos = input.length - 2;
4341 array[HOUR] = toInt(input.substr(0, pos));
4342 array[MINUTE] = toInt(input.substr(pos));
4343 getParsingFlags(config).bigHour = true;
4344 });
4345 addParseToken('hmmss', function (input, array, config) {
4346 var pos1 = input.length - 4;
4347 var pos2 = input.length - 2;
4348 array[HOUR] = toInt(input.substr(0, pos1));
4349 array[MINUTE] = toInt(input.substr(pos1, 2));
4350 array[SECOND] = toInt(input.substr(pos2));
4351 getParsingFlags(config).bigHour = true;
4352 });
4353 addParseToken('Hmm', function (input, array, config) {
4354 var pos = input.length - 2;
4355 array[HOUR] = toInt(input.substr(0, pos));
4356 array[MINUTE] = toInt(input.substr(pos));
4357 });
4358 addParseToken('Hmmss', function (input, array, config) {
4359 var pos1 = input.length - 4;
4360 var pos2 = input.length - 2;
4361 array[HOUR] = toInt(input.substr(0, pos1));
4362 array[MINUTE] = toInt(input.substr(pos1, 2));
4363 array[SECOND] = toInt(input.substr(pos2));
4364 }); // LOCALES
4365
4366 function localeIsPM(input) {
4367 // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
4368 // Using charAt should be more compatible.
4369 return (input + '').toLowerCase().charAt(0) === 'p';
4370 }
4371
4372 var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i;
4373
4374 function localeMeridiem(hours, minutes, isLower) {
4375 if (hours > 11) {
4376 return isLower ? 'pm' : 'PM';
4377 } else {
4378 return isLower ? 'am' : 'AM';
4379 }
4380 } // MOMENTS
4381 // Setting the hour should keep the time, because the user explicitly
4382 // specified which hour they want. So trying to maintain the same hour (in
4383 // a new timezone) makes sense. Adding/subtracting hours does not follow
4384 // this rule.
4385
4386
4387 var getSetHour = makeGetSet('Hours', true);
4388 var baseConfig = {
4389 calendar: defaultCalendar,
4390 longDateFormat: defaultLongDateFormat,
4391 invalidDate: defaultInvalidDate,
4392 ordinal: defaultOrdinal,
4393 dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,
4394 relativeTime: defaultRelativeTime,
4395 months: defaultLocaleMonths,
4396 monthsShort: defaultLocaleMonthsShort,
4397 week: defaultLocaleWeek,
4398 weekdays: defaultLocaleWeekdays,
4399 weekdaysMin: defaultLocaleWeekdaysMin,
4400 weekdaysShort: defaultLocaleWeekdaysShort,
4401 meridiemParse: defaultLocaleMeridiemParse
4402 }; // internal storage for locale config files
4403
4404 var locales = {};
4405 var localeFamilies = {};
4406 var globalLocale;
4407
4408 function normalizeLocale(key) {
4409 return key ? key.toLowerCase().replace('_', '-') : key;
4410 } // pick the locale from the array
4411 // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
4412 // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
4413
4414
4415 function chooseLocale(names) {
4416 var i = 0,
4417 j,
4418 next,
4419 locale,
4420 split;
4421
4422 while (i < names.length) {
4423 split = normalizeLocale(names[i]).split('-');
4424 j = split.length;
4425 next = normalizeLocale(names[i + 1]);
4426 next = next ? next.split('-') : null;
4427
4428 while (j > 0) {
4429 locale = loadLocale(slice$2(split).call(split, 0, j).join('-'));
4430
4431 if (locale) {
4432 return locale;
4433 }
4434
4435 if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
4436 //the next array item is better than a shallower substring of this one
4437 break;
4438 }
4439
4440 j--;
4441 }
4442
4443 i++;
4444 }
4445
4446 return globalLocale;
4447 }
4448
4449 function loadLocale(name) {
4450 var oldLocale = null; // TODO: Find a better way to register and load all the locales in Node
4451
4452 if (!locales[name] && 'object' !== 'undefined' && module && module.exports) {
4453 try {
4454 oldLocale = globalLocale._abbr;
4455 var aliasedRequire = commonjsRequire;
4456 aliasedRequire('./locale/' + name);
4457 getSetGlobalLocale(oldLocale);
4458 } catch (e) {}
4459 }
4460
4461 return locales[name];
4462 } // This function will load locale and then set the global locale. If
4463 // no arguments are passed in, it will simply return the current global
4464 // locale key.
4465
4466
4467 function getSetGlobalLocale(key, values) {
4468 var data;
4469
4470 if (key) {
4471 if (isUndefined(values)) {
4472 data = getLocale(key);
4473 } else {
4474 data = defineLocale(key, values);
4475 }
4476
4477 if (data) {
4478 // moment.duration._locale = moment._locale = data;
4479 globalLocale = data;
4480 } else {
4481 if (typeof console !== 'undefined' && console.warn) {
4482 //warn user if arguments are passed but the locale could not be set
4483 console.warn('Locale ' + key + ' not found. Did you forget to load it?');
4484 }
4485 }
4486 }
4487
4488 return globalLocale._abbr;
4489 }
4490
4491 function defineLocale(name, config) {
4492 if (config !== null) {
4493 var locale,
4494 parentConfig = baseConfig;
4495 config.abbr = name;
4496
4497 if (locales[name] != null) {
4498 deprecateSimple('defineLocaleOverride', 'use moment.updateLocale(localeName, config) to change ' + 'an existing locale. moment.defineLocale(localeName, ' + 'config) should only be used for creating a new locale ' + 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.');
4499 parentConfig = locales[name]._config;
4500 } else if (config.parentLocale != null) {
4501 if (locales[config.parentLocale] != null) {
4502 parentConfig = locales[config.parentLocale]._config;
4503 } else {
4504 locale = loadLocale(config.parentLocale);
4505
4506 if (locale != null) {
4507 parentConfig = locale._config;
4508 } else {
4509 if (!localeFamilies[config.parentLocale]) {
4510 localeFamilies[config.parentLocale] = [];
4511 }
4512
4513 localeFamilies[config.parentLocale].push({
4514 name: name,
4515 config: config
4516 });
4517 return null;
4518 }
4519 }
4520 }
4521
4522 locales[name] = new Locale(mergeConfigs(parentConfig, config));
4523
4524 if (localeFamilies[name]) {
4525 var _context2;
4526
4527 forEach$2(_context2 = localeFamilies[name]).call(_context2, function (x) {
4528 defineLocale(x.name, x.config);
4529 });
4530 } // backwards compat for now: also set the locale
4531 // make sure we set the locale AFTER all child locales have been
4532 // created, so we won't end up with the child locale set.
4533
4534
4535 getSetGlobalLocale(name);
4536 return locales[name];
4537 } else {
4538 // useful for testing
4539 delete locales[name];
4540 return null;
4541 }
4542 }
4543
4544 function updateLocale(name, config) {
4545 if (config != null) {
4546 var locale,
4547 tmpLocale,
4548 parentConfig = baseConfig; // MERGE
4549
4550 tmpLocale = loadLocale(name);
4551
4552 if (tmpLocale != null) {
4553 parentConfig = tmpLocale._config;
4554 }
4555
4556 config = mergeConfigs(parentConfig, config);
4557 locale = new Locale(config);
4558 locale.parentLocale = locales[name];
4559 locales[name] = locale; // backwards compat for now: also set the locale
4560
4561 getSetGlobalLocale(name);
4562 } else {
4563 // pass null for config to unupdate, useful for tests
4564 if (locales[name] != null) {
4565 if (locales[name].parentLocale != null) {
4566 locales[name] = locales[name].parentLocale;
4567 } else if (locales[name] != null) {
4568 delete locales[name];
4569 }
4570 }
4571 }
4572
4573 return locales[name];
4574 } // returns locale data
4575
4576
4577 function getLocale(key) {
4578 var locale;
4579
4580 if (key && key._locale && key._locale._abbr) {
4581 key = key._locale._abbr;
4582 }
4583
4584 if (!key) {
4585 return globalLocale;
4586 }
4587
4588 if (!isArray(key)) {
4589 //short-circuit everything else
4590 locale = loadLocale(key);
4591
4592 if (locale) {
4593 return locale;
4594 }
4595
4596 key = [key];
4597 }
4598
4599 return chooseLocale(key);
4600 }
4601
4602 function listLocales() {
4603 return keys(locales);
4604 }
4605
4606 function checkOverflow(m) {
4607 var overflow;
4608 var a = m._a;
4609
4610 if (a && getParsingFlags(m).overflow === -2) {
4611 overflow = a[MONTH] < 0 || a[MONTH] > 11 ? MONTH : a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE : a[HOUR] < 0 || a[HOUR] > 24 || a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0) ? HOUR : a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE : a[SECOND] < 0 || a[SECOND] > 59 ? SECOND : a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND : -1;
4612
4613 if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
4614 overflow = DATE;
4615 }
4616
4617 if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
4618 overflow = WEEK;
4619 }
4620
4621 if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
4622 overflow = WEEKDAY;
4623 }
4624
4625 getParsingFlags(m).overflow = overflow;
4626 }
4627
4628 return m;
4629 } // Pick the first defined of two or three arguments.
4630
4631
4632 function defaults(a, b, c) {
4633 if (a != null) {
4634 return a;
4635 }
4636
4637 if (b != null) {
4638 return b;
4639 }
4640
4641 return c;
4642 }
4643
4644 function currentDateArray(config) {
4645 // hooks is actually the exported moment object
4646 var nowValue = new Date(hooks.now());
4647
4648 if (config._useUTC) {
4649 return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()];
4650 }
4651
4652 return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
4653 } // convert an array to a date.
4654 // the array should mirror the parameters below
4655 // note: all values past the year are optional and will default to the lowest possible value.
4656 // [year, month, day , hour, minute, second, millisecond]
4657
4658
4659 function configFromArray(config) {
4660 var i,
4661 date,
4662 input = [],
4663 currentDate,
4664 expectedWeekday,
4665 yearToUse;
4666
4667 if (config._d) {
4668 return;
4669 }
4670
4671 currentDate = currentDateArray(config); //compute day of the year from weeks and weekdays
4672
4673 if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
4674 dayOfYearFromWeekInfo(config);
4675 } //if the day of the year is set, figure out what it is
4676
4677
4678 if (config._dayOfYear != null) {
4679 yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
4680
4681 if (config._dayOfYear > daysInYear(yearToUse) || config._dayOfYear === 0) {
4682 getParsingFlags(config)._overflowDayOfYear = true;
4683 }
4684
4685 date = createUTCDate(yearToUse, 0, config._dayOfYear);
4686 config._a[MONTH] = date.getUTCMonth();
4687 config._a[DATE] = date.getUTCDate();
4688 } // Default to current date.
4689 // * if no year, month, day of month are given, default to today
4690 // * if day of month is given, default month and year
4691 // * if month is given, default only year
4692 // * if year is given, don't default anything
4693
4694
4695 for (i = 0; i < 3 && config._a[i] == null; ++i) {
4696 config._a[i] = input[i] = currentDate[i];
4697 } // Zero out whatever was not defaulted, including time
4698
4699
4700 for (; i < 7; i++) {
4701 config._a[i] = input[i] = config._a[i] == null ? i === 2 ? 1 : 0 : config._a[i];
4702 } // Check for 24:00:00.000
4703
4704
4705 if (config._a[HOUR] === 24 && config._a[MINUTE] === 0 && config._a[SECOND] === 0 && config._a[MILLISECOND] === 0) {
4706 config._nextDay = true;
4707 config._a[HOUR] = 0;
4708 }
4709
4710 config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input);
4711 expectedWeekday = config._useUTC ? config._d.getUTCDay() : config._d.getDay(); // Apply timezone offset from input. The actual utcOffset can be changed
4712 // with parseZone.
4713
4714 if (config._tzm != null) {
4715 config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
4716 }
4717
4718 if (config._nextDay) {
4719 config._a[HOUR] = 24;
4720 } // check for mismatching day of week
4721
4722
4723 if (config._w && typeof config._w.d !== 'undefined' && config._w.d !== expectedWeekday) {
4724 getParsingFlags(config).weekdayMismatch = true;
4725 }
4726 }
4727
4728 function dayOfYearFromWeekInfo(config) {
4729 var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow;
4730 w = config._w;
4731
4732 if (w.GG != null || w.W != null || w.E != null) {
4733 dow = 1;
4734 doy = 4; // TODO: We need to take the current isoWeekYear, but that depends on
4735 // how we interpret now (local, utc, fixed offset). So create
4736 // a now version of current config (take local/utc/offset flags, and
4737 // create now).
4738
4739 weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year);
4740 week = defaults(w.W, 1);
4741 weekday = defaults(w.E, 1);
4742
4743 if (weekday < 1 || weekday > 7) {
4744 weekdayOverflow = true;
4745 }
4746 } else {
4747 dow = config._locale._week.dow;
4748 doy = config._locale._week.doy;
4749 var curWeek = weekOfYear(createLocal(), dow, doy);
4750 weekYear = defaults(w.gg, config._a[YEAR], curWeek.year); // Default to current week.
4751
4752 week = defaults(w.w, curWeek.week);
4753
4754 if (w.d != null) {
4755 // weekday -- low day numbers are considered next week
4756 weekday = w.d;
4757
4758 if (weekday < 0 || weekday > 6) {
4759 weekdayOverflow = true;
4760 }
4761 } else if (w.e != null) {
4762 // local weekday -- counting starts from beginning of week
4763 weekday = w.e + dow;
4764
4765 if (w.e < 0 || w.e > 6) {
4766 weekdayOverflow = true;
4767 }
4768 } else {
4769 // default to beginning of week
4770 weekday = dow;
4771 }
4772 }
4773
4774 if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
4775 getParsingFlags(config)._overflowWeeks = true;
4776 } else if (weekdayOverflow != null) {
4777 getParsingFlags(config)._overflowWeekday = true;
4778 } else {
4779 temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
4780 config._a[YEAR] = temp.year;
4781 config._dayOfYear = temp.dayOfYear;
4782 }
4783 } // iso 8601 regex
4784 // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
4785
4786
4787 var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;
4788 var basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;
4789 var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/;
4790 var isoDates = [['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/], ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/], ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/], ['GGGG-[W]WW', /\d{4}-W\d\d/, false], ['YYYY-DDD', /\d{4}-\d{3}/], ['YYYY-MM', /\d{4}-\d\d/, false], ['YYYYYYMMDD', /[+-]\d{10}/], ['YYYYMMDD', /\d{8}/], // YYYYMM is NOT allowed by the standard
4791 ['GGGG[W]WWE', /\d{4}W\d{3}/], ['GGGG[W]WW', /\d{4}W\d{2}/, false], ['YYYYDDD', /\d{7}/]]; // iso time formats and regexes
4792
4793 var isoTimes = [['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/], ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/], ['HH:mm:ss', /\d\d:\d\d:\d\d/], ['HH:mm', /\d\d:\d\d/], ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/], ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/], ['HHmmss', /\d\d\d\d\d\d/], ['HHmm', /\d\d\d\d/], ['HH', /\d\d/]];
4794 var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i; // date from iso format
4795
4796 function configFromISO(config) {
4797 var i,
4798 l,
4799 string = config._i,
4800 match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
4801 allowTime,
4802 dateFormat,
4803 timeFormat,
4804 tzFormat;
4805
4806 if (match) {
4807 getParsingFlags(config).iso = true;
4808
4809 for (i = 0, l = isoDates.length; i < l; i++) {
4810 if (isoDates[i][1].exec(match[1])) {
4811 dateFormat = isoDates[i][0];
4812 allowTime = isoDates[i][2] !== false;
4813 break;
4814 }
4815 }
4816
4817 if (dateFormat == null) {
4818 config._isValid = false;
4819 return;
4820 }
4821
4822 if (match[3]) {
4823 for (i = 0, l = isoTimes.length; i < l; i++) {
4824 if (isoTimes[i][1].exec(match[3])) {
4825 // match[2] should be 'T' or space
4826 timeFormat = (match[2] || ' ') + isoTimes[i][0];
4827 break;
4828 }
4829 }
4830
4831 if (timeFormat == null) {
4832 config._isValid = false;
4833 return;
4834 }
4835 }
4836
4837 if (!allowTime && timeFormat != null) {
4838 config._isValid = false;
4839 return;
4840 }
4841
4842 if (match[4]) {
4843 if (tzRegex.exec(match[4])) {
4844 tzFormat = 'Z';
4845 } else {
4846 config._isValid = false;
4847 return;
4848 }
4849 }
4850
4851 config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
4852 configFromStringAndFormat(config);
4853 } else {
4854 config._isValid = false;
4855 }
4856 } // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
4857
4858
4859 var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/;
4860
4861 function extractFromRFC2822Strings(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {
4862 var result = [untruncateYear(yearStr), indexOf$3(defaultLocaleMonthsShort).call(defaultLocaleMonthsShort, monthStr), _parseInt$3(dayStr, 10), _parseInt$3(hourStr, 10), _parseInt$3(minuteStr, 10)];
4863
4864 if (secondStr) {
4865 result.push(_parseInt$3(secondStr, 10));
4866 }
4867
4868 return result;
4869 }
4870
4871 function untruncateYear(yearStr) {
4872 var year = _parseInt$3(yearStr, 10);
4873
4874 if (year <= 49) {
4875 return 2000 + year;
4876 } else if (year <= 999) {
4877 return 1900 + year;
4878 }
4879
4880 return year;
4881 }
4882
4883 function preprocessRFC2822(s) {
4884 // Remove comments and folding whitespace and replace multiple-spaces with a single space
4885 return s.replace(/\([^)]*\)|[\n\t]/g, ' ').replace(/(\s\s+)/g, ' ').replace(/^\s\s*/, '').replace(/\s\s*$/, '');
4886 }
4887
4888 function checkWeekday(weekdayStr, parsedInput, config) {
4889 if (weekdayStr) {
4890 // TODO: Replace the vanilla JS Date object with an indepentent day-of-week check.
4891 var weekdayProvided = indexOf$3(defaultLocaleWeekdaysShort).call(defaultLocaleWeekdaysShort, weekdayStr),
4892 weekdayActual = new Date(parsedInput[0], parsedInput[1], parsedInput[2]).getDay();
4893
4894 if (weekdayProvided !== weekdayActual) {
4895 getParsingFlags(config).weekdayMismatch = true;
4896 config._isValid = false;
4897 return false;
4898 }
4899 }
4900
4901 return true;
4902 }
4903
4904 var obsOffsets = {
4905 UT: 0,
4906 GMT: 0,
4907 EDT: -4 * 60,
4908 EST: -5 * 60,
4909 CDT: -5 * 60,
4910 CST: -6 * 60,
4911 MDT: -6 * 60,
4912 MST: -7 * 60,
4913 PDT: -7 * 60,
4914 PST: -8 * 60
4915 };
4916
4917 function calculateOffset(obsOffset, militaryOffset, numOffset) {
4918 if (obsOffset) {
4919 return obsOffsets[obsOffset];
4920 } else if (militaryOffset) {
4921 // the only allowed military tz is Z
4922 return 0;
4923 } else {
4924 var hm = _parseInt$3(numOffset, 10);
4925
4926 var m = hm % 100,
4927 h = (hm - m) / 100;
4928 return h * 60 + m;
4929 }
4930 } // date and time from ref 2822 format
4931
4932
4933 function configFromRFC2822(config) {
4934 var match = rfc2822.exec(preprocessRFC2822(config._i));
4935
4936 if (match) {
4937 var parsedArray = extractFromRFC2822Strings(match[4], match[3], match[2], match[5], match[6], match[7]);
4938
4939 if (!checkWeekday(match[1], parsedArray, config)) {
4940 return;
4941 }
4942
4943 config._a = parsedArray;
4944 config._tzm = calculateOffset(match[8], match[9], match[10]);
4945 config._d = createUTCDate.apply(null, config._a);
4946
4947 config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
4948
4949 getParsingFlags(config).rfc2822 = true;
4950 } else {
4951 config._isValid = false;
4952 }
4953 } // date from iso format or fallback
4954
4955
4956 function configFromString(config) {
4957 var matched = aspNetJsonRegex.exec(config._i);
4958
4959 if (matched !== null) {
4960 config._d = new Date(+matched[1]);
4961 return;
4962 }
4963
4964 configFromISO(config);
4965
4966 if (config._isValid === false) {
4967 delete config._isValid;
4968 } else {
4969 return;
4970 }
4971
4972 configFromRFC2822(config);
4973
4974 if (config._isValid === false) {
4975 delete config._isValid;
4976 } else {
4977 return;
4978 } // Final attempt, use Input Fallback
4979
4980
4981 hooks.createFromInputFallback(config);
4982 }
4983
4984 hooks.createFromInputFallback = deprecate('value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' + 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' + 'discouraged and will be removed in an upcoming major release. Please refer to ' + 'http://momentjs.com/guides/#/warnings/js-date/ for more info.', function (config) {
4985 config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
4986 }); // constant that refers to the ISO standard
4987
4988 hooks.ISO_8601 = function () {}; // constant that refers to the RFC 2822 form
4989
4990
4991 hooks.RFC_2822 = function () {}; // date from string and format string
4992
4993
4994 function configFromStringAndFormat(config) {
4995 var _context3; // TODO: Move this to another part of the creation flow to prevent circular deps
4996
4997
4998 if (config._f === hooks.ISO_8601) {
4999 configFromISO(config);
5000 return;
5001 }
5002
5003 if (config._f === hooks.RFC_2822) {
5004 configFromRFC2822(config);
5005 return;
5006 }
5007
5008 config._a = [];
5009 getParsingFlags(config).empty = true; // This array is used to make a Date, either with `new Date` or `Date.UTC`
5010
5011 var string = '' + config._i,
5012 i,
5013 parsedInput,
5014 tokens,
5015 token,
5016 skipped,
5017 stringLength = string.length,
5018 totalParsedInputLength = 0;
5019 tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];
5020
5021 for (i = 0; i < tokens.length; i++) {
5022 token = tokens[i];
5023 parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; // console.log('token', token, 'parsedInput', parsedInput,
5024 // 'regex', getParseRegexForToken(token, config));
5025
5026 if (parsedInput) {
5027 skipped = string.substr(0, indexOf$3(string).call(string, parsedInput));
5028
5029 if (skipped.length > 0) {
5030 getParsingFlags(config).unusedInput.push(skipped);
5031 }
5032
5033 string = slice$2(string).call(string, indexOf$3(string).call(string, parsedInput) + parsedInput.length);
5034 totalParsedInputLength += parsedInput.length;
5035 } // don't parse if it's not a known token
5036
5037
5038 if (formatTokenFunctions[token]) {
5039 if (parsedInput) {
5040 getParsingFlags(config).empty = false;
5041 } else {
5042 getParsingFlags(config).unusedTokens.push(token);
5043 }
5044
5045 addTimeToArrayFromToken(token, parsedInput, config);
5046 } else if (config._strict && !parsedInput) {
5047 getParsingFlags(config).unusedTokens.push(token);
5048 }
5049 } // add remaining unparsed input length to the string
5050
5051
5052 getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength;
5053
5054 if (string.length > 0) {
5055 getParsingFlags(config).unusedInput.push(string);
5056 } // clear _12h flag if hour is <= 12
5057
5058
5059 if (config._a[HOUR] <= 12 && getParsingFlags(config).bigHour === true && config._a[HOUR] > 0) {
5060 getParsingFlags(config).bigHour = undefined;
5061 }
5062
5063 getParsingFlags(config).parsedDateParts = slice$2(_context3 = config._a).call(_context3, 0);
5064 getParsingFlags(config).meridiem = config._meridiem; // handle meridiem
5065
5066 config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem);
5067 configFromArray(config);
5068 checkOverflow(config);
5069 }
5070
5071 function meridiemFixWrap(locale, hour, meridiem) {
5072 var isPm;
5073
5074 if (meridiem == null) {
5075 // nothing to do
5076 return hour;
5077 }
5078
5079 if (locale.meridiemHour != null) {
5080 return locale.meridiemHour(hour, meridiem);
5081 } else if (locale.isPM != null) {
5082 // Fallback
5083 isPm = locale.isPM(meridiem);
5084
5085 if (isPm && hour < 12) {
5086 hour += 12;
5087 }
5088
5089 if (!isPm && hour === 12) {
5090 hour = 0;
5091 }
5092
5093 return hour;
5094 } else {
5095 // this is not supposed to happen
5096 return hour;
5097 }
5098 } // date from string and array of format strings
5099
5100
5101 function configFromStringAndArray(config) {
5102 var tempConfig, bestMoment, scoreToBeat, i, currentScore;
5103
5104 if (config._f.length === 0) {
5105 getParsingFlags(config).invalidFormat = true;
5106 config._d = new Date(NaN);
5107 return;
5108 }
5109
5110 for (i = 0; i < config._f.length; i++) {
5111 currentScore = 0;
5112 tempConfig = copyConfig({}, config);
5113
5114 if (config._useUTC != null) {
5115 tempConfig._useUTC = config._useUTC;
5116 }
5117
5118 tempConfig._f = config._f[i];
5119 configFromStringAndFormat(tempConfig);
5120
5121 if (!isValid(tempConfig)) {
5122 continue;
5123 } // if there is any input that was not parsed add a penalty for that format
5124
5125
5126 currentScore += getParsingFlags(tempConfig).charsLeftOver; //or tokens
5127
5128 currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
5129 getParsingFlags(tempConfig).score = currentScore;
5130
5131 if (scoreToBeat == null || currentScore < scoreToBeat) {
5132 scoreToBeat = currentScore;
5133 bestMoment = tempConfig;
5134 }
5135 }
5136
5137 extend(config, bestMoment || tempConfig);
5138 }
5139
5140 function configFromObject(config) {
5141 if (config._d) {
5142 return;
5143 }
5144
5145 var i = normalizeObjectUnits(config._i);
5146 config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) {
5147 return obj && _parseInt$3(obj, 10);
5148 });
5149 configFromArray(config);
5150 }
5151
5152 function createFromConfig(config) {
5153 var res = new Moment(checkOverflow(prepareConfig(config)));
5154
5155 if (res._nextDay) {
5156 // Adding is smart enough around DST
5157 res.add(1, 'd');
5158 res._nextDay = undefined;
5159 }
5160
5161 return res;
5162 }
5163
5164 function prepareConfig(config) {
5165 var input = config._i,
5166 format = config._f;
5167 config._locale = config._locale || getLocale(config._l);
5168
5169 if (input === null || format === undefined && input === '') {
5170 return createInvalid({
5171 nullInput: true
5172 });
5173 }
5174
5175 if (typeof input === 'string') {
5176 config._i = input = config._locale.preparse(input);
5177 }
5178
5179 if (isMoment(input)) {
5180 return new Moment(checkOverflow(input));
5181 } else if (isDate(input)) {
5182 config._d = input;
5183 } else if (isArray(format)) {
5184 configFromStringAndArray(config);
5185 } else if (format) {
5186 configFromStringAndFormat(config);
5187 } else {
5188 configFromInput(config);
5189 }
5190
5191 if (!isValid(config)) {
5192 config._d = null;
5193 }
5194
5195 return config;
5196 }
5197
5198 function configFromInput(config) {
5199 var input = config._i;
5200
5201 if (isUndefined(input)) {
5202 config._d = new Date(hooks.now());
5203 } else if (isDate(input)) {
5204 config._d = new Date(input.valueOf());
5205 } else if (typeof input === 'string') {
5206 configFromString(config);
5207 } else if (isArray(input)) {
5208 config._a = map(slice$2(input).call(input, 0), function (obj) {
5209 return _parseInt$3(obj, 10);
5210 });
5211 configFromArray(config);
5212 } else if (isObject(input)) {
5213 configFromObject(config);
5214 } else if (isNumber(input)) {
5215 // from milliseconds
5216 config._d = new Date(input);
5217 } else {
5218 hooks.createFromInputFallback(config);
5219 }
5220 }
5221
5222 function createLocalOrUTC(input, format, locale, strict, isUTC) {
5223 var c = {};
5224
5225 if (locale === true || locale === false) {
5226 strict = locale;
5227 locale = undefined;
5228 }
5229
5230 if (isObject(input) && isObjectEmpty(input) || isArray(input) && input.length === 0) {
5231 input = undefined;
5232 } // object construction must be done this way.
5233 // https://github.com/moment/moment/issues/1423
5234
5235
5236 c._isAMomentObject = true;
5237 c._useUTC = c._isUTC = isUTC;
5238 c._l = locale;
5239 c._i = input;
5240 c._f = format;
5241 c._strict = strict;
5242 return createFromConfig(c);
5243 }
5244
5245 function createLocal(input, format, locale, strict) {
5246 return createLocalOrUTC(input, format, locale, strict, false);
5247 }
5248
5249 var prototypeMin = deprecate('moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/', function () {
5250 var other = createLocal.apply(null, arguments);
5251
5252 if (this.isValid() && other.isValid()) {
5253 return other < this ? this : other;
5254 } else {
5255 return createInvalid();
5256 }
5257 });
5258 var prototypeMax = deprecate('moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/', function () {
5259 var other = createLocal.apply(null, arguments);
5260
5261 if (this.isValid() && other.isValid()) {
5262 return other > this ? this : other;
5263 } else {
5264 return createInvalid();
5265 }
5266 }); // Pick a moment m from moments so that m[fn](other) is true for all
5267 // other. This relies on the function fn to be transitive.
5268 //
5269 // moments should either be an array of moment objects or an array, whose
5270 // first element is an array of moment objects.
5271
5272 function pickBy(fn, moments) {
5273 var res, i;
5274
5275 if (moments.length === 1 && isArray(moments[0])) {
5276 moments = moments[0];
5277 }
5278
5279 if (!moments.length) {
5280 return createLocal();
5281 }
5282
5283 res = moments[0];
5284
5285 for (i = 1; i < moments.length; ++i) {
5286 if (!moments[i].isValid() || moments[i][fn](res)) {
5287 res = moments[i];
5288 }
5289 }
5290
5291 return res;
5292 } // TODO: Use [].sort instead?
5293
5294
5295 function min() {
5296 var args = slice$2([]).call(arguments, 0);
5297 return pickBy('isBefore', args);
5298 }
5299
5300 function max() {
5301 var args = slice$2([]).call(arguments, 0);
5302 return pickBy('isAfter', args);
5303 }
5304
5305 var now = function now() {
5306 return now$2 ? now$2() : +new Date();
5307 };
5308
5309 var ordering = ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond'];
5310
5311 function isDurationValid(m) {
5312 for (var key in m) {
5313 if (!(indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])))) {
5314 return false;
5315 }
5316 }
5317
5318 var unitHasDecimal = false;
5319
5320 for (var i = 0; i < ordering.length; ++i) {
5321 if (m[ordering[i]]) {
5322 if (unitHasDecimal) {
5323 return false; // only allow non-integers for smallest unit
5324 }
5325
5326 if (_parseFloat$3(m[ordering[i]]) !== toInt(m[ordering[i]])) {
5327 unitHasDecimal = true;
5328 }
5329 }
5330 }
5331
5332 return true;
5333 }
5334
5335 function isValid$1() {
5336 return this._isValid;
5337 }
5338
5339 function createInvalid$1() {
5340 return createDuration(NaN);
5341 }
5342
5343 function Duration(duration) {
5344 var normalizedInput = normalizeObjectUnits(duration),
5345 years = normalizedInput.year || 0,
5346 quarters = normalizedInput.quarter || 0,
5347 months = normalizedInput.month || 0,
5348 weeks = normalizedInput.week || normalizedInput.isoWeek || 0,
5349 days = normalizedInput.day || 0,
5350 hours = normalizedInput.hour || 0,
5351 minutes = normalizedInput.minute || 0,
5352 seconds = normalizedInput.second || 0,
5353 milliseconds = normalizedInput.millisecond || 0;
5354 this._isValid = isDurationValid(normalizedInput); // representation for dateAddRemove
5355
5356 this._milliseconds = +milliseconds + seconds * 1e3 + // 1000
5357 minutes * 6e4 + // 1000 * 60
5358 hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
5359 // Because of dateAddRemove treats 24 hours as different from a
5360 // day when working around DST, we need to store them separately
5361
5362 this._days = +days + weeks * 7; // It is impossible to translate months into days without knowing
5363 // which months you are are talking about, so we have to store
5364 // it separately.
5365
5366 this._months = +months + quarters * 3 + years * 12;
5367 this._data = {};
5368 this._locale = getLocale();
5369
5370 this._bubble();
5371 }
5372
5373 function isDuration(obj) {
5374 return obj instanceof Duration;
5375 }
5376
5377 function absRound(number) {
5378 if (number < 0) {
5379 return Math.round(-1 * number) * -1;
5380 } else {
5381 return Math.round(number);
5382 }
5383 } // FORMATTING
5384
5385
5386 function offset(token, separator) {
5387 addFormatToken(token, 0, 0, function () {
5388 var offset = this.utcOffset();
5389 var sign = '+';
5390
5391 if (offset < 0) {
5392 offset = -offset;
5393 sign = '-';
5394 }
5395
5396 return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~offset % 60, 2);
5397 });
5398 }
5399
5400 offset('Z', ':');
5401 offset('ZZ', ''); // PARSING
5402
5403 addRegexToken('Z', matchShortOffset);
5404 addRegexToken('ZZ', matchShortOffset);
5405 addParseToken(['Z', 'ZZ'], function (input, array, config) {
5406 config._useUTC = true;
5407 config._tzm = offsetFromString(matchShortOffset, input);
5408 }); // HELPERS
5409 // timezone chunker
5410 // '+10:00' > ['10', '00']
5411 // '-1530' > ['-15', '30']
5412
5413 var chunkOffset = /([\+\-]|\d\d)/gi;
5414
5415 function offsetFromString(matcher, string) {
5416 var matches = (string || '').match(matcher);
5417
5418 if (matches === null) {
5419 return null;
5420 }
5421
5422 var chunk = matches[matches.length - 1] || [];
5423 var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
5424 var minutes = +(parts[1] * 60) + toInt(parts[2]);
5425 return minutes === 0 ? 0 : parts[0] === '+' ? minutes : -minutes;
5426 } // Return a moment from input, that is local/utc/zone equivalent to model.
5427
5428
5429 function cloneWithOffset(input, model) {
5430 var res, diff;
5431
5432 if (model._isUTC) {
5433 res = model.clone();
5434 diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf(); // Use low-level api, because this fn is low-level api.
5435
5436 res._d.setTime(res._d.valueOf() + diff);
5437
5438 hooks.updateOffset(res, false);
5439 return res;
5440 } else {
5441 return createLocal(input).local();
5442 }
5443 }
5444
5445 function getDateOffset(m) {
5446 // On Firefox.24 Date#getTimezoneOffset returns a floating point.
5447 // https://github.com/moment/moment/pull/1871
5448 return -Math.round(m._d.getTimezoneOffset() / 15) * 15;
5449 } // HOOKS
5450 // This function will be called whenever a moment is mutated.
5451 // It is intended to keep the offset in sync with the timezone.
5452
5453
5454 hooks.updateOffset = function () {}; // MOMENTS
5455 // keepLocalTime = true means only change the timezone, without
5456 // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
5457 // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
5458 // +0200, so we adjust the time as needed, to be valid.
5459 //
5460 // Keeping the time actually adds/subtracts (one hour)
5461 // from the actual represented time. That is why we call updateOffset
5462 // a second time. In case it wants us to change the offset again
5463 // _changeInProgress == true case, then we have to adjust, because
5464 // there is no such time in the given timezone.
5465
5466
5467 function getSetOffset(input, keepLocalTime, keepMinutes) {
5468 var offset = this._offset || 0,
5469 localAdjust;
5470
5471 if (!this.isValid()) {
5472 return input != null ? this : NaN;
5473 }
5474
5475 if (input != null) {
5476 if (typeof input === 'string') {
5477 input = offsetFromString(matchShortOffset, input);
5478
5479 if (input === null) {
5480 return this;
5481 }
5482 } else if (Math.abs(input) < 16 && !keepMinutes) {
5483 input = input * 60;
5484 }
5485
5486 if (!this._isUTC && keepLocalTime) {
5487 localAdjust = getDateOffset(this);
5488 }
5489
5490 this._offset = input;
5491 this._isUTC = true;
5492
5493 if (localAdjust != null) {
5494 this.add(localAdjust, 'm');
5495 }
5496
5497 if (offset !== input) {
5498 if (!keepLocalTime || this._changeInProgress) {
5499 addSubtract(this, createDuration(input - offset, 'm'), 1, false);
5500 } else if (!this._changeInProgress) {
5501 this._changeInProgress = true;
5502 hooks.updateOffset(this, true);
5503 this._changeInProgress = null;
5504 }
5505 }
5506
5507 return this;
5508 } else {
5509 return this._isUTC ? offset : getDateOffset(this);
5510 }
5511 }
5512
5513 function getSetZone(input, keepLocalTime) {
5514 if (input != null) {
5515 if (typeof input !== 'string') {
5516 input = -input;
5517 }
5518
5519 this.utcOffset(input, keepLocalTime);
5520 return this;
5521 } else {
5522 return -this.utcOffset();
5523 }
5524 }
5525
5526 function setOffsetToUTC(keepLocalTime) {
5527 return this.utcOffset(0, keepLocalTime);
5528 }
5529
5530 function setOffsetToLocal(keepLocalTime) {
5531 if (this._isUTC) {
5532 this.utcOffset(0, keepLocalTime);
5533 this._isUTC = false;
5534
5535 if (keepLocalTime) {
5536 this.subtract(getDateOffset(this), 'm');
5537 }
5538 }
5539
5540 return this;
5541 }
5542
5543 function setOffsetToParsedOffset() {
5544 if (this._tzm != null) {
5545 this.utcOffset(this._tzm, false, true);
5546 } else if (typeof this._i === 'string') {
5547 var tZone = offsetFromString(matchOffset, this._i);
5548
5549 if (tZone != null) {
5550 this.utcOffset(tZone);
5551 } else {
5552 this.utcOffset(0, true);
5553 }
5554 }
5555
5556 return this;
5557 }
5558
5559 function hasAlignedHourOffset(input) {
5560 if (!this.isValid()) {
5561 return false;
5562 }
5563
5564 input = input ? createLocal(input).utcOffset() : 0;
5565 return (this.utcOffset() - input) % 60 === 0;
5566 }
5567
5568 function isDaylightSavingTime() {
5569 return this.utcOffset() > this.clone().month(0).utcOffset() || this.utcOffset() > this.clone().month(5).utcOffset();
5570 }
5571
5572 function isDaylightSavingTimeShifted() {
5573 if (!isUndefined(this._isDSTShifted)) {
5574 return this._isDSTShifted;
5575 }
5576
5577 var c = {};
5578 copyConfig(c, this);
5579 c = prepareConfig(c);
5580
5581 if (c._a) {
5582 var other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
5583 this._isDSTShifted = this.isValid() && compareArrays(c._a, other.toArray()) > 0;
5584 } else {
5585 this._isDSTShifted = false;
5586 }
5587
5588 return this._isDSTShifted;
5589 }
5590
5591 function isLocal() {
5592 return this.isValid() ? !this._isUTC : false;
5593 }
5594
5595 function isUtcOffset() {
5596 return this.isValid() ? this._isUTC : false;
5597 }
5598
5599 function isUtc() {
5600 return this.isValid() ? this._isUTC && this._offset === 0 : false;
5601 } // ASP.NET json date format regex
5602
5603
5604 var aspNetRegex = /^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/; // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
5605 // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
5606 // and further modified to allow for strings containing both week and day
5607
5608 var isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
5609
5610 function createDuration(input, key) {
5611 var duration = input,
5612 // matching against regexp is expensive, do it on demand
5613 match = null,
5614 sign,
5615 ret,
5616 diffRes;
5617
5618 if (isDuration(input)) {
5619 duration = {
5620 ms: input._milliseconds,
5621 d: input._days,
5622 M: input._months
5623 };
5624 } else if (isNumber(input)) {
5625 duration = {};
5626
5627 if (key) {
5628 duration[key] = input;
5629 } else {
5630 duration.milliseconds = input;
5631 }
5632 } else if (!!(match = aspNetRegex.exec(input))) {
5633 sign = match[1] === '-' ? -1 : 1;
5634 duration = {
5635 y: 0,
5636 d: toInt(match[DATE]) * sign,
5637 h: toInt(match[HOUR]) * sign,
5638 m: toInt(match[MINUTE]) * sign,
5639 s: toInt(match[SECOND]) * sign,
5640 ms: toInt(absRound(match[MILLISECOND] * 1000)) * sign // the millisecond decimal point is included in the match
5641
5642 };
5643 } else if (!!(match = isoRegex.exec(input))) {
5644 sign = match[1] === '-' ? -1 : 1;
5645 duration = {
5646 y: parseIso(match[2], sign),
5647 M: parseIso(match[3], sign),
5648 w: parseIso(match[4], sign),
5649 d: parseIso(match[5], sign),
5650 h: parseIso(match[6], sign),
5651 m: parseIso(match[7], sign),
5652 s: parseIso(match[8], sign)
5653 };
5654 } else if (duration == null) {
5655 // checks for null or undefined
5656 duration = {};
5657 } else if (_typeof_1(duration) === 'object' && ('from' in duration || 'to' in duration)) {
5658 diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to));
5659 duration = {};
5660 duration.ms = diffRes.milliseconds;
5661 duration.M = diffRes.months;
5662 }
5663
5664 ret = new Duration(duration);
5665
5666 if (isDuration(input) && hasOwnProp(input, '_locale')) {
5667 ret._locale = input._locale;
5668 }
5669
5670 return ret;
5671 }
5672
5673 createDuration.fn = Duration.prototype;
5674 createDuration.invalid = createInvalid$1;
5675
5676 function parseIso(inp, sign) {
5677 // We'd normally use ~~inp for this, but unfortunately it also
5678 // converts floats to ints.
5679 // inp may be undefined, so careful calling replace on it.
5680 var res = inp && _parseFloat$3(inp.replace(',', '.')); // apply sign while we're at it
5681
5682
5683 return (isNaN(res) ? 0 : res) * sign;
5684 }
5685
5686 function positiveMomentsDifference(base, other) {
5687 var res = {};
5688 res.months = other.month() - base.month() + (other.year() - base.year()) * 12;
5689
5690 if (base.clone().add(res.months, 'M').isAfter(other)) {
5691 --res.months;
5692 }
5693
5694 res.milliseconds = +other - +base.clone().add(res.months, 'M');
5695 return res;
5696 }
5697
5698 function momentsDifference(base, other) {
5699 var res;
5700
5701 if (!(base.isValid() && other.isValid())) {
5702 return {
5703 milliseconds: 0,
5704 months: 0
5705 };
5706 }
5707
5708 other = cloneWithOffset(other, base);
5709
5710 if (base.isBefore(other)) {
5711 res = positiveMomentsDifference(base, other);
5712 } else {
5713 res = positiveMomentsDifference(other, base);
5714 res.milliseconds = -res.milliseconds;
5715 res.months = -res.months;
5716 }
5717
5718 return res;
5719 } // TODO: remove 'name' arg after deprecation is removed
5720
5721
5722 function createAdder(direction, name) {
5723 return function (val, period) {
5724 var dur, tmp; //invert the arguments, but complain about it
5725
5726 if (period !== null && !isNaN(+period)) {
5727 deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' + 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.');
5728 tmp = val;
5729 val = period;
5730 period = tmp;
5731 }
5732
5733 val = typeof val === 'string' ? +val : val;
5734 dur = createDuration(val, period);
5735 addSubtract(this, dur, direction);
5736 return this;
5737 };
5738 }
5739
5740 function addSubtract(mom, duration, isAdding, updateOffset) {
5741 var milliseconds = duration._milliseconds,
5742 days = absRound(duration._days),
5743 months = absRound(duration._months);
5744
5745 if (!mom.isValid()) {
5746 // No op
5747 return;
5748 }
5749
5750 updateOffset = updateOffset == null ? true : updateOffset;
5751
5752 if (months) {
5753 setMonth(mom, get(mom, 'Month') + months * isAdding);
5754 }
5755
5756 if (days) {
5757 set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);
5758 }
5759
5760 if (milliseconds) {
5761 mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
5762 }
5763
5764 if (updateOffset) {
5765 hooks.updateOffset(mom, days || months);
5766 }
5767 }
5768
5769 var add = createAdder(1, 'add');
5770 var subtract = createAdder(-1, 'subtract');
5771
5772 function getCalendarFormat(myMoment, now) {
5773 var diff = myMoment.diff(now, 'days', true);
5774 return diff < -6 ? 'sameElse' : diff < -1 ? 'lastWeek' : diff < 0 ? 'lastDay' : diff < 1 ? 'sameDay' : diff < 2 ? 'nextDay' : diff < 7 ? 'nextWeek' : 'sameElse';
5775 }
5776
5777 function calendar$1(time, formats) {
5778 // We want to compare the start of today, vs this.
5779 // Getting start-of-today depends on whether we're local/utc/offset or not.
5780 var now = time || createLocal(),
5781 sod = cloneWithOffset(now, this).startOf('day'),
5782 format = hooks.calendarFormat(this, sod) || 'sameElse';
5783 var output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]);
5784 return this.format(output || this.localeData().calendar(format, this, createLocal(now)));
5785 }
5786
5787 function clone() {
5788 return new Moment(this);
5789 }
5790
5791 function isAfter(input, units) {
5792 var localInput = isMoment(input) ? input : createLocal(input);
5793
5794 if (!(this.isValid() && localInput.isValid())) {
5795 return false;
5796 }
5797
5798 units = normalizeUnits(units) || 'millisecond';
5799
5800 if (units === 'millisecond') {
5801 return this.valueOf() > localInput.valueOf();
5802 } else {
5803 return localInput.valueOf() < this.clone().startOf(units).valueOf();
5804 }
5805 }
5806
5807 function isBefore(input, units) {
5808 var localInput = isMoment(input) ? input : createLocal(input);
5809
5810 if (!(this.isValid() && localInput.isValid())) {
5811 return false;
5812 }
5813
5814 units = normalizeUnits(units) || 'millisecond';
5815
5816 if (units === 'millisecond') {
5817 return this.valueOf() < localInput.valueOf();
5818 } else {
5819 return this.clone().endOf(units).valueOf() < localInput.valueOf();
5820 }
5821 }
5822
5823 function isBetween(from, to, units, inclusivity) {
5824 var localFrom = isMoment(from) ? from : createLocal(from),
5825 localTo = isMoment(to) ? to : createLocal(to);
5826
5827 if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) {
5828 return false;
5829 }
5830
5831 inclusivity = inclusivity || '()';
5832 return (inclusivity[0] === '(' ? this.isAfter(localFrom, units) : !this.isBefore(localFrom, units)) && (inclusivity[1] === ')' ? this.isBefore(localTo, units) : !this.isAfter(localTo, units));
5833 }
5834
5835 function isSame(input, units) {
5836 var localInput = isMoment(input) ? input : createLocal(input),
5837 inputMs;
5838
5839 if (!(this.isValid() && localInput.isValid())) {
5840 return false;
5841 }
5842
5843 units = normalizeUnits(units) || 'millisecond';
5844
5845 if (units === 'millisecond') {
5846 return this.valueOf() === localInput.valueOf();
5847 } else {
5848 inputMs = localInput.valueOf();
5849 return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf();
5850 }
5851 }
5852
5853 function isSameOrAfter(input, units) {
5854 return this.isSame(input, units) || this.isAfter(input, units);
5855 }
5856
5857 function isSameOrBefore(input, units) {
5858 return this.isSame(input, units) || this.isBefore(input, units);
5859 }
5860
5861 function diff(input, units, asFloat) {
5862 var that, zoneDelta, output;
5863
5864 if (!this.isValid()) {
5865 return NaN;
5866 }
5867
5868 that = cloneWithOffset(input, this);
5869
5870 if (!that.isValid()) {
5871 return NaN;
5872 }
5873
5874 zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
5875 units = normalizeUnits(units);
5876
5877 switch (units) {
5878 case 'year':
5879 output = monthDiff(this, that) / 12;
5880 break;
5881
5882 case 'month':
5883 output = monthDiff(this, that);
5884 break;
5885
5886 case 'quarter':
5887 output = monthDiff(this, that) / 3;
5888 break;
5889
5890 case 'second':
5891 output = (this - that) / 1e3;
5892 break;
5893 // 1000
5894
5895 case 'minute':
5896 output = (this - that) / 6e4;
5897 break;
5898 // 1000 * 60
5899
5900 case 'hour':
5901 output = (this - that) / 36e5;
5902 break;
5903 // 1000 * 60 * 60
5904
5905 case 'day':
5906 output = (this - that - zoneDelta) / 864e5;
5907 break;
5908 // 1000 * 60 * 60 * 24, negate dst
5909
5910 case 'week':
5911 output = (this - that - zoneDelta) / 6048e5;
5912 break;
5913 // 1000 * 60 * 60 * 24 * 7, negate dst
5914
5915 default:
5916 output = this - that;
5917 }
5918
5919 return asFloat ? output : absFloor(output);
5920 }
5921
5922 function monthDiff(a, b) {
5923 // difference in months
5924 var wholeMonthDiff = (b.year() - a.year()) * 12 + (b.month() - a.month()),
5925 // b is in (anchor - 1 month, anchor + 1 month)
5926 anchor = a.clone().add(wholeMonthDiff, 'months'),
5927 anchor2,
5928 adjust;
5929
5930 if (b - anchor < 0) {
5931 anchor2 = a.clone().add(wholeMonthDiff - 1, 'months'); // linear across the month
5932
5933 adjust = (b - anchor) / (anchor - anchor2);
5934 } else {
5935 anchor2 = a.clone().add(wholeMonthDiff + 1, 'months'); // linear across the month
5936
5937 adjust = (b - anchor) / (anchor2 - anchor);
5938 } //check for negative zero, return zero if negative zero
5939
5940
5941 return -(wholeMonthDiff + adjust) || 0;
5942 }
5943
5944 hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
5945 hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';
5946
5947 function toString() {
5948 return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
5949 }
5950
5951 function toISOString(keepOffset) {
5952 if (!this.isValid()) {
5953 return null;
5954 }
5955
5956 var utc = keepOffset !== true;
5957 var m = utc ? this.clone().utc() : this;
5958
5959 if (m.year() < 0 || m.year() > 9999) {
5960 return formatMoment(m, utc ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ');
5961 }
5962
5963 if (isFunction(Date.prototype.toISOString)) {
5964 // native implementation is ~50x faster, use it when we can
5965 if (utc) {
5966 return this.toDate().toISOString();
5967 } else {
5968 return new Date(this.valueOf() + this.utcOffset() * 60 * 1000).toISOString().replace('Z', formatMoment(m, 'Z'));
5969 }
5970 }
5971
5972 return formatMoment(m, utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ');
5973 }
5974 /**
5975 * Return a human readable representation of a moment that can
5976 * also be evaluated to get a new moment which is the same
5977 *
5978 * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
5979 */
5980
5981
5982 function inspect() {
5983 if (!this.isValid()) {
5984 return 'moment.invalid(/* ' + this._i + ' */)';
5985 }
5986
5987 var func = 'moment';
5988 var zone = '';
5989
5990 if (!this.isLocal()) {
5991 func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
5992 zone = 'Z';
5993 }
5994
5995 var prefix = '[' + func + '("]';
5996 var year = 0 <= this.year() && this.year() <= 9999 ? 'YYYY' : 'YYYYYY';
5997 var datetime = '-MM-DD[T]HH:mm:ss.SSS';
5998 var suffix = zone + '[")]';
5999 return this.format(prefix + year + datetime + suffix);
6000 }
6001
6002 function format(inputString) {
6003 if (!inputString) {
6004 inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat;
6005 }
6006
6007 var output = formatMoment(this, inputString);
6008 return this.localeData().postformat(output);
6009 }
6010
6011 function from(time, withoutSuffix) {
6012 if (this.isValid() && (isMoment(time) && time.isValid() || createLocal(time).isValid())) {
6013 return createDuration({
6014 to: this,
6015 from: time
6016 }).locale(this.locale()).humanize(!withoutSuffix);
6017 } else {
6018 return this.localeData().invalidDate();
6019 }
6020 }
6021
6022 function fromNow(withoutSuffix) {
6023 return this.from(createLocal(), withoutSuffix);
6024 }
6025
6026 function to(time, withoutSuffix) {
6027 if (this.isValid() && (isMoment(time) && time.isValid() || createLocal(time).isValid())) {
6028 return createDuration({
6029 from: this,
6030 to: time
6031 }).locale(this.locale()).humanize(!withoutSuffix);
6032 } else {
6033 return this.localeData().invalidDate();
6034 }
6035 }
6036
6037 function toNow(withoutSuffix) {
6038 return this.to(createLocal(), withoutSuffix);
6039 } // If passed a locale key, it will set the locale for this
6040 // instance. Otherwise, it will return the locale configuration
6041 // variables for this instance.
6042
6043
6044 function locale(key) {
6045 var newLocaleData;
6046
6047 if (key === undefined) {
6048 return this._locale._abbr;
6049 } else {
6050 newLocaleData = getLocale(key);
6051
6052 if (newLocaleData != null) {
6053 this._locale = newLocaleData;
6054 }
6055
6056 return this;
6057 }
6058 }
6059
6060 var lang = deprecate('moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', function (key) {
6061 if (key === undefined) {
6062 return this.localeData();
6063 } else {
6064 return this.locale(key);
6065 }
6066 });
6067
6068 function localeData() {
6069 return this._locale;
6070 }
6071
6072 var MS_PER_SECOND = 1000;
6073 var MS_PER_MINUTE = 60 * MS_PER_SECOND;
6074 var MS_PER_HOUR = 60 * MS_PER_MINUTE;
6075 var MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR; // actual modulo - handles negative numbers (for dates before 1970):
6076
6077 function mod$1(dividend, divisor) {
6078 return (dividend % divisor + divisor) % divisor;
6079 }
6080
6081 function localStartOfDate(y, m, d) {
6082 // the date constructor remaps years 0-99 to 1900-1999
6083 if (y < 100 && y >= 0) {
6084 // preserve leap years using a full 400 year cycle, then reset
6085 return new Date(y + 400, m, d) - MS_PER_400_YEARS;
6086 } else {
6087 return new Date(y, m, d).valueOf();
6088 }
6089 }
6090
6091 function utcStartOfDate(y, m, d) {
6092 // Date.UTC remaps years 0-99 to 1900-1999
6093 if (y < 100 && y >= 0) {
6094 // preserve leap years using a full 400 year cycle, then reset
6095 return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS;
6096 } else {
6097 return Date.UTC(y, m, d);
6098 }
6099 }
6100
6101 function startOf(units) {
6102 var time;
6103 units = normalizeUnits(units);
6104
6105 if (units === undefined || units === 'millisecond' || !this.isValid()) {
6106 return this;
6107 }
6108
6109 var startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
6110
6111 switch (units) {
6112 case 'year':
6113 time = startOfDate(this.year(), 0, 1);
6114 break;
6115
6116 case 'quarter':
6117 time = startOfDate(this.year(), this.month() - this.month() % 3, 1);
6118 break;
6119
6120 case 'month':
6121 time = startOfDate(this.year(), this.month(), 1);
6122 break;
6123
6124 case 'week':
6125 time = startOfDate(this.year(), this.month(), this.date() - this.weekday());
6126 break;
6127
6128 case 'isoWeek':
6129 time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1));
6130 break;
6131
6132 case 'day':
6133 case 'date':
6134 time = startOfDate(this.year(), this.month(), this.date());
6135 break;
6136
6137 case 'hour':
6138 time = this._d.valueOf();
6139 time -= mod$1(time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR);
6140 break;
6141
6142 case 'minute':
6143 time = this._d.valueOf();
6144 time -= mod$1(time, MS_PER_MINUTE);
6145 break;
6146
6147 case 'second':
6148 time = this._d.valueOf();
6149 time -= mod$1(time, MS_PER_SECOND);
6150 break;
6151 }
6152
6153 this._d.setTime(time);
6154
6155 hooks.updateOffset(this, true);
6156 return this;
6157 }
6158
6159 function endOf(units) {
6160 var time;
6161 units = normalizeUnits(units);
6162
6163 if (units === undefined || units === 'millisecond' || !this.isValid()) {
6164 return this;
6165 }
6166
6167 var startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
6168
6169 switch (units) {
6170 case 'year':
6171 time = startOfDate(this.year() + 1, 0, 1) - 1;
6172 break;
6173
6174 case 'quarter':
6175 time = startOfDate(this.year(), this.month() - this.month() % 3 + 3, 1) - 1;
6176 break;
6177
6178 case 'month':
6179 time = startOfDate(this.year(), this.month() + 1, 1) - 1;
6180 break;
6181
6182 case 'week':
6183 time = startOfDate(this.year(), this.month(), this.date() - this.weekday() + 7) - 1;
6184 break;
6185
6186 case 'isoWeek':
6187 time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1) + 7) - 1;
6188 break;
6189
6190 case 'day':
6191 case 'date':
6192 time = startOfDate(this.year(), this.month(), this.date() + 1) - 1;
6193 break;
6194
6195 case 'hour':
6196 time = this._d.valueOf();
6197 time += MS_PER_HOUR - mod$1(time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR) - 1;
6198 break;
6199
6200 case 'minute':
6201 time = this._d.valueOf();
6202 time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1;
6203 break;
6204
6205 case 'second':
6206 time = this._d.valueOf();
6207 time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1;
6208 break;
6209 }
6210
6211 this._d.setTime(time);
6212
6213 hooks.updateOffset(this, true);
6214 return this;
6215 }
6216
6217 function valueOf() {
6218 return this._d.valueOf() - (this._offset || 0) * 60000;
6219 }
6220
6221 function unix() {
6222 return Math.floor(this.valueOf() / 1000);
6223 }
6224
6225 function toDate() {
6226 return new Date(this.valueOf());
6227 }
6228
6229 function toArray() {
6230 var m = this;
6231 return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()];
6232 }
6233
6234 function toObject() {
6235 var m = this;
6236 return {
6237 years: m.year(),
6238 months: m.month(),
6239 date: m.date(),
6240 hours: m.hours(),
6241 minutes: m.minutes(),
6242 seconds: m.seconds(),
6243 milliseconds: m.milliseconds()
6244 };
6245 }
6246
6247 function toJSON() {
6248 // new Date(NaN).toJSON() === null
6249 return this.isValid() ? this.toISOString() : null;
6250 }
6251
6252 function isValid$2() {
6253 return isValid(this);
6254 }
6255
6256 function parsingFlags() {
6257 return extend({}, getParsingFlags(this));
6258 }
6259
6260 function invalidAt() {
6261 return getParsingFlags(this).overflow;
6262 }
6263
6264 function creationData() {
6265 return {
6266 input: this._i,
6267 format: this._f,
6268 locale: this._locale,
6269 isUTC: this._isUTC,
6270 strict: this._strict
6271 };
6272 } // FORMATTING
6273
6274
6275 addFormatToken(0, ['gg', 2], 0, function () {
6276 return this.weekYear() % 100;
6277 });
6278 addFormatToken(0, ['GG', 2], 0, function () {
6279 return this.isoWeekYear() % 100;
6280 });
6281
6282 function addWeekYearFormatToken(token, getter) {
6283 addFormatToken(0, [token, token.length], 0, getter);
6284 }
6285
6286 addWeekYearFormatToken('gggg', 'weekYear');
6287 addWeekYearFormatToken('ggggg', 'weekYear');
6288 addWeekYearFormatToken('GGGG', 'isoWeekYear');
6289 addWeekYearFormatToken('GGGGG', 'isoWeekYear'); // ALIASES
6290
6291 addUnitAlias('weekYear', 'gg');
6292 addUnitAlias('isoWeekYear', 'GG'); // PRIORITY
6293
6294 addUnitPriority('weekYear', 1);
6295 addUnitPriority('isoWeekYear', 1); // PARSING
6296
6297 addRegexToken('G', matchSigned);
6298 addRegexToken('g', matchSigned);
6299 addRegexToken('GG', match1to2, match2);
6300 addRegexToken('gg', match1to2, match2);
6301 addRegexToken('GGGG', match1to4, match4);
6302 addRegexToken('gggg', match1to4, match4);
6303 addRegexToken('GGGGG', match1to6, match6);
6304 addRegexToken('ggggg', match1to6, match6);
6305 addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) {
6306 week[token.substr(0, 2)] = toInt(input);
6307 });
6308 addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
6309 week[token] = hooks.parseTwoDigitYear(input);
6310 }); // MOMENTS
6311
6312 function getSetWeekYear(input) {
6313 return getSetWeekYearHelper.call(this, input, this.week(), this.weekday(), this.localeData()._week.dow, this.localeData()._week.doy);
6314 }
6315
6316 function getSetISOWeekYear(input) {
6317 return getSetWeekYearHelper.call(this, input, this.isoWeek(), this.isoWeekday(), 1, 4);
6318 }
6319
6320 function getISOWeeksInYear() {
6321 return weeksInYear(this.year(), 1, 4);
6322 }
6323
6324 function getWeeksInYear() {
6325 var weekInfo = this.localeData()._week;
6326
6327 return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
6328 }
6329
6330 function getSetWeekYearHelper(input, week, weekday, dow, doy) {
6331 var weeksTarget;
6332
6333 if (input == null) {
6334 return weekOfYear(this, dow, doy).year;
6335 } else {
6336 weeksTarget = weeksInYear(input, dow, doy);
6337
6338 if (week > weeksTarget) {
6339 week = weeksTarget;
6340 }
6341
6342 return setWeekAll.call(this, input, week, weekday, dow, doy);
6343 }
6344 }
6345
6346 function setWeekAll(weekYear, week, weekday, dow, doy) {
6347 var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
6348 date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
6349 this.year(date.getUTCFullYear());
6350 this.month(date.getUTCMonth());
6351 this.date(date.getUTCDate());
6352 return this;
6353 } // FORMATTING
6354
6355
6356 addFormatToken('Q', 0, 'Qo', 'quarter'); // ALIASES
6357
6358 addUnitAlias('quarter', 'Q'); // PRIORITY
6359
6360 addUnitPriority('quarter', 7); // PARSING
6361
6362 addRegexToken('Q', match1);
6363 addParseToken('Q', function (input, array) {
6364 array[MONTH] = (toInt(input) - 1) * 3;
6365 }); // MOMENTS
6366
6367 function getSetQuarter(input) {
6368 return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
6369 } // FORMATTING
6370
6371
6372 addFormatToken('D', ['DD', 2], 'Do', 'date'); // ALIASES
6373
6374 addUnitAlias('date', 'D'); // PRIORITY
6375
6376 addUnitPriority('date', 9); // PARSING
6377
6378 addRegexToken('D', match1to2);
6379 addRegexToken('DD', match1to2, match2);
6380 addRegexToken('Do', function (isStrict, locale) {
6381 // TODO: Remove "ordinalParse" fallback in next major release.
6382 return isStrict ? locale._dayOfMonthOrdinalParse || locale._ordinalParse : locale._dayOfMonthOrdinalParseLenient;
6383 });
6384 addParseToken(['D', 'DD'], DATE);
6385 addParseToken('Do', function (input, array) {
6386 array[DATE] = toInt(input.match(match1to2)[0]);
6387 }); // MOMENTS
6388
6389 var getSetDayOfMonth = makeGetSet('Date', true); // FORMATTING
6390
6391 addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear'); // ALIASES
6392
6393 addUnitAlias('dayOfYear', 'DDD'); // PRIORITY
6394
6395 addUnitPriority('dayOfYear', 4); // PARSING
6396
6397 addRegexToken('DDD', match1to3);
6398 addRegexToken('DDDD', match3);
6399 addParseToken(['DDD', 'DDDD'], function (input, array, config) {
6400 config._dayOfYear = toInt(input);
6401 }); // HELPERS
6402 // MOMENTS
6403
6404 function getSetDayOfYear(input) {
6405 var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1;
6406 return input == null ? dayOfYear : this.add(input - dayOfYear, 'd');
6407 } // FORMATTING
6408
6409
6410 addFormatToken('m', ['mm', 2], 0, 'minute'); // ALIASES
6411
6412 addUnitAlias('minute', 'm'); // PRIORITY
6413
6414 addUnitPriority('minute', 14); // PARSING
6415
6416 addRegexToken('m', match1to2);
6417 addRegexToken('mm', match1to2, match2);
6418 addParseToken(['m', 'mm'], MINUTE); // MOMENTS
6419
6420 var getSetMinute = makeGetSet('Minutes', false); // FORMATTING
6421
6422 addFormatToken('s', ['ss', 2], 0, 'second'); // ALIASES
6423
6424 addUnitAlias('second', 's'); // PRIORITY
6425
6426 addUnitPriority('second', 15); // PARSING
6427
6428 addRegexToken('s', match1to2);
6429 addRegexToken('ss', match1to2, match2);
6430 addParseToken(['s', 'ss'], SECOND); // MOMENTS
6431
6432 var getSetSecond = makeGetSet('Seconds', false); // FORMATTING
6433
6434 addFormatToken('S', 0, 0, function () {
6435 return ~~(this.millisecond() / 100);
6436 });
6437 addFormatToken(0, ['SS', 2], 0, function () {
6438 return ~~(this.millisecond() / 10);
6439 });
6440 addFormatToken(0, ['SSS', 3], 0, 'millisecond');
6441 addFormatToken(0, ['SSSS', 4], 0, function () {
6442 return this.millisecond() * 10;
6443 });
6444 addFormatToken(0, ['SSSSS', 5], 0, function () {
6445 return this.millisecond() * 100;
6446 });
6447 addFormatToken(0, ['SSSSSS', 6], 0, function () {
6448 return this.millisecond() * 1000;
6449 });
6450 addFormatToken(0, ['SSSSSSS', 7], 0, function () {
6451 return this.millisecond() * 10000;
6452 });
6453 addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
6454 return this.millisecond() * 100000;
6455 });
6456 addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
6457 return this.millisecond() * 1000000;
6458 }); // ALIASES
6459
6460 addUnitAlias('millisecond', 'ms'); // PRIORITY
6461
6462 addUnitPriority('millisecond', 16); // PARSING
6463
6464 addRegexToken('S', match1to3, match1);
6465 addRegexToken('SS', match1to3, match2);
6466 addRegexToken('SSS', match1to3, match3);
6467 var token;
6468
6469 for (token = 'SSSS'; token.length <= 9; token += 'S') {
6470 addRegexToken(token, matchUnsigned);
6471 }
6472
6473 function parseMs(input, array) {
6474 array[MILLISECOND] = toInt(('0.' + input) * 1000);
6475 }
6476
6477 for (token = 'S'; token.length <= 9; token += 'S') {
6478 addParseToken(token, parseMs);
6479 } // MOMENTS
6480
6481
6482 var getSetMillisecond = makeGetSet('Milliseconds', false); // FORMATTING
6483
6484 addFormatToken('z', 0, 0, 'zoneAbbr');
6485 addFormatToken('zz', 0, 0, 'zoneName'); // MOMENTS
6486
6487 function getZoneAbbr() {
6488 return this._isUTC ? 'UTC' : '';
6489 }
6490
6491 function getZoneName() {
6492 return this._isUTC ? 'Coordinated Universal Time' : '';
6493 }
6494
6495 var proto = Moment.prototype;
6496 proto.add = add;
6497 proto.calendar = calendar$1;
6498 proto.clone = clone;
6499 proto.diff = diff;
6500 proto.endOf = endOf;
6501 proto.format = format;
6502 proto.from = from;
6503 proto.fromNow = fromNow;
6504 proto.to = to;
6505 proto.toNow = toNow;
6506 proto.get = stringGet;
6507 proto.invalidAt = invalidAt;
6508 proto.isAfter = isAfter;
6509 proto.isBefore = isBefore;
6510 proto.isBetween = isBetween;
6511 proto.isSame = isSame;
6512 proto.isSameOrAfter = isSameOrAfter;
6513 proto.isSameOrBefore = isSameOrBefore;
6514 proto.isValid = isValid$2;
6515 proto.lang = lang;
6516 proto.locale = locale;
6517 proto.localeData = localeData;
6518 proto.max = prototypeMax;
6519 proto.min = prototypeMin;
6520 proto.parsingFlags = parsingFlags;
6521 proto.set = stringSet;
6522 proto.startOf = startOf;
6523 proto.subtract = subtract;
6524 proto.toArray = toArray;
6525 proto.toObject = toObject;
6526 proto.toDate = toDate;
6527 proto.toISOString = toISOString;
6528 proto.inspect = inspect;
6529 proto.toJSON = toJSON;
6530 proto.toString = toString;
6531 proto.unix = unix;
6532 proto.valueOf = valueOf;
6533 proto.creationData = creationData;
6534 proto.year = getSetYear;
6535 proto.isLeapYear = getIsLeapYear;
6536 proto.weekYear = getSetWeekYear;
6537 proto.isoWeekYear = getSetISOWeekYear;
6538 proto.quarter = proto.quarters = getSetQuarter;
6539 proto.month = getSetMonth;
6540 proto.daysInMonth = getDaysInMonth;
6541 proto.week = proto.weeks = getSetWeek;
6542 proto.isoWeek = proto.isoWeeks = getSetISOWeek;
6543 proto.weeksInYear = getWeeksInYear;
6544 proto.isoWeeksInYear = getISOWeeksInYear;
6545 proto.date = getSetDayOfMonth;
6546 proto.day = proto.days = getSetDayOfWeek;
6547 proto.weekday = getSetLocaleDayOfWeek;
6548 proto.isoWeekday = getSetISODayOfWeek;
6549 proto.dayOfYear = getSetDayOfYear;
6550 proto.hour = proto.hours = getSetHour;
6551 proto.minute = proto.minutes = getSetMinute;
6552 proto.second = proto.seconds = getSetSecond;
6553 proto.millisecond = proto.milliseconds = getSetMillisecond;
6554 proto.utcOffset = getSetOffset;
6555 proto.utc = setOffsetToUTC;
6556 proto.local = setOffsetToLocal;
6557 proto.parseZone = setOffsetToParsedOffset;
6558 proto.hasAlignedHourOffset = hasAlignedHourOffset;
6559 proto.isDST = isDaylightSavingTime;
6560 proto.isLocal = isLocal;
6561 proto.isUtcOffset = isUtcOffset;
6562 proto.isUtc = isUtc;
6563 proto.isUTC = isUtc;
6564 proto.zoneAbbr = getZoneAbbr;
6565 proto.zoneName = getZoneName;
6566 proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth);
6567 proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth);
6568 proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear);
6569 proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone);
6570 proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted);
6571
6572 function createUnix(input) {
6573 return createLocal(input * 1000);
6574 }
6575
6576 function createInZone() {
6577 return createLocal.apply(null, arguments).parseZone();
6578 }
6579
6580 function preParsePostFormat(string) {
6581 return string;
6582 }
6583
6584 var proto$1 = Locale.prototype;
6585 proto$1.calendar = calendar;
6586 proto$1.longDateFormat = longDateFormat;
6587 proto$1.invalidDate = invalidDate;
6588 proto$1.ordinal = ordinal;
6589 proto$1.preparse = preParsePostFormat;
6590 proto$1.postformat = preParsePostFormat;
6591 proto$1.relativeTime = relativeTime;
6592 proto$1.pastFuture = pastFuture;
6593 proto$1.set = set;
6594 proto$1.months = localeMonths;
6595 proto$1.monthsShort = localeMonthsShort;
6596 proto$1.monthsParse = localeMonthsParse;
6597 proto$1.monthsRegex = monthsRegex;
6598 proto$1.monthsShortRegex = monthsShortRegex;
6599 proto$1.week = localeWeek;
6600 proto$1.firstDayOfYear = localeFirstDayOfYear;
6601 proto$1.firstDayOfWeek = localeFirstDayOfWeek;
6602 proto$1.weekdays = localeWeekdays;
6603 proto$1.weekdaysMin = localeWeekdaysMin;
6604 proto$1.weekdaysShort = localeWeekdaysShort;
6605 proto$1.weekdaysParse = localeWeekdaysParse;
6606 proto$1.weekdaysRegex = weekdaysRegex;
6607 proto$1.weekdaysShortRegex = weekdaysShortRegex;
6608 proto$1.weekdaysMinRegex = weekdaysMinRegex;
6609 proto$1.isPM = localeIsPM;
6610 proto$1.meridiem = localeMeridiem;
6611
6612 function get$1(format, index, field, setter) {
6613 var locale = getLocale();
6614 var utc = createUTC().set(setter, index);
6615 return locale[field](utc, format);
6616 }
6617
6618 function listMonthsImpl(format, index, field) {
6619 if (isNumber(format)) {
6620 index = format;
6621 format = undefined;
6622 }
6623
6624 format = format || '';
6625
6626 if (index != null) {
6627 return get$1(format, index, field, 'month');
6628 }
6629
6630 var i;
6631 var out = [];
6632
6633 for (i = 0; i < 12; i++) {
6634 out[i] = get$1(format, i, field, 'month');
6635 }
6636
6637 return out;
6638 } // ()
6639 // (5)
6640 // (fmt, 5)
6641 // (fmt)
6642 // (true)
6643 // (true, 5)
6644 // (true, fmt, 5)
6645 // (true, fmt)
6646
6647
6648 function listWeekdaysImpl(localeSorted, format, index, field) {
6649 if (typeof localeSorted === 'boolean') {
6650 if (isNumber(format)) {
6651 index = format;
6652 format = undefined;
6653 }
6654
6655 format = format || '';
6656 } else {
6657 format = localeSorted;
6658 index = format;
6659 localeSorted = false;
6660
6661 if (isNumber(format)) {
6662 index = format;
6663 format = undefined;
6664 }
6665
6666 format = format || '';
6667 }
6668
6669 var locale = getLocale(),
6670 shift = localeSorted ? locale._week.dow : 0;
6671
6672 if (index != null) {
6673 return get$1(format, (index + shift) % 7, field, 'day');
6674 }
6675
6676 var i;
6677 var out = [];
6678
6679 for (i = 0; i < 7; i++) {
6680 out[i] = get$1(format, (i + shift) % 7, field, 'day');
6681 }
6682
6683 return out;
6684 }
6685
6686 function listMonths(format, index) {
6687 return listMonthsImpl(format, index, 'months');
6688 }
6689
6690 function listMonthsShort(format, index) {
6691 return listMonthsImpl(format, index, 'monthsShort');
6692 }
6693
6694 function listWeekdays(localeSorted, format, index) {
6695 return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
6696 }
6697
6698 function listWeekdaysShort(localeSorted, format, index) {
6699 return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
6700 }
6701
6702 function listWeekdaysMin(localeSorted, format, index) {
6703 return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
6704 }
6705
6706 getSetGlobalLocale('en', {
6707 dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
6708 ordinal: function ordinal(number) {
6709 var b = number % 10,
6710 output = toInt(number % 100 / 10) === 1 ? 'th' : b === 1 ? 'st' : b === 2 ? 'nd' : b === 3 ? 'rd' : 'th';
6711 return number + output;
6712 }
6713 }); // Side effect imports
6714
6715 hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale);
6716 hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', getLocale);
6717 var mathAbs = Math.abs;
6718
6719 function abs() {
6720 var data = this._data;
6721 this._milliseconds = mathAbs(this._milliseconds);
6722 this._days = mathAbs(this._days);
6723 this._months = mathAbs(this._months);
6724 data.milliseconds = mathAbs(data.milliseconds);
6725 data.seconds = mathAbs(data.seconds);
6726 data.minutes = mathAbs(data.minutes);
6727 data.hours = mathAbs(data.hours);
6728 data.months = mathAbs(data.months);
6729 data.years = mathAbs(data.years);
6730 return this;
6731 }
6732
6733 function addSubtract$1(duration, input, value, direction) {
6734 var other = createDuration(input, value);
6735 duration._milliseconds += direction * other._milliseconds;
6736 duration._days += direction * other._days;
6737 duration._months += direction * other._months;
6738 return duration._bubble();
6739 } // supports only 2.0-style add(1, 's') or add(duration)
6740
6741
6742 function add$1(input, value) {
6743 return addSubtract$1(this, input, value, 1);
6744 } // supports only 2.0-style subtract(1, 's') or subtract(duration)
6745
6746
6747 function subtract$1(input, value) {
6748 return addSubtract$1(this, input, value, -1);
6749 }
6750
6751 function absCeil(number) {
6752 if (number < 0) {
6753 return Math.floor(number);
6754 } else {
6755 return Math.ceil(number);
6756 }
6757 }
6758
6759 function bubble() {
6760 var milliseconds = this._milliseconds;
6761 var days = this._days;
6762 var months = this._months;
6763 var data = this._data;
6764 var seconds, minutes, hours, years, monthsFromDays; // if we have a mix of positive and negative values, bubble down first
6765 // check: https://github.com/moment/moment/issues/2166
6766
6767 if (!(milliseconds >= 0 && days >= 0 && months >= 0 || milliseconds <= 0 && days <= 0 && months <= 0)) {
6768 milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
6769 days = 0;
6770 months = 0;
6771 } // The following code bubbles up values, see the tests for
6772 // examples of what that means.
6773
6774
6775 data.milliseconds = milliseconds % 1000;
6776 seconds = absFloor(milliseconds / 1000);
6777 data.seconds = seconds % 60;
6778 minutes = absFloor(seconds / 60);
6779 data.minutes = minutes % 60;
6780 hours = absFloor(minutes / 60);
6781 data.hours = hours % 24;
6782 days += absFloor(hours / 24); // convert days to months
6783
6784 monthsFromDays = absFloor(daysToMonths(days));
6785 months += monthsFromDays;
6786 days -= absCeil(monthsToDays(monthsFromDays)); // 12 months -> 1 year
6787
6788 years = absFloor(months / 12);
6789 months %= 12;
6790 data.days = days;
6791 data.months = months;
6792 data.years = years;
6793 return this;
6794 }
6795
6796 function daysToMonths(days) {
6797 // 400 years have 146097 days (taking into account leap year rules)
6798 // 400 years have 12 months === 4800
6799 return days * 4800 / 146097;
6800 }
6801
6802 function monthsToDays(months) {
6803 // the reverse of daysToMonths
6804 return months * 146097 / 4800;
6805 }
6806
6807 function as(units) {
6808 if (!this.isValid()) {
6809 return NaN;
6810 }
6811
6812 var days;
6813 var months;
6814 var milliseconds = this._milliseconds;
6815 units = normalizeUnits(units);
6816
6817 if (units === 'month' || units === 'quarter' || units === 'year') {
6818 days = this._days + milliseconds / 864e5;
6819 months = this._months + daysToMonths(days);
6820
6821 switch (units) {
6822 case 'month':
6823 return months;
6824
6825 case 'quarter':
6826 return months / 3;
6827
6828 case 'year':
6829 return months / 12;
6830 }
6831 } else {
6832 // handle milliseconds separately because of floating point math errors (issue #1867)
6833 days = this._days + Math.round(monthsToDays(this._months));
6834
6835 switch (units) {
6836 case 'week':
6837 return days / 7 + milliseconds / 6048e5;
6838
6839 case 'day':
6840 return days + milliseconds / 864e5;
6841
6842 case 'hour':
6843 return days * 24 + milliseconds / 36e5;
6844
6845 case 'minute':
6846 return days * 1440 + milliseconds / 6e4;
6847
6848 case 'second':
6849 return days * 86400 + milliseconds / 1000;
6850 // Math.floor prevents floating point math errors here
6851
6852 case 'millisecond':
6853 return Math.floor(days * 864e5) + milliseconds;
6854
6855 default:
6856 throw new Error('Unknown unit ' + units);
6857 }
6858 }
6859 } // TODO: Use this.as('ms')?
6860
6861
6862 function valueOf$1() {
6863 if (!this.isValid()) {
6864 return NaN;
6865 }
6866
6867 return this._milliseconds + this._days * 864e5 + this._months % 12 * 2592e6 + toInt(this._months / 12) * 31536e6;
6868 }
6869
6870 function makeAs(alias) {
6871 return function () {
6872 return this.as(alias);
6873 };
6874 }
6875
6876 var asMilliseconds = makeAs('ms');
6877 var asSeconds = makeAs('s');
6878 var asMinutes = makeAs('m');
6879 var asHours = makeAs('h');
6880 var asDays = makeAs('d');
6881 var asWeeks = makeAs('w');
6882 var asMonths = makeAs('M');
6883 var asQuarters = makeAs('Q');
6884 var asYears = makeAs('y');
6885
6886 function clone$1() {
6887 return createDuration(this);
6888 }
6889
6890 function get$2(units) {
6891 units = normalizeUnits(units);
6892 return this.isValid() ? this[units + 's']() : NaN;
6893 }
6894
6895 function makeGetter(name) {
6896 return function () {
6897 return this.isValid() ? this._data[name] : NaN;
6898 };
6899 }
6900
6901 var milliseconds = makeGetter('milliseconds');
6902 var seconds = makeGetter('seconds');
6903 var minutes = makeGetter('minutes');
6904 var hours = makeGetter('hours');
6905 var days = makeGetter('days');
6906 var months = makeGetter('months');
6907 var years = makeGetter('years');
6908
6909 function weeks() {
6910 return absFloor(this.days() / 7);
6911 }
6912
6913 var round = Math.round;
6914 var thresholds = {
6915 ss: 44,
6916 // a few seconds to seconds
6917 s: 45,
6918 // seconds to minute
6919 m: 45,
6920 // minutes to hour
6921 h: 22,
6922 // hours to day
6923 d: 26,
6924 // days to month
6925 M: 11 // months to year
6926
6927 }; // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
6928
6929 function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
6930 return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
6931 }
6932
6933 function relativeTime$1(posNegDuration, withoutSuffix, locale) {
6934 var duration = createDuration(posNegDuration).abs();
6935 var seconds = round(duration.as('s'));
6936 var minutes = round(duration.as('m'));
6937 var hours = round(duration.as('h'));
6938 var days = round(duration.as('d'));
6939 var months = round(duration.as('M'));
6940 var years = round(duration.as('y'));
6941 var a = seconds <= thresholds.ss && ['s', seconds] || seconds < thresholds.s && ['ss', seconds] || minutes <= 1 && ['m'] || minutes < thresholds.m && ['mm', minutes] || hours <= 1 && ['h'] || hours < thresholds.h && ['hh', hours] || days <= 1 && ['d'] || days < thresholds.d && ['dd', days] || months <= 1 && ['M'] || months < thresholds.M && ['MM', months] || years <= 1 && ['y'] || ['yy', years];
6942 a[2] = withoutSuffix;
6943 a[3] = +posNegDuration > 0;
6944 a[4] = locale;
6945 return substituteTimeAgo.apply(null, a);
6946 } // This function allows you to set the rounding function for relative time strings
6947
6948
6949 function getSetRelativeTimeRounding(roundingFunction) {
6950 if (roundingFunction === undefined) {
6951 return round;
6952 }
6953
6954 if (typeof roundingFunction === 'function') {
6955 round = roundingFunction;
6956 return true;
6957 }
6958
6959 return false;
6960 } // This function allows you to set a threshold for relative time strings
6961
6962
6963 function getSetRelativeTimeThreshold(threshold, limit) {
6964 if (thresholds[threshold] === undefined) {
6965 return false;
6966 }
6967
6968 if (limit === undefined) {
6969 return thresholds[threshold];
6970 }
6971
6972 thresholds[threshold] = limit;
6973
6974 if (threshold === 's') {
6975 thresholds.ss = limit - 1;
6976 }
6977
6978 return true;
6979 }
6980
6981 function humanize(withSuffix) {
6982 if (!this.isValid()) {
6983 return this.localeData().invalidDate();
6984 }
6985
6986 var locale = this.localeData();
6987 var output = relativeTime$1(this, !withSuffix, locale);
6988
6989 if (withSuffix) {
6990 output = locale.pastFuture(+this, output);
6991 }
6992
6993 return locale.postformat(output);
6994 }
6995
6996 var abs$1 = Math.abs;
6997
6998 function sign(x) {
6999 return (x > 0) - (x < 0) || +x;
7000 }
7001
7002 function toISOString$1() {
7003 // for ISO strings we do not use the normal bubbling rules:
7004 // * milliseconds bubble up until they become hours
7005 // * days do not bubble at all
7006 // * months bubble up until they become years
7007 // This is because there is no context-free conversion between hours and days
7008 // (think of clock changes)
7009 // and also not between days and months (28-31 days per month)
7010 if (!this.isValid()) {
7011 return this.localeData().invalidDate();
7012 }
7013
7014 var seconds = abs$1(this._milliseconds) / 1000;
7015 var days = abs$1(this._days);
7016 var months = abs$1(this._months);
7017 var minutes, hours, years; // 3600 seconds -> 60 minutes -> 1 hour
7018
7019 minutes = absFloor(seconds / 60);
7020 hours = absFloor(minutes / 60);
7021 seconds %= 60;
7022 minutes %= 60; // 12 months -> 1 year
7023
7024 years = absFloor(months / 12);
7025 months %= 12; // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
7026
7027 var Y = years;
7028 var M = months;
7029 var D = days;
7030 var h = hours;
7031 var m = minutes;
7032 var s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : '';
7033 var total = this.asSeconds();
7034
7035 if (!total) {
7036 // this is the same as C#'s (Noda) and python (isodate)...
7037 // but not other JS (goog.date)
7038 return 'P0D';
7039 }
7040
7041 var totalSign = total < 0 ? '-' : '';
7042 var ymSign = sign(this._months) !== sign(total) ? '-' : '';
7043 var daysSign = sign(this._days) !== sign(total) ? '-' : '';
7044 var hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '';
7045 return totalSign + 'P' + (Y ? ymSign + Y + 'Y' : '') + (M ? ymSign + M + 'M' : '') + (D ? daysSign + D + 'D' : '') + (h || m || s ? 'T' : '') + (h ? hmsSign + h + 'H' : '') + (m ? hmsSign + m + 'M' : '') + (s ? hmsSign + s + 'S' : '');
7046 }
7047
7048 var proto$2 = Duration.prototype;
7049 proto$2.isValid = isValid$1;
7050 proto$2.abs = abs;
7051 proto$2.add = add$1;
7052 proto$2.subtract = subtract$1;
7053 proto$2.as = as;
7054 proto$2.asMilliseconds = asMilliseconds;
7055 proto$2.asSeconds = asSeconds;
7056 proto$2.asMinutes = asMinutes;
7057 proto$2.asHours = asHours;
7058 proto$2.asDays = asDays;
7059 proto$2.asWeeks = asWeeks;
7060 proto$2.asMonths = asMonths;
7061 proto$2.asQuarters = asQuarters;
7062 proto$2.asYears = asYears;
7063 proto$2.valueOf = valueOf$1;
7064 proto$2._bubble = bubble;
7065 proto$2.clone = clone$1;
7066 proto$2.get = get$2;
7067 proto$2.milliseconds = milliseconds;
7068 proto$2.seconds = seconds;
7069 proto$2.minutes = minutes;
7070 proto$2.hours = hours;
7071 proto$2.days = days;
7072 proto$2.weeks = weeks;
7073 proto$2.months = months;
7074 proto$2.years = years;
7075 proto$2.humanize = humanize;
7076 proto$2.toISOString = toISOString$1;
7077 proto$2.toString = toISOString$1;
7078 proto$2.toJSON = toISOString$1;
7079 proto$2.locale = locale;
7080 proto$2.localeData = localeData;
7081 proto$2.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1);
7082 proto$2.lang = lang; // Side effect imports
7083 // FORMATTING
7084
7085 addFormatToken('X', 0, 0, 'unix');
7086 addFormatToken('x', 0, 0, 'valueOf'); // PARSING
7087
7088 addRegexToken('x', matchSigned);
7089 addRegexToken('X', matchTimestamp);
7090 addParseToken('X', function (input, array, config) {
7091 config._d = new Date(_parseFloat$3(input, 10) * 1000);
7092 });
7093 addParseToken('x', function (input, array, config) {
7094 config._d = new Date(toInt(input));
7095 }); // Side effect imports
7096
7097 hooks.version = '2.24.0';
7098 setHookCallback(createLocal);
7099 hooks.fn = proto;
7100 hooks.min = min;
7101 hooks.max = max;
7102 hooks.now = now;
7103 hooks.utc = createUTC;
7104 hooks.unix = createUnix;
7105 hooks.months = listMonths;
7106 hooks.isDate = isDate;
7107 hooks.locale = getSetGlobalLocale;
7108 hooks.invalid = createInvalid;
7109 hooks.duration = createDuration;
7110 hooks.isMoment = isMoment;
7111 hooks.weekdays = listWeekdays;
7112 hooks.parseZone = createInZone;
7113 hooks.localeData = getLocale;
7114 hooks.isDuration = isDuration;
7115 hooks.monthsShort = listMonthsShort;
7116 hooks.weekdaysMin = listWeekdaysMin;
7117 hooks.defineLocale = defineLocale;
7118 hooks.updateLocale = updateLocale;
7119 hooks.locales = listLocales;
7120 hooks.weekdaysShort = listWeekdaysShort;
7121 hooks.normalizeUnits = normalizeUnits;
7122 hooks.relativeTimeRounding = getSetRelativeTimeRounding;
7123 hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
7124 hooks.calendarFormat = getCalendarFormat;
7125 hooks.prototype = proto; // currently HTML5 input type only supports 24-hour formats
7126
7127 hooks.HTML5_FMT = {
7128 DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm',
7129 // <input type="datetime-local" />
7130 DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss',
7131 // <input type="datetime-local" step="1" />
7132 DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS',
7133 // <input type="datetime-local" step="0.001" />
7134 DATE: 'YYYY-MM-DD',
7135 // <input type="date" />
7136 TIME: 'HH:mm',
7137 // <input type="time" />
7138 TIME_SECONDS: 'HH:mm:ss',
7139 // <input type="time" step="1" />
7140 TIME_MS: 'HH:mm:ss.SSS',
7141 // <input type="time" step="0.001" />
7142 WEEK: 'GGGG-[W]WW',
7143 // <input type="week" />
7144 MONTH: 'YYYY-MM' // <input type="month" />
7145
7146 };
7147 return hooks;
7148 });
7149}); // Maps for number <-> hex string conversion
7150
7151var byteToHex = [];
7152
7153for (var i = 0; i < 256; i++) {
7154 byteToHex[i] = (i + 0x100).toString(16).substr(1);
7155}
7156/**
7157 * Represent binary UUID into it's string representation.
7158 *
7159 * @param buf - Buffer containing UUID bytes.
7160 * @param offset - Offset from the start of the buffer where the UUID is saved (not needed if the buffer starts with the UUID).
7161 *
7162 * @returns String representation of the UUID.
7163 */
7164
7165
7166function stringifyUUID(buf, offset) {
7167 var i = offset || 0;
7168 var bth = byteToHex;
7169 return bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]];
7170}
7171/**
7172 * Generate 16 random bytes to be used as a base for UUID.
7173 *
7174 * @ignore
7175 */
7176
7177
7178var random = function () {
7179 if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
7180 // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto
7181 // Moderately fast, high quality
7182 var _rnds8 = new Uint8Array(16);
7183
7184 return function whatwgRNG() {
7185 crypto.getRandomValues(_rnds8);
7186 return _rnds8;
7187 };
7188 } // Math.random()-based (RNG)
7189 //
7190 // If all else fails, use Math.random().
7191 // It's fast, but is of unspecified quality.
7192
7193
7194 var _rnds = new Array(16);
7195
7196 return function () {
7197 for (var i = 0, r; i < 16; i++) {
7198 if ((i & 0x03) === 0) {
7199 r = Math.random() * 0x100000000;
7200 }
7201
7202 _rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
7203 }
7204
7205 return _rnds;
7206 }; // uuid.js
7207 //
7208 // Copyright (c) 2010-2012 Robert Kieffer
7209 // MIT License - http://opensource.org/licenses/mit-license.php
7210 // Unique ID creation requires a high quality random # generator. We feature
7211 // detect to determine the best RNG source, normalizing to a function that
7212 // returns 128-bits of randomness, since that's what's usually required
7213 // return require('./rng');
7214}();
7215
7216var byteToHex$1 = [];
7217
7218for (var i$1 = 0; i$1 < 256; i$1++) {
7219 byteToHex$1[i$1] = (i$1 + 0x100).toString(16).substr(1);
7220} // **`v1()` - Generate time-based UUID**
7221//
7222// Inspired by https://github.com/LiosK/UUID.js
7223// and http://docs.python.org/library/uuid.html
7224// random #'s we need to init node and clockseq
7225
7226
7227var seedBytes = random(); // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
7228
7229var defaultNodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; // Per 4.2.2, randomize (14 bit) clockseq
7230
7231var defaultClockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; // Previous uuid creation time
7232
7233/**
7234 * UUIDv4 options.
7235 */
7236
7237/**
7238 * Generate UUIDv4
7239 *
7240 * @param options - Options to be used instead of default generated values.
7241 * String 'binary' is a shorthand for uuid4({}, new Array(16)).
7242 * @param buf - If present the buffer will be filled with the generated UUID.
7243 * @param offset - Offset of the UUID from the start of the buffer.
7244 *
7245 * @returns UUIDv4
7246 */
7247
7248function uuid4() {
7249 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
7250 var buf = arguments.length > 1 ? arguments[1] : undefined;
7251 var offset = arguments.length > 2 ? arguments[2] : undefined; // Deprecated - 'format' argument, as supported in v1.2
7252
7253 var i = buf && offset || 0;
7254
7255 if (typeof options === 'string') {
7256 buf = options === 'binary' ? new Array(16) : undefined;
7257 options = {};
7258 }
7259
7260 var rnds = options.random || (options.rng || random)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
7261
7262 rnds[6] = rnds[6] & 0x0f | 0x40;
7263 rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
7264
7265 if (buf) {
7266 for (var ii = 0; ii < 16; ii++) {
7267 buf[i + ii] = rnds[ii];
7268 }
7269 }
7270
7271 return buf || stringifyUUID(rnds);
7272} // Rollup will complain about mixing default and named exports in UMD build,
7273
7274
7275function ownKeys$1(object, enumerableOnly) {
7276 var keys = keys$3(object);
7277
7278 if (getOwnPropertySymbols$2) {
7279 var symbols = getOwnPropertySymbols$2(object);
7280 if (enumerableOnly) symbols = filter$2(symbols).call(symbols, function (sym) {
7281 return getOwnPropertyDescriptor$3(object, sym).enumerable;
7282 });
7283 keys.push.apply(keys, symbols);
7284 }
7285
7286 return keys;
7287}
7288
7289function _objectSpread(target) {
7290 for (var i = 1; i < arguments.length; i++) {
7291 var source = arguments[i] != null ? arguments[i] : {};
7292
7293 if (i % 2) {
7294 var _context11;
7295
7296 forEach$2(_context11 = ownKeys$1(source, true)).call(_context11, function (key) {
7297 defineProperty$6(target, key, source[key]);
7298 });
7299 } else if (getOwnPropertyDescriptors$2) {
7300 defineProperties$1(target, getOwnPropertyDescriptors$2(source));
7301 } else {
7302 var _context12;
7303
7304 forEach$2(_context12 = ownKeys$1(source)).call(_context12, function (key) {
7305 defineProperty$1(target, key, getOwnPropertyDescriptor$3(source, key));
7306 });
7307 }
7308 }
7309
7310 return target;
7311} // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
7312// code from http://momentjs.com/
7313
7314
7315var ASPDateRegex = /^\/?Date\((-?\d+)/i; // Color REs
7316
7317var fullHexRE = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
7318var shortHexRE = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
7319var rgbRE = /^rgb\( *(1?\d{1,2}|2[0-4]\d|25[0-5]) *, *(1?\d{1,2}|2[0-4]\d|25[0-5]) *, *(1?\d{1,2}|2[0-4]\d|25[0-5]) *\)$/i;
7320var rgbaRE = /^rgba\( *(1?\d{1,2}|2[0-4]\d|25[0-5]) *, *(1?\d{1,2}|2[0-4]\d|25[0-5]) *, *(1?\d{1,2}|2[0-4]\d|25[0-5]) *, *([01]|0?\.\d+) *\)$/i;
7321/**
7322 * Hue, Saturation, Value.
7323 */
7324
7325/**
7326 * Test whether given object is a number
7327 *
7328 * @param value - Input value of unknown type.
7329 *
7330 * @returns True if number, false otherwise.
7331 */
7332
7333function isNumber(value) {
7334 return value instanceof Number || typeof value === "number";
7335}
7336/**
7337 * Remove everything in the DOM object
7338 *
7339 * @param DOMobject - Node whose child nodes will be recursively deleted.
7340 */
7341
7342
7343function recursiveDOMDelete(DOMobject) {
7344 if (DOMobject) {
7345 while (DOMobject.hasChildNodes() === true) {
7346 var child = DOMobject.firstChild;
7347
7348 if (child) {
7349 recursiveDOMDelete(child);
7350 DOMobject.removeChild(child);
7351 }
7352 }
7353 }
7354}
7355/**
7356 * Test whether given object is a string
7357 *
7358 * @param value - Input value of unknown type.
7359 *
7360 * @returns True if string, false otherwise.
7361 */
7362
7363
7364function isString(value) {
7365 return value instanceof String || typeof value === "string";
7366}
7367/**
7368 * Test whether given object is a object (not primitive or null).
7369 *
7370 * @param value - Input value of unknown type.
7371 *
7372 * @returns True if not null object, false otherwise.
7373 */
7374
7375
7376function isObject$1(value) {
7377 return _typeof_1(value) === "object" && value !== null;
7378}
7379/**
7380 * Test whether given object is a Date, or a String containing a Date
7381 *
7382 * @param value - Input value of unknown type.
7383 *
7384 * @returns True if Date instance or string date representation, false otherwise.
7385 */
7386
7387
7388function isDate(value) {
7389 if (value instanceof Date) {
7390 return true;
7391 } else if (isString(value)) {
7392 // test whether this string contains a date
7393 var match = ASPDateRegex.exec(value);
7394
7395 if (match) {
7396 return true;
7397 } else if (!isNaN(Date.parse(value))) {
7398 return true;
7399 }
7400 }
7401
7402 return false;
7403}
7404/**
7405 * Test whether given object is a Moment date.
7406 * @TODO: This is basically a workaround, if Moment was imported property it wouldn't necessary as moment.isMoment is a TS type guard.
7407 *
7408 * @param value - Input value of unknown type.
7409 *
7410 * @returns True if Moment instance, false otherwise.
7411 */
7412
7413
7414function isMoment(value) {
7415 return moment.isMoment(value);
7416}
7417/**
7418 * Copy property from b to a if property present in a.
7419 * If property in b explicitly set to null, delete it if `allowDeletion` set.
7420 *
7421 * Internal helper routine, should not be exported. Not added to `exports` for that reason.
7422 *
7423 * @param a - Target object.
7424 * @param b - Source object.
7425 * @param prop - Name of property to copy from b to a.
7426 * @param allowDeletion if true, delete property in a if explicitly set to null in b
7427 */
7428
7429
7430function copyOrDelete(a, b, prop, allowDeletion) {
7431 var doDeletion = false;
7432
7433 if (allowDeletion === true) {
7434 doDeletion = b[prop] === null && a[prop] !== undefined;
7435 }
7436
7437 if (doDeletion) {
7438 delete a[prop];
7439 } else {
7440 a[prop] = b[prop]; // Remember, this is a reference copy!
7441 }
7442}
7443/**
7444 * Fill an object with a possibly partially defined other object.
7445 *
7446 * Only copies values for the properties already present in a.
7447 * That means an object is not created on a property if only the b object has it.
7448 *
7449 * @param a - The object that will have it's properties updated.
7450 * @param b - The object with property updates.
7451 * @param allowDeletion - if true, delete properties in a that are explicitly set to null in b
7452 */
7453
7454
7455function fillIfDefined(a, b) {
7456 var allowDeletion = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; // NOTE: iteration of properties of a
7457 // NOTE: prototype properties iterated over as well
7458
7459 for (var prop in a) {
7460 if (b[prop] !== undefined) {
7461 if (b[prop] === null || _typeof_1(b[prop]) !== "object") {
7462 // Note: typeof null === 'object'
7463 copyOrDelete(a, b, prop, allowDeletion);
7464 } else {
7465 var aProp = a[prop];
7466 var bProp = b[prop];
7467
7468 if (isObject$1(aProp) && isObject$1(bProp)) {
7469 fillIfDefined(aProp, bProp, allowDeletion);
7470 }
7471 }
7472 }
7473 }
7474}
7475/**
7476 * Copy the values of all of the enumerable own properties from one or more source objects to a
7477 * target object. Returns the target object.
7478 *
7479 * @param target - The target object to copy to.
7480 * @param source - The source object from which to copy properties.
7481 *
7482 * @return The target object.
7483 */
7484
7485
7486var extend = assign$2;
7487/**
7488 * Extend object a with selected properties of object b or a series of objects
7489 * Only properties with defined values are copied
7490 *
7491 * @param props - Properties to be copied to a.
7492 * @param a - The target.
7493 * @param others - The sources.
7494 *
7495 * @returns Argument a.
7496 */
7497
7498function selectiveExtend(props, a) {
7499 if (!isArray$5(props)) {
7500 throw new Error("Array with property names expected as first argument");
7501 }
7502
7503 for (var _len = arguments.length, others = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
7504 others[_key - 2] = arguments[_key];
7505 }
7506
7507 for (var _i = 0, _others = others; _i < _others.length; _i++) {
7508 var other = _others[_i];
7509
7510 for (var p = 0; p < props.length; p++) {
7511 var prop = props[p];
7512
7513 if (other && Object.prototype.hasOwnProperty.call(other, prop)) {
7514 a[prop] = other[prop];
7515 }
7516 }
7517 }
7518
7519 return a;
7520}
7521/**
7522 * Extend object a with selected properties of object b.
7523 * Only properties with defined values are copied.
7524 *
7525 * **Note:** Previous version of this routine implied that multiple source objects
7526 * could be used; however, the implementation was **wrong**.
7527 * Since multiple (>1) sources weren't used anywhere in the `vis.js` code,
7528 * this has been removed
7529 *
7530 * @param props - Names of first-level properties to copy over.
7531 * @param a - Target object.
7532 * @param b - Source object.
7533 * @param allowDeletion - If true, delete property in a if explicitly set to null in b.
7534 *
7535 * @returns Argument a.
7536 */
7537
7538
7539function selectiveDeepExtend(props, a, b) {
7540 var allowDeletion = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; // TODO: add support for Arrays to deepExtend
7541
7542 if (isArray$5(b)) {
7543 throw new TypeError("Arrays are not supported by deepExtend");
7544 }
7545
7546 for (var p = 0; p < props.length; p++) {
7547 var prop = props[p];
7548
7549 if (Object.prototype.hasOwnProperty.call(b, prop)) {
7550 if (b[prop] && b[prop].constructor === Object) {
7551 if (a[prop] === undefined) {
7552 a[prop] = {};
7553 }
7554
7555 if (a[prop].constructor === Object) {
7556 deepExtend(a[prop], b[prop], false, allowDeletion);
7557 } else {
7558 copyOrDelete(a, b, prop, allowDeletion);
7559 }
7560 } else if (isArray$5(b[prop])) {
7561 throw new TypeError("Arrays are not supported by deepExtend");
7562 } else {
7563 copyOrDelete(a, b, prop, allowDeletion);
7564 }
7565 }
7566 }
7567
7568 return a;
7569}
7570/**
7571 * Extend object `a` with properties of object `b`, ignoring properties which are explicitly
7572 * specified to be excluded.
7573 *
7574 * The properties of `b` are considered for copying.
7575 * Properties which are themselves objects are are also extended.
7576 * Only properties with defined values are copied
7577 *
7578 * @param propsToExclude - Names of properties which should *not* be copied.
7579 * @param a - Object to extend.
7580 * @param b - Object to take properties from for extension.
7581 * @param allowDeletion - If true, delete properties in a that are explicitly set to null in b.
7582 *
7583 * @returns Argument a.
7584 */
7585
7586
7587function selectiveNotDeepExtend(propsToExclude, a, b) {
7588 var allowDeletion = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; // TODO: add support for Arrays to deepExtend
7589 // NOTE: array properties have an else-below; apparently, there is a problem here.
7590
7591 if (isArray$5(b)) {
7592 throw new TypeError("Arrays are not supported by deepExtend");
7593 }
7594
7595 for (var prop in b) {
7596 if (!Object.prototype.hasOwnProperty.call(b, prop)) {
7597 continue;
7598 } // Handle local properties only
7599
7600
7601 if (indexOf$3(propsToExclude).call(propsToExclude, prop) !== -1) {
7602 continue;
7603 } // In exclusion list, skip
7604
7605
7606 if (b[prop] && b[prop].constructor === Object) {
7607 if (a[prop] === undefined) {
7608 a[prop] = {};
7609 }
7610
7611 if (a[prop].constructor === Object) {
7612 deepExtend(a[prop], b[prop]); // NOTE: allowDeletion not propagated!
7613 } else {
7614 copyOrDelete(a, b, prop, allowDeletion);
7615 }
7616 } else if (isArray$5(b[prop])) {
7617 a[prop] = [];
7618
7619 for (var i = 0; i < b[prop].length; i++) {
7620 a[prop].push(b[prop][i]);
7621 }
7622 } else {
7623 copyOrDelete(a, b, prop, allowDeletion);
7624 }
7625 }
7626
7627 return a;
7628}
7629/**
7630 * Deep extend an object a with the properties of object b
7631 *
7632 * @param a - Target object.
7633 * @param b - Source object.
7634 * @param protoExtend - If true, the prototype values will also be extended
7635 * (ie. the options objects that inherit from others will also get the inherited options).
7636 * @param allowDeletion - If true, the values of fields that are null will be deleted.
7637 *
7638 * @returns Argument a.
7639 */
7640
7641
7642function deepExtend(a, b) {
7643 var protoExtend = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
7644 var allowDeletion = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
7645
7646 for (var prop in b) {
7647 if (Object.prototype.hasOwnProperty.call(b, prop) || protoExtend === true) {
7648 if (_typeof_1(b[prop]) === "object" && b[prop] !== null && getPrototypeOf$2(b[prop]) === Object.prototype) {
7649 if (a[prop] === undefined) {
7650 a[prop] = deepExtend({}, b[prop], protoExtend); // NOTE: allowDeletion not propagated!
7651 } else if (_typeof_1(a[prop]) === "object" && a[prop] !== null && getPrototypeOf$2(a[prop]) === Object.prototype) {
7652 deepExtend(a[prop], b[prop], protoExtend); // NOTE: allowDeletion not propagated!
7653 } else {
7654 copyOrDelete(a, b, prop, allowDeletion);
7655 }
7656 } else if (isArray$5(b[prop])) {
7657 var _context;
7658
7659 a[prop] = slice$2(_context = b[prop]).call(_context);
7660 } else {
7661 copyOrDelete(a, b, prop, allowDeletion);
7662 }
7663 }
7664 }
7665
7666 return a;
7667}
7668/**
7669 * Test whether all elements in two arrays are equal.
7670 *
7671 * @param a - First array.
7672 * @param b - Second array.
7673 *
7674 * @returns True if both arrays have the same length and same elements (1 = '1').
7675 */
7676
7677
7678function equalArray(a, b) {
7679 if (a.length !== b.length) {
7680 return false;
7681 }
7682
7683 for (var i = 0, len = a.length; i < len; i++) {
7684 if (a[i] != b[i]) {
7685 return false;
7686 }
7687 }
7688
7689 return true;
7690}
7691/**
7692 * Convert an object into another type
7693 *
7694 * @param object - Value of unknown type.
7695 * @param type - Name of the desired type.
7696 *
7697 * @returns Object in the desired type.
7698 * @throws Error
7699 */
7700
7701
7702function convert(object, type) {
7703 var match;
7704
7705 if (object === undefined) {
7706 return undefined;
7707 }
7708
7709 if (object === null) {
7710 return null;
7711 }
7712
7713 if (!type) {
7714 return object;
7715 }
7716
7717 if (!(typeof type === "string") && !(type instanceof String)) {
7718 throw new Error("Type must be a string");
7719 } //noinspection FallthroughInSwitchStatementJS
7720
7721
7722 switch (type) {
7723 case "boolean":
7724 case "Boolean":
7725 return Boolean(object);
7726
7727 case "number":
7728 case "Number":
7729 if (isString(object) && !isNaN(Date.parse(object))) {
7730 return moment(object).valueOf();
7731 } else {
7732 // @TODO: I don't think that Number and String constructors are a good idea.
7733 // This could also fail if the object doesn't have valueOf method or if it's redefined.
7734 // For example: Object.create(null) or { valueOf: 7 }.
7735 return Number(object.valueOf());
7736 }
7737
7738 case "string":
7739 case "String":
7740 return String(object);
7741
7742 case "Date":
7743 if (isNumber(object)) {
7744 return new Date(object);
7745 }
7746
7747 if (object instanceof Date) {
7748 return new Date(object.valueOf());
7749 } else if (isMoment(object)) {
7750 return new Date(object.valueOf());
7751 }
7752
7753 if (isString(object)) {
7754 match = ASPDateRegex.exec(object);
7755
7756 if (match) {
7757 // object is an ASP date
7758 return new Date(Number(match[1])); // parse number
7759 } else {
7760 return moment(new Date(object)).toDate(); // parse string
7761 }
7762 } else {
7763 throw new Error("Cannot convert object of type " + getType(object) + " to type Date");
7764 }
7765
7766 case "Moment":
7767 if (isNumber(object)) {
7768 return moment(object);
7769 }
7770
7771 if (object instanceof Date) {
7772 return moment(object.valueOf());
7773 } else if (isMoment(object)) {
7774 return moment(object);
7775 }
7776
7777 if (isString(object)) {
7778 match = ASPDateRegex.exec(object);
7779
7780 if (match) {
7781 // object is an ASP date
7782 return moment(Number(match[1])); // parse number
7783 } else {
7784 return moment(object); // parse string
7785 }
7786 } else {
7787 throw new Error("Cannot convert object of type " + getType(object) + " to type Date");
7788 }
7789
7790 case "ISODate":
7791 if (isNumber(object)) {
7792 return new Date(object);
7793 } else if (object instanceof Date) {
7794 return object.toISOString();
7795 } else if (isMoment(object)) {
7796 return object.toDate().toISOString();
7797 } else if (isString(object)) {
7798 match = ASPDateRegex.exec(object);
7799
7800 if (match) {
7801 // object is an ASP date
7802 return new Date(Number(match[1])).toISOString(); // parse number
7803 } else {
7804 return moment(object).format(); // ISO 8601
7805 }
7806 } else {
7807 throw new Error("Cannot convert object of type " + getType(object) + " to type ISODate");
7808 }
7809
7810 case "ASPDate":
7811 if (isNumber(object)) {
7812 return "/Date(" + object + ")/";
7813 } else if (object instanceof Date || isMoment(object)) {
7814 return "/Date(" + object.valueOf() + ")/";
7815 } else if (isString(object)) {
7816 match = ASPDateRegex.exec(object);
7817
7818 var _value;
7819
7820 if (match) {
7821 // object is an ASP date
7822 _value = new Date(Number(match[1])).valueOf(); // parse number
7823 } else {
7824 _value = new Date(object).valueOf(); // parse string
7825 }
7826
7827 return "/Date(" + _value + ")/";
7828 } else {
7829 throw new Error("Cannot convert object of type " + getType(object) + " to type ASPDate");
7830 }
7831
7832 default:
7833 var never = type;
7834 throw new Error("Unknown type ".concat(never));
7835 }
7836}
7837/**
7838 * Get the type of an object, for example exports.getType([]) returns 'Array'
7839 *
7840 * @param object - Input value of unknown type.
7841 *
7842 * @returns Detected type.
7843 */
7844
7845
7846function getType(object) {
7847 var type = _typeof_1(object);
7848
7849 if (type === "object") {
7850 if (object === null) {
7851 return "null";
7852 }
7853
7854 if (object instanceof Boolean) {
7855 return "Boolean";
7856 }
7857
7858 if (object instanceof Number) {
7859 return "Number";
7860 }
7861
7862 if (object instanceof String) {
7863 return "String";
7864 }
7865
7866 if (isArray$5(object)) {
7867 return "Array";
7868 }
7869
7870 if (object instanceof Date) {
7871 return "Date";
7872 }
7873
7874 return "Object";
7875 }
7876
7877 if (type === "number") {
7878 return "Number";
7879 }
7880
7881 if (type === "boolean") {
7882 return "Boolean";
7883 }
7884
7885 if (type === "string") {
7886 return "String";
7887 }
7888
7889 if (type === undefined) {
7890 return "undefined";
7891 }
7892
7893 return type;
7894}
7895/**
7896 * Used to extend an array and copy it. This is used to propagate paths recursively.
7897 *
7898 * @param arr - First part.
7899 * @param newValue - The value to be aadded into the array.
7900 *
7901 * @returns A new array with all items from arr and newValue (which is last).
7902 */
7903
7904
7905function copyAndExtendArray(arr, newValue) {
7906 var _context2;
7907
7908 return concat$2(_context2 = []).call(_context2, toConsumableArray(arr), [newValue]);
7909}
7910/**
7911 * Used to extend an array and copy it. This is used to propagate paths recursively.
7912 *
7913 * @param arr - The array to be copied.
7914 *
7915 * @returns Shallow copy of arr.
7916 */
7917
7918
7919function copyArray(arr) {
7920 return slice$2(arr).call(arr);
7921}
7922/**
7923 * Retrieve the absolute left value of a DOM element
7924 *
7925 * @param elem - A dom element, for example a div.
7926 *
7927 * @returns The absolute left position of this element in the browser page.
7928 */
7929
7930
7931function getAbsoluteLeft(elem) {
7932 return elem.getBoundingClientRect().left;
7933}
7934/**
7935 * Retrieve the absolute right value of a DOM element
7936 *
7937 * @param elem - A dom element, for example a div.
7938 *
7939 * @returns The absolute right position of this element in the browser page.
7940 */
7941
7942
7943function getAbsoluteRight(elem) {
7944 return elem.getBoundingClientRect().right;
7945}
7946/**
7947 * Retrieve the absolute top value of a DOM element
7948 *
7949 * @param elem - A dom element, for example a div.
7950 *
7951 * @returns The absolute top position of this element in the browser page.
7952 */
7953
7954
7955function getAbsoluteTop(elem) {
7956 return elem.getBoundingClientRect().top;
7957}
7958/**
7959 * Add a className to the given elements style.
7960 *
7961 * @param elem - The element to which the classes will be added.
7962 * @param classNames - Space separated list of classes.
7963 */
7964
7965
7966function addClassName(elem, classNames) {
7967 var classes = elem.className.split(" ");
7968 var newClasses = classNames.split(" ");
7969 classes = concat$2(classes).call(classes, filter$2(newClasses).call(newClasses, function (className) {
7970 return indexOf$3(classes).call(classes, className) < 0;
7971 }));
7972 elem.className = classes.join(" ");
7973}
7974/**
7975 * Remove a className from the given elements style.
7976 *
7977 * @param elem - The element from which the classes will be removed.
7978 * @param classNames - Space separated list of classes.
7979 */
7980
7981
7982function removeClassName(elem, classNames) {
7983 var classes = elem.className.split(" ");
7984 var oldClasses = classNames.split(" ");
7985 classes = filter$2(classes).call(classes, function (className) {
7986 return indexOf$3(oldClasses).call(oldClasses, className) < 0;
7987 });
7988 elem.className = classes.join(" ");
7989}
7990/**
7991 * For each method for both arrays and objects.
7992 * In case of an array, the built-in Array.forEach() is applied (**No, it's not!**).
7993 * In case of an Object, the method loops over all properties of the object.
7994 *
7995 * @param object - An Object or Array to be iterated over.
7996 * @param callback - Array.forEach-like callback.
7997 */
7998
7999
8000function forEach$3(object, callback) {
8001 if (isArray$5(object)) {
8002 // array
8003 var len = object.length;
8004
8005 for (var i = 0; i < len; i++) {
8006 callback(object[i], i, object);
8007 }
8008 } else {
8009 // object
8010 for (var _key2 in object) {
8011 if (Object.prototype.hasOwnProperty.call(object, _key2)) {
8012 callback(object[_key2], _key2, object);
8013 }
8014 }
8015 }
8016}
8017/**
8018 * Convert an object into an array: all objects properties are put into the array. The resulting array is unordered.
8019 *
8020 * @param o - Object that contains the properties and methods.
8021 *
8022 * @returns An array of unordered values.
8023 */
8024
8025
8026var toArray = values$2;
8027/**
8028 * Update a property in an object
8029 *
8030 * @param object - The object whose property will be updated.
8031 * @param key - Name of the property to be updated.
8032 * @param value - The new value to be assigned.
8033 *
8034 * @returns Whether the value was updated (true) or already strictly the same in the original object (false).
8035 */
8036
8037function updateProperty(object, key, value) {
8038 if (object[key] !== value) {
8039 object[key] = value;
8040 return true;
8041 } else {
8042 return false;
8043 }
8044}
8045/**
8046 * Throttle the given function to be only executed once per animation frame.
8047 *
8048 * @param fn - The original function.
8049 *
8050 * @returns The throttled function.
8051 */
8052
8053
8054function throttle(fn) {
8055 var scheduled = false;
8056 return function () {
8057 if (!scheduled) {
8058 scheduled = true;
8059 requestAnimationFrame(function () {
8060 scheduled = false;
8061 fn();
8062 });
8063 }
8064 };
8065}
8066/**
8067 * Add and event listener. Works for all browsers.
8068 *
8069 * @param element - The element to bind the event listener to.
8070 * @param action - Same as Element.addEventListener(action, —, —).
8071 * @param listener - Same as Element.addEventListener(—, listener, —).
8072 * @param useCapture - Same as Element.addEventListener(—, —, useCapture).
8073 */
8074
8075
8076function addEventListener(element, action, listener, useCapture) {
8077 if (element.addEventListener) {
8078 var _context3;
8079
8080 if (useCapture === undefined) {
8081 useCapture = false;
8082 }
8083
8084 if (action === "mousewheel" && indexOf$3(_context3 = navigator.userAgent).call(_context3, "Firefox") >= 0) {
8085 action = "DOMMouseScroll"; // For Firefox
8086 }
8087
8088 element.addEventListener(action, listener, useCapture);
8089 } else {
8090 // @TODO: IE types? Does anyone care?
8091 element.attachEvent("on" + action, listener); // IE browsers
8092 }
8093}
8094/**
8095 * Remove an event listener from an element
8096 *
8097 * @param element - The element to bind the event listener to.
8098 * @param action - Same as Element.removeEventListener(action, —, —).
8099 * @param listener - Same as Element.removeEventListener(—, listener, —).
8100 * @param useCapture - Same as Element.removeEventListener(—, —, useCapture).
8101 */
8102
8103
8104function removeEventListener(element, action, listener, useCapture) {
8105 if (element.removeEventListener) {
8106 var _context4; // non-IE browsers
8107
8108
8109 if (useCapture === undefined) {
8110 useCapture = false;
8111 }
8112
8113 if (action === "mousewheel" && indexOf$3(_context4 = navigator.userAgent).call(_context4, "Firefox") >= 0) {
8114 action = "DOMMouseScroll"; // For Firefox
8115 }
8116
8117 element.removeEventListener(action, listener, useCapture);
8118 } else {
8119 // @TODO: IE types? Does anyone care?
8120 element.detachEvent("on" + action, listener); // IE browsers
8121 }
8122}
8123/**
8124 * Cancels the event's default action if it is cancelable, without stopping further propagation of the event.
8125 *
8126 * @param event - The event whose default action should be prevented.
8127 */
8128
8129
8130function preventDefault(event) {
8131 if (!event) {
8132 event = window.event;
8133 }
8134
8135 if (!event) ;else if (event.preventDefault) {
8136 event.preventDefault(); // non-IE browsers
8137 } else {
8138 // @TODO: IE types? Does anyone care?
8139 event.returnValue = false; // IE browsers
8140 }
8141}
8142/**
8143 * Get HTML element which is the target of the event.
8144 *
8145 * @param event - The event.
8146 *
8147 * @returns The element or null if not obtainable.
8148 */
8149
8150
8151function getTarget() {
8152 var event = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window.event; // code from http://www.quirksmode.org/js/events_properties.html
8153 // @TODO: EventTarget can be almost anything, is it okay to return only Elements?
8154
8155 var target = null;
8156 if (!event) ;else if (event.target) {
8157 target = event.target;
8158 } else if (event.srcElement) {
8159 target = event.srcElement;
8160 }
8161
8162 if (!(target instanceof Element)) {
8163 return null;
8164 }
8165
8166 if (target.nodeType != null && target.nodeType == 3) {
8167 // defeat Safari bug
8168 target = target.parentNode;
8169
8170 if (!(target instanceof Element)) {
8171 return null;
8172 }
8173 }
8174
8175 return target;
8176}
8177/**
8178 * Check if given element contains given parent somewhere in the DOM tree
8179 *
8180 * @param element - The element to be tested.
8181 * @param parent - The ancestor (not necessarily parent) of the element.
8182 *
8183 * @returns True if parent is an ancestor of the element, false otherwise.
8184 */
8185
8186
8187function hasParent(element, parent) {
8188 var elem = element;
8189
8190 while (elem) {
8191 if (elem === parent) {
8192 return true;
8193 } else if (elem.parentNode) {
8194 elem = elem.parentNode;
8195 } else {
8196 return false;
8197 }
8198 }
8199
8200 return false;
8201}
8202
8203var option = {
8204 /**
8205 * Convert a value into a boolean.
8206 *
8207 * @param value - Value to be converted intoboolean, a function will be executed as (() => unknown).
8208 * @param defaultValue - If the value or the return value of the function == null then this will be returned.
8209 *
8210 * @returns Corresponding boolean value, if none then the default value, if none then null.
8211 */
8212 asBoolean: function asBoolean(value, defaultValue) {
8213 if (typeof value == "function") {
8214 value = value();
8215 }
8216
8217 if (value != null) {
8218 return value != false;
8219 }
8220
8221 return defaultValue || null;
8222 },
8223
8224 /**
8225 * Convert a value into a number.
8226 *
8227 * @param value - Value to be converted intonumber, a function will be executed as (() => unknown).
8228 * @param defaultValue - If the value or the return value of the function == null then this will be returned.
8229 *
8230 * @returns Corresponding **boxed** number value, if none then the default value, if none then null.
8231 */
8232 asNumber: function asNumber(value, defaultValue) {
8233 if (typeof value == "function") {
8234 value = value();
8235 }
8236
8237 if (value != null) {
8238 return Number(value) || defaultValue || null;
8239 }
8240
8241 return defaultValue || null;
8242 },
8243
8244 /**
8245 * Convert a value into a string.
8246 *
8247 * @param value - Value to be converted intostring, a function will be executed as (() => unknown).
8248 * @param defaultValue - If the value or the return value of the function == null then this will be returned.
8249 *
8250 * @returns Corresponding **boxed** string value, if none then the default value, if none then null.
8251 */
8252 asString: function asString(value, defaultValue) {
8253 if (typeof value == "function") {
8254 value = value();
8255 }
8256
8257 if (value != null) {
8258 return String(value);
8259 }
8260
8261 return defaultValue || null;
8262 },
8263
8264 /**
8265 * Convert a value into a size.
8266 *
8267 * @param value - Value to be converted intosize, a function will be executed as (() => unknown).
8268 * @param defaultValue - If the value or the return value of the function == null then this will be returned.
8269 *
8270 * @returns Corresponding string value (number + 'px'), if none then the default value, if none then null.
8271 */
8272 asSize: function asSize(value, defaultValue) {
8273 if (typeof value == "function") {
8274 value = value();
8275 }
8276
8277 if (isString(value)) {
8278 return value;
8279 } else if (isNumber(value)) {
8280 return value + "px";
8281 } else {
8282 return defaultValue || null;
8283 }
8284 },
8285
8286 /**
8287 * Convert a value into a DOM Element.
8288 *
8289 * @param value - Value to be converted into DOM Element, a function will be executed as (() => unknown).
8290 * @param defaultValue - If the value or the return value of the function == null then this will be returned.
8291 *
8292 * @returns The DOM Element, if none then the default value, if none then null.
8293 */
8294 asElement: function asElement(value, defaultValue) {
8295 if (typeof value == "function") {
8296 value = value();
8297 }
8298
8299 return value || defaultValue || null;
8300 }
8301};
8302/**
8303 * Convert hex color string into RGB color object.
8304 * http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
8305 *
8306 * @param hex - Hex color string (3 or 6 digits, with or without #).
8307 *
8308 * @returns RGB color object.
8309 */
8310
8311function hexToRGB(hex) {
8312 var result;
8313
8314 switch (hex.length) {
8315 case 3:
8316 case 4:
8317 result = shortHexRE.exec(hex);
8318 return result ? {
8319 r: _parseInt$3(result[1] + result[1], 16),
8320 g: _parseInt$3(result[2] + result[2], 16),
8321 b: _parseInt$3(result[3] + result[3], 16)
8322 } : null;
8323
8324 case 6:
8325 case 7:
8326 result = fullHexRE.exec(hex);
8327 return result ? {
8328 r: _parseInt$3(result[1], 16),
8329 g: _parseInt$3(result[2], 16),
8330 b: _parseInt$3(result[3], 16)
8331 } : null;
8332
8333 default:
8334 return null;
8335 }
8336}
8337/**
8338 * This function takes string color in hex or RGB format and adds the opacity, RGBA is passed through unchanged.
8339 *
8340 * @param color - The color string (hex, RGB, RGBA).
8341 * @param opacity - The new opacity.
8342 *
8343 * @returns RGBA string, for example 'rgba(255, 0, 127, 0.3)'.
8344 */
8345
8346
8347function overrideOpacity(color, opacity) {
8348 if (indexOf$3(color).call(color, "rgba") !== -1) {
8349 return color;
8350 } else if (indexOf$3(color).call(color, "rgb") !== -1) {
8351 var rgb = color.substr(indexOf$3(color).call(color, "(") + 1).replace(")", "").split(",");
8352 return "rgba(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + "," + opacity + ")";
8353 } else {
8354 var _rgb = hexToRGB(color);
8355
8356 if (_rgb == null) {
8357 return color;
8358 } else {
8359 return "rgba(" + _rgb.r + "," + _rgb.g + "," + _rgb.b + "," + opacity + ")";
8360 }
8361 }
8362}
8363/**
8364 * Convert RGB <0, 255> into hex color string.
8365 *
8366 * @param red - Red channel.
8367 * @param green - Green channel.
8368 * @param blue - Blue channel.
8369 *
8370 * @returns Hex color string (for example: '#0acdc0').
8371 */
8372
8373
8374function RGBToHex(red, green, blue) {
8375 var _context5;
8376
8377 return "#" + slice$2(_context5 = ((1 << 24) + (red << 16) + (green << 8) + blue).toString(16)).call(_context5, 1);
8378}
8379/**
8380 * Parse a color property into an object with border, background, and highlight colors
8381 *
8382 * @param inputColor - Shorthand color string or input color object.
8383 * @param defaultColor - Full color object to fill in missing values in inputColor.
8384 *
8385 * @returns Color object.
8386 */
8387
8388
8389function parseColor(inputColor, defaultColor) {
8390 if (isString(inputColor)) {
8391 var colorStr = inputColor;
8392
8393 if (isValidRGB(colorStr)) {
8394 var _context6;
8395
8396 var rgb = map$2(_context6 = colorStr.substr(4).substr(0, colorStr.length - 5).split(",")).call(_context6, function (value) {
8397 return _parseInt$3(value);
8398 });
8399 colorStr = RGBToHex(rgb[0], rgb[1], rgb[2]);
8400 }
8401
8402 if (isValidHex(colorStr) === true) {
8403 var hsv = hexToHSV(colorStr);
8404 var lighterColorHSV = {
8405 h: hsv.h,
8406 s: hsv.s * 0.8,
8407 v: Math.min(1, hsv.v * 1.02)
8408 };
8409 var darkerColorHSV = {
8410 h: hsv.h,
8411 s: Math.min(1, hsv.s * 1.25),
8412 v: hsv.v * 0.8
8413 };
8414 var darkerColorHex = HSVToHex(darkerColorHSV.h, darkerColorHSV.s, darkerColorHSV.v);
8415 var lighterColorHex = HSVToHex(lighterColorHSV.h, lighterColorHSV.s, lighterColorHSV.v);
8416 return {
8417 background: colorStr,
8418 border: darkerColorHex,
8419 highlight: {
8420 background: lighterColorHex,
8421 border: darkerColorHex
8422 },
8423 hover: {
8424 background: lighterColorHex,
8425 border: darkerColorHex
8426 }
8427 };
8428 } else {
8429 return {
8430 background: colorStr,
8431 border: colorStr,
8432 highlight: {
8433 background: colorStr,
8434 border: colorStr
8435 },
8436 hover: {
8437 background: colorStr,
8438 border: colorStr
8439 }
8440 };
8441 }
8442 } else {
8443 if (defaultColor) {
8444 var color = {
8445 background: inputColor.background || defaultColor.background,
8446 border: inputColor.border || defaultColor.border,
8447 highlight: isString(inputColor.highlight) ? {
8448 border: inputColor.highlight,
8449 background: inputColor.highlight
8450 } : {
8451 background: inputColor.highlight && inputColor.highlight.background || defaultColor.highlight.background,
8452 border: inputColor.highlight && inputColor.highlight.border || defaultColor.highlight.border
8453 },
8454 hover: isString(inputColor.hover) ? {
8455 border: inputColor.hover,
8456 background: inputColor.hover
8457 } : {
8458 border: inputColor.hover && inputColor.hover.border || defaultColor.hover.border,
8459 background: inputColor.hover && inputColor.hover.background || defaultColor.hover.background
8460 }
8461 };
8462 return color;
8463 } else {
8464 var _color = {
8465 background: inputColor.background || undefined,
8466 border: inputColor.border || undefined,
8467 highlight: isString(inputColor.highlight) ? {
8468 border: inputColor.highlight,
8469 background: inputColor.highlight
8470 } : {
8471 background: inputColor.highlight && inputColor.highlight.background || undefined,
8472 border: inputColor.highlight && inputColor.highlight.border || undefined
8473 },
8474 hover: isString(inputColor.hover) ? {
8475 border: inputColor.hover,
8476 background: inputColor.hover
8477 } : {
8478 border: inputColor.hover && inputColor.hover.border || undefined,
8479 background: inputColor.hover && inputColor.hover.background || undefined
8480 }
8481 };
8482 return _color;
8483 }
8484 }
8485}
8486/**
8487 * Convert RGB <0, 255> into HSV object.
8488 * http://www.javascripter.net/faq/rgb2hsv.htm
8489 *
8490 * @param red - Red channel.
8491 * @param green - Green channel.
8492 * @param blue - Blue channel.
8493 *
8494 * @returns HSV color object.
8495 */
8496
8497
8498function RGBToHSV(red, green, blue) {
8499 red = red / 255;
8500 green = green / 255;
8501 blue = blue / 255;
8502 var minRGB = Math.min(red, Math.min(green, blue));
8503 var maxRGB = Math.max(red, Math.max(green, blue)); // Black-gray-white
8504
8505 if (minRGB === maxRGB) {
8506 return {
8507 h: 0,
8508 s: 0,
8509 v: minRGB
8510 };
8511 } // Colors other than black-gray-white:
8512
8513
8514 var d = red === minRGB ? green - blue : blue === minRGB ? red - green : blue - red;
8515 var h = red === minRGB ? 3 : blue === minRGB ? 1 : 5;
8516 var hue = 60 * (h - d / (maxRGB - minRGB)) / 360;
8517 var saturation = (maxRGB - minRGB) / maxRGB;
8518 var value = maxRGB;
8519 return {
8520 h: hue,
8521 s: saturation,
8522 v: value
8523 };
8524}
8525
8526var cssUtil = {
8527 // split a string with css styles into an object with key/values
8528 split: function split(cssText) {
8529 var _context7;
8530
8531 var styles = {};
8532 forEach$2(_context7 = cssText.split(";")).call(_context7, function (style) {
8533 if (trim$2(style).call(style) != "") {
8534 var _context8, _context9;
8535
8536 var parts = style.split(":");
8537
8538 var _key3 = trim$2(_context8 = parts[0]).call(_context8);
8539
8540 var _value2 = trim$2(_context9 = parts[1]).call(_context9);
8541
8542 styles[_key3] = _value2;
8543 }
8544 });
8545 return styles;
8546 },
8547 // build a css text string from an object with key/values
8548 join: function join(styles) {
8549 var _context10;
8550
8551 return map$2(_context10 = keys$3(styles)).call(_context10, function (key) {
8552 return key + ": " + styles[key];
8553 }).join("; ");
8554 }
8555};
8556/**
8557 * Append a string with css styles to an element
8558 *
8559 * @param element - The element that will receive new styles.
8560 * @param cssText - The styles to be appended.
8561 */
8562
8563function addCssText(element, cssText) {
8564 var currentStyles = cssUtil.split(element.style.cssText);
8565 var newStyles = cssUtil.split(cssText);
8566
8567 var styles = _objectSpread({}, currentStyles, {}, newStyles);
8568
8569 element.style.cssText = cssUtil.join(styles);
8570}
8571/**
8572 * Remove a string with css styles from an element
8573 *
8574 * @param element - The element from which styles should be removed.
8575 * @param cssText - The styles to be removed.
8576 */
8577
8578
8579function removeCssText(element, cssText) {
8580 var styles = cssUtil.split(element.style.cssText);
8581 var removeStyles = cssUtil.split(cssText);
8582
8583 for (var _key4 in removeStyles) {
8584 if (Object.prototype.hasOwnProperty.call(removeStyles, _key4)) {
8585 delete styles[_key4];
8586 }
8587 }
8588
8589 element.style.cssText = cssUtil.join(styles);
8590}
8591/**
8592 * Convert HSV <0, 1> into RGB color object.
8593 * https://gist.github.com/mjijackson/5311256
8594 *
8595 * @param h - Hue
8596 * @param s - Saturation
8597 * @param v - Value
8598 *
8599 * @returns RGB color object.
8600 */
8601
8602
8603function HSVToRGB(h, s, v) {
8604 var r;
8605 var g;
8606 var b;
8607 var i = Math.floor(h * 6);
8608 var f = h * 6 - i;
8609 var p = v * (1 - s);
8610 var q = v * (1 - f * s);
8611 var t = v * (1 - (1 - f) * s);
8612
8613 switch (i % 6) {
8614 case 0:
8615 r = v, g = t, b = p;
8616 break;
8617
8618 case 1:
8619 r = q, g = v, b = p;
8620 break;
8621
8622 case 2:
8623 r = p, g = v, b = t;
8624 break;
8625
8626 case 3:
8627 r = p, g = q, b = v;
8628 break;
8629
8630 case 4:
8631 r = t, g = p, b = v;
8632 break;
8633
8634 case 5:
8635 r = v, g = p, b = q;
8636 break;
8637 }
8638
8639 return {
8640 r: Math.floor(r * 255),
8641 g: Math.floor(g * 255),
8642 b: Math.floor(b * 255)
8643 };
8644}
8645/**
8646 * Convert HSV <0, 1> into hex color string.
8647 *
8648 * @param h - Hue
8649 * @param s - Saturation
8650 * @param v - Value
8651 *
8652 * @returns Hex color string.
8653 */
8654
8655
8656function HSVToHex(h, s, v) {
8657 var rgb = HSVToRGB(h, s, v);
8658 return RGBToHex(rgb.r, rgb.g, rgb.b);
8659}
8660/**
8661 * Convert hex color string into HSV <0, 1>.
8662 *
8663 * @param hex - Hex color string.
8664 *
8665 * @returns HSV color object.
8666 */
8667
8668
8669function hexToHSV(hex) {
8670 var rgb = hexToRGB(hex);
8671
8672 if (!rgb) {
8673 throw new TypeError("'".concat(hex, "' is not a valid color."));
8674 }
8675
8676 return RGBToHSV(rgb.r, rgb.g, rgb.b);
8677}
8678/**
8679 * Validate hex color string.
8680 *
8681 * @param hex - Unknown string that may contain a color.
8682 *
8683 * @returns True if the string is valid, false otherwise.
8684 */
8685
8686
8687function isValidHex(hex) {
8688 var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex);
8689 return isOk;
8690}
8691/**
8692 * Validate RGB color string.
8693 *
8694 * @param rgb - Unknown string that may contain a color.
8695 *
8696 * @returns True if the string is valid, false otherwise.
8697 */
8698
8699
8700function isValidRGB(rgb) {
8701 return rgbRE.test(rgb);
8702}
8703/**
8704 * Validate RGBA color string.
8705 *
8706 * @param rgba - Unknown string that may contain a color.
8707 *
8708 * @returns True if the string is valid, false otherwise.
8709 */
8710
8711
8712function isValidRGBA(rgba) {
8713 return rgbaRE.test(rgba);
8714}
8715/**
8716 * This recursively redirects the prototype of JSON objects to the referenceObject.
8717 * This is used for default options.
8718 *
8719 * @param fields - Names of properties to be bridged.
8720 * @param referenceObject - The original object.
8721 *
8722 * @returns A new object inheriting from the referenceObject.
8723 */
8724
8725
8726function selectiveBridgeObject(fields, referenceObject) {
8727 if (referenceObject !== null && _typeof_1(referenceObject) === "object") {
8728 // !!! typeof null === 'object'
8729 var objectTo = create$2(referenceObject);
8730
8731 for (var i = 0; i < fields.length; i++) {
8732 if (Object.prototype.hasOwnProperty.call(referenceObject, fields[i])) {
8733 if (_typeof_1(referenceObject[fields[i]]) == "object") {
8734 objectTo[fields[i]] = bridgeObject(referenceObject[fields[i]]);
8735 }
8736 }
8737 }
8738
8739 return objectTo;
8740 } else {
8741 return null;
8742 }
8743}
8744/**
8745 * This recursively redirects the prototype of JSON objects to the referenceObject.
8746 * This is used for default options.
8747 *
8748 * @param referenceObject - The original object.
8749 *
8750 * @returns The Element if the referenceObject is an Element, or a new object inheriting from the referenceObject.
8751 */
8752
8753
8754function bridgeObject(referenceObject) {
8755 if (referenceObject === null || _typeof_1(referenceObject) !== "object") {
8756 return null;
8757 }
8758
8759 if (referenceObject instanceof Element) {
8760 // Avoid bridging DOM objects
8761 return referenceObject;
8762 }
8763
8764 var objectTo = create$2(referenceObject);
8765
8766 for (var i in referenceObject) {
8767 if (Object.prototype.hasOwnProperty.call(referenceObject, i)) {
8768 if (_typeof_1(referenceObject[i]) == "object") {
8769 objectTo[i] = bridgeObject(referenceObject[i]);
8770 }
8771 }
8772 }
8773
8774 return objectTo;
8775}
8776/**
8777 * This method provides a stable sort implementation, very fast for presorted data.
8778 *
8779 * @param a - The array to be sorted (in-place).
8780 * @param compare - An order comparator.
8781 *
8782 * @returns The argument a.
8783 */
8784
8785
8786function insertSort(a, compare) {
8787 for (var i = 0; i < a.length; i++) {
8788 var k = a[i];
8789 var j = void 0;
8790
8791 for (j = i; j > 0 && compare(k, a[j - 1]) < 0; j--) {
8792 a[j] = a[j - 1];
8793 }
8794
8795 a[j] = k;
8796 }
8797
8798 return a;
8799}
8800/**
8801 * This is used to set the options of subobjects in the options object.
8802 *
8803 * A requirement of these subobjects is that they have an 'enabled' element
8804 * which is optional for the user but mandatory for the program.
8805 *
8806 * The added value here of the merge is that option 'enabled' is set as required.
8807 *
8808 * @param mergeTarget - Either this.options or the options used for the groups.
8809 * @param options - Options.
8810 * @param option - Option key in the options argument.
8811 * @param globalOptions - Global options, passed in to determine value of option 'enabled'.
8812 */
8813
8814
8815function mergeOptions(mergeTarget, options, option) {
8816 var globalOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; // Local helpers
8817
8818 var isPresent = function isPresent(obj) {
8819 return obj !== null && obj !== undefined;
8820 };
8821
8822 var isObject = function isObject(obj) {
8823 return obj !== null && _typeof_1(obj) === "object";
8824 }; // https://stackoverflow.com/a/34491287/1223531
8825
8826
8827 var isEmpty = function isEmpty(obj) {
8828 for (var x in obj) {
8829 if (Object.prototype.hasOwnProperty.call(obj, x)) {
8830 return false;
8831 }
8832 }
8833
8834 return true;
8835 }; // Guards
8836
8837
8838 if (!isObject(mergeTarget)) {
8839 throw new Error("Parameter mergeTarget must be an object");
8840 }
8841
8842 if (!isObject(options)) {
8843 throw new Error("Parameter options must be an object");
8844 }
8845
8846 if (!isPresent(option)) {
8847 throw new Error("Parameter option must have a value");
8848 }
8849
8850 if (!isObject(globalOptions)) {
8851 throw new Error("Parameter globalOptions must be an object");
8852 } //
8853 // Actual merge routine, separated from main logic
8854 // Only a single level of options is merged. Deeper levels are ref'd. This may actually be an issue.
8855 //
8856
8857
8858 var doMerge = function doMerge(target, options, option) {
8859 if (!isObject(target[option])) {
8860 target[option] = {};
8861 }
8862
8863 var src = options[option];
8864 var dst = target[option];
8865
8866 for (var prop in src) {
8867 if (Object.prototype.hasOwnProperty.call(src, prop)) {
8868 dst[prop] = src[prop];
8869 }
8870 }
8871 }; // Local initialization
8872
8873
8874 var srcOption = options[option];
8875 var globalPassed = isObject(globalOptions) && !isEmpty(globalOptions);
8876 var globalOption = globalPassed ? globalOptions[option] : undefined;
8877 var globalEnabled = globalOption ? globalOption.enabled : undefined; /////////////////////////////////////////
8878 // Main routine
8879 /////////////////////////////////////////
8880
8881 if (srcOption === undefined) {
8882 return; // Nothing to do
8883 }
8884
8885 if (typeof srcOption === "boolean") {
8886 if (!isObject(mergeTarget[option])) {
8887 mergeTarget[option] = {};
8888 }
8889
8890 mergeTarget[option].enabled = srcOption;
8891 return;
8892 }
8893
8894 if (srcOption === null && !isObject(mergeTarget[option])) {
8895 // If possible, explicit copy from globals
8896 if (isPresent(globalOption)) {
8897 mergeTarget[option] = create$2(globalOption);
8898 } else {
8899 return; // Nothing to do
8900 }
8901 }
8902
8903 if (!isObject(srcOption)) {
8904 return;
8905 } //
8906 // Ensure that 'enabled' is properly set. It is required internally
8907 // Note that the value from options will always overwrite the existing value
8908 //
8909
8910
8911 var enabled = true; // default value
8912
8913 if (srcOption.enabled !== undefined) {
8914 enabled = srcOption.enabled;
8915 } else {
8916 // Take from globals, if present
8917 if (globalEnabled !== undefined) {
8918 enabled = globalOption.enabled;
8919 }
8920 }
8921
8922 doMerge(mergeTarget, options, option);
8923 mergeTarget[option].enabled = enabled;
8924}
8925/**
8926 * This function does a binary search for a visible item in a sorted list. If we find a visible item, the code that uses
8927 * this function will then iterate in both directions over this sorted list to find all visible items.
8928 *
8929 * @param orderedItems - Items ordered by start
8930 * @param comparator - -1 is lower, 0 is equal, 1 is higher
8931 * @param field - Property name on an item (i.e. item[field]).
8932 * @param field2 - Second property name on an item (i.e. item[field][field2]).
8933 *
8934 * @returns Index of the found item or -1 if nothing was found.
8935 */
8936
8937
8938function binarySearchCustom(orderedItems, comparator, field, field2) {
8939 var maxIterations = 10000;
8940 var iteration = 0;
8941 var low = 0;
8942 var high = orderedItems.length - 1;
8943
8944 while (low <= high && iteration < maxIterations) {
8945 var middle = Math.floor((low + high) / 2);
8946 var item = orderedItems[middle];
8947
8948 var _value3 = field2 === undefined ? item[field] : item[field][field2];
8949
8950 var searchResult = comparator(_value3);
8951
8952 if (searchResult == 0) {
8953 // jihaa, found a visible item!
8954 return middle;
8955 } else if (searchResult == -1) {
8956 // it is too small --> increase low
8957 low = middle + 1;
8958 } else {
8959 // it is too big --> decrease high
8960 high = middle - 1;
8961 }
8962
8963 iteration++;
8964 }
8965
8966 return -1;
8967}
8968/**
8969 * This function does a binary search for a specific value in a sorted array. If it does not exist but is in between of
8970 * two values, we return either the one before or the one after, depending on user input
8971 * If it is found, we return the index, else -1.
8972 *
8973 * @param orderedItems - Sorted array.
8974 * @param target - The searched value.
8975 * @param field - Name of the property in items to be searched.
8976 * @param sidePreference - If the target is between two values, should the index of the before or the after be returned?
8977 * @param comparator - An optional comparator, returning -1, 0, 1 for <, ===, >.
8978 *
8979 * @returns The index of found value or -1 if nothing was found.
8980 */
8981
8982
8983function binarySearchValue(orderedItems, target, field, sidePreference, comparator) {
8984 var maxIterations = 10000;
8985 var iteration = 0;
8986 var low = 0;
8987 var high = orderedItems.length - 1;
8988 var prevValue;
8989 var value;
8990 var nextValue;
8991 var middle;
8992 comparator = comparator != undefined ? comparator : function (a, b) {
8993 return a == b ? 0 : a < b ? -1 : 1;
8994 };
8995
8996 while (low <= high && iteration < maxIterations) {
8997 // get a new guess
8998 middle = Math.floor(0.5 * (high + low));
8999 prevValue = orderedItems[Math.max(0, middle - 1)][field];
9000 value = orderedItems[middle][field];
9001 nextValue = orderedItems[Math.min(orderedItems.length - 1, middle + 1)][field];
9002
9003 if (comparator(value, target) == 0) {
9004 // we found the target
9005 return middle;
9006 } else if (comparator(prevValue, target) < 0 && comparator(value, target) > 0) {
9007 // target is in between of the previous and the current
9008 return sidePreference == "before" ? Math.max(0, middle - 1) : middle;
9009 } else if (comparator(value, target) < 0 && comparator(nextValue, target) > 0) {
9010 // target is in between of the current and the next
9011 return sidePreference == "before" ? middle : Math.min(orderedItems.length - 1, middle + 1);
9012 } else {
9013 // didnt find the target, we need to change our boundaries.
9014 if (comparator(value, target) < 0) {
9015 // it is too small --> increase low
9016 low = middle + 1;
9017 } else {
9018 // it is too big --> decrease high
9019 high = middle - 1;
9020 }
9021 }
9022
9023 iteration++;
9024 } // didnt find anything. Return -1.
9025
9026
9027 return -1;
9028}
9029/*
9030 * Easing Functions.
9031 * Only considering the t value for the range [0, 1] => [0, 1].
9032 *
9033 * Inspiration: from http://gizma.com/easing/
9034 * https://gist.github.com/gre/1650294
9035 */
9036
9037
9038var easingFunctions = {
9039 /**
9040 * no easing, no acceleration
9041 *
9042 * @param t - Time.
9043 *
9044 * @returns Value at time t.
9045 */
9046 linear: function linear(t) {
9047 return t;
9048 },
9049
9050 /**
9051 * accelerating from zero velocity
9052 *
9053 * @param t - Time.
9054 *
9055 * @returns Value at time t.
9056 */
9057 easeInQuad: function easeInQuad(t) {
9058 return t * t;
9059 },
9060
9061 /**
9062 * decelerating to zero velocity
9063 *
9064 * @param t - Time.
9065 *
9066 * @returns Value at time t.
9067 */
9068 easeOutQuad: function easeOutQuad(t) {
9069 return t * (2 - t);
9070 },
9071
9072 /**
9073 * acceleration until halfway, then deceleration
9074 *
9075 * @param t - Time.
9076 *
9077 * @returns Value at time t.
9078 */
9079 easeInOutQuad: function easeInOutQuad(t) {
9080 return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
9081 },
9082
9083 /**
9084 * accelerating from zero velocity
9085 *
9086 * @param t - Time.
9087 *
9088 * @returns Value at time t.
9089 */
9090 easeInCubic: function easeInCubic(t) {
9091 return t * t * t;
9092 },
9093
9094 /**
9095 * decelerating to zero velocity
9096 *
9097 * @param t - Time.
9098 *
9099 * @returns Value at time t.
9100 */
9101 easeOutCubic: function easeOutCubic(t) {
9102 return --t * t * t + 1;
9103 },
9104
9105 /**
9106 * acceleration until halfway, then deceleration
9107 *
9108 * @param t - Time.
9109 *
9110 * @returns Value at time t.
9111 */
9112 easeInOutCubic: function easeInOutCubic(t) {
9113 return t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1;
9114 },
9115
9116 /**
9117 * accelerating from zero velocity
9118 *
9119 * @param t - Time.
9120 *
9121 * @returns Value at time t.
9122 */
9123 easeInQuart: function easeInQuart(t) {
9124 return t * t * t * t;
9125 },
9126
9127 /**
9128 * decelerating to zero velocity
9129 *
9130 * @param t - Time.
9131 *
9132 * @returns Value at time t.
9133 */
9134 easeOutQuart: function easeOutQuart(t) {
9135 return 1 - --t * t * t * t;
9136 },
9137
9138 /**
9139 * acceleration until halfway, then deceleration
9140 *
9141 * @param t - Time.
9142 *
9143 * @returns Value at time t.
9144 */
9145 easeInOutQuart: function easeInOutQuart(t) {
9146 return t < 0.5 ? 8 * t * t * t * t : 1 - 8 * --t * t * t * t;
9147 },
9148
9149 /**
9150 * accelerating from zero velocity
9151 *
9152 * @param t - Time.
9153 *
9154 * @returns Value at time t.
9155 */
9156 easeInQuint: function easeInQuint(t) {
9157 return t * t * t * t * t;
9158 },
9159
9160 /**
9161 * decelerating to zero velocity
9162 *
9163 * @param t - Time.
9164 *
9165 * @returns Value at time t.
9166 */
9167 easeOutQuint: function easeOutQuint(t) {
9168 return 1 + --t * t * t * t * t;
9169 },
9170
9171 /**
9172 * acceleration until halfway, then deceleration
9173 *
9174 * @param t - Time.
9175 *
9176 * @returns Value at time t.
9177 */
9178 easeInOutQuint: function easeInOutQuint(t) {
9179 return t < 0.5 ? 16 * t * t * t * t * t : 1 + 16 * --t * t * t * t * t;
9180 }
9181};
9182/**
9183 * Experimentaly compute the width of the scrollbar for this browser.
9184 *
9185 * @returns The width in pixels.
9186 */
9187
9188function getScrollBarWidth() {
9189 var inner = document.createElement("p");
9190 inner.style.width = "100%";
9191 inner.style.height = "200px";
9192 var outer = document.createElement("div");
9193 outer.style.position = "absolute";
9194 outer.style.top = "0px";
9195 outer.style.left = "0px";
9196 outer.style.visibility = "hidden";
9197 outer.style.width = "200px";
9198 outer.style.height = "150px";
9199 outer.style.overflow = "hidden";
9200 outer.appendChild(inner);
9201 document.body.appendChild(outer);
9202 var w1 = inner.offsetWidth;
9203 outer.style.overflow = "scroll";
9204 var w2 = inner.offsetWidth;
9205
9206 if (w1 == w2) {
9207 w2 = outer.clientWidth;
9208 }
9209
9210 document.body.removeChild(outer);
9211 return w1 - w2;
9212} // @TODO: This doesn't work properly.
9213// It works only for single property objects,
9214// otherwise it combines all of the types in a union.
9215// export function topMost<K1 extends string, V1> (
9216// pile: Record<K1, undefined | V1>[],
9217// accessors: K1 | [K1]
9218// ): undefined | V1
9219// export function topMost<K1 extends string, K2 extends string, V1, V2> (
9220// pile: Record<K1, undefined | V1 | Record<K2, undefined | V2>>[],
9221// accessors: [K1, K2]
9222// ): undefined | V1 | V2
9223// export function topMost<K1 extends string, K2 extends string, K3 extends string, V1, V2, V3> (
9224// pile: Record<K1, undefined | V1 | Record<K2, undefined | V2 | Record<K3, undefined | V3>>>[],
9225// accessors: [K1, K2, K3]
9226// ): undefined | V1 | V2 | V3
9227
9228/**
9229 * Get the top most property value from a pile of objects.
9230 *
9231 * @param pile - Array of objects, no required format.
9232 * @param accessors - Array of property names (e.g. object['foo']['bar'] → ['foo', 'bar']).
9233 *
9234 * @returns Value of the property with given accessors path from the first pile item where it's not undefined.
9235 */
9236
9237
9238function topMost(pile, accessors) {
9239 var candidate;
9240
9241 if (!isArray$5(accessors)) {
9242 accessors = [accessors];
9243 }
9244
9245 var _iteratorNormalCompletion = true;
9246 var _didIteratorError = false;
9247 var _iteratorError = undefined;
9248
9249 try {
9250 for (var _iterator = getIterator$2(pile), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
9251 var member = _step.value;
9252
9253 if (member) {
9254 candidate = member[accessors[0]];
9255
9256 for (var i = 1; i < accessors.length; i++) {
9257 if (candidate) {
9258 candidate = candidate[accessors[i]];
9259 }
9260 }
9261
9262 if (typeof candidate !== "undefined") {
9263 break;
9264 }
9265 }
9266 }
9267 } catch (err) {
9268 _didIteratorError = true;
9269 _iteratorError = err;
9270 } finally {
9271 try {
9272 if (!_iteratorNormalCompletion && _iterator.return != null) {
9273 _iterator.return();
9274 }
9275 } finally {
9276 if (_didIteratorError) {
9277 throw _iteratorError;
9278 }
9279 }
9280 }
9281
9282 return candidate;
9283}
9284
9285var util =
9286/*#__PURE__*/
9287Object.freeze({
9288 isNumber: isNumber,
9289 recursiveDOMDelete: recursiveDOMDelete,
9290 isString: isString,
9291 isObject: isObject$1,
9292 isDate: isDate,
9293 isMoment: isMoment,
9294 fillIfDefined: fillIfDefined,
9295 extend: extend,
9296 selectiveExtend: selectiveExtend,
9297 selectiveDeepExtend: selectiveDeepExtend,
9298 selectiveNotDeepExtend: selectiveNotDeepExtend,
9299 deepExtend: deepExtend,
9300 equalArray: equalArray,
9301 convert: convert,
9302 getType: getType,
9303 copyAndExtendArray: copyAndExtendArray,
9304 copyArray: copyArray,
9305 getAbsoluteLeft: getAbsoluteLeft,
9306 getAbsoluteRight: getAbsoluteRight,
9307 getAbsoluteTop: getAbsoluteTop,
9308 addClassName: addClassName,
9309 removeClassName: removeClassName,
9310 forEach: forEach$3,
9311 toArray: toArray,
9312 updateProperty: updateProperty,
9313 throttle: throttle,
9314 addEventListener: addEventListener,
9315 removeEventListener: removeEventListener,
9316 preventDefault: preventDefault,
9317 getTarget: getTarget,
9318 hasParent: hasParent,
9319 option: option,
9320 hexToRGB: hexToRGB,
9321 overrideOpacity: overrideOpacity,
9322 RGBToHex: RGBToHex,
9323 parseColor: parseColor,
9324 RGBToHSV: RGBToHSV,
9325 addCssText: addCssText,
9326 removeCssText: removeCssText,
9327 HSVToRGB: HSVToRGB,
9328 HSVToHex: HSVToHex,
9329 hexToHSV: hexToHSV,
9330 isValidHex: isValidHex,
9331 isValidRGB: isValidRGB,
9332 isValidRGBA: isValidRGBA,
9333 selectiveBridgeObject: selectiveBridgeObject,
9334 bridgeObject: bridgeObject,
9335 insertSort: insertSort,
9336 mergeOptions: mergeOptions,
9337 binarySearchCustom: binarySearchCustom,
9338 binarySearchValue: binarySearchValue,
9339 easingFunctions: easingFunctions,
9340 getScrollBarWidth: getScrollBarWidth,
9341 topMost: topMost,
9342 randomUUID: uuid4
9343}); // New API (tree shakeable).
9344
9345var commonjsGlobal$1 = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
9346
9347function commonjsRequire$1 () {
9348 throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
9349}
9350
9351function createCommonjsModule$1(fn, module) {
9352 return module = { exports: {} }, fn(module, module.exports), module.exports;
9353}
9354
9355var DOMutil = createCommonjsModule$1(function (module, exports) {
9356 // DOM utility methods
9357
9358 /**
9359 * this prepares the JSON container for allocating SVG elements
9360 * @param {Object} JSONcontainer
9361 * @private
9362 */
9363 exports.prepareElements = function (JSONcontainer) {
9364 // cleanup the redundant svgElements;
9365 for (var elementType in JSONcontainer) {
9366 if (JSONcontainer.hasOwnProperty(elementType)) {
9367 JSONcontainer[elementType].redundant = JSONcontainer[elementType].used;
9368 JSONcontainer[elementType].used = [];
9369 }
9370 }
9371 };
9372 /**
9373 * this cleans up all the unused SVG elements. By asking for the parentNode, we only need to supply the JSON container from
9374 * which to remove the redundant elements.
9375 *
9376 * @param {Object} JSONcontainer
9377 * @private
9378 */
9379
9380
9381 exports.cleanupElements = function (JSONcontainer) {
9382 // cleanup the redundant svgElements;
9383 for (var elementType in JSONcontainer) {
9384 if (JSONcontainer.hasOwnProperty(elementType)) {
9385 if (JSONcontainer[elementType].redundant) {
9386 for (var i = 0; i < JSONcontainer[elementType].redundant.length; i++) {
9387 JSONcontainer[elementType].redundant[i].parentNode.removeChild(JSONcontainer[elementType].redundant[i]);
9388 }
9389
9390 JSONcontainer[elementType].redundant = [];
9391 }
9392 }
9393 }
9394 };
9395 /**
9396 * Ensures that all elements are removed first up so they can be recreated cleanly
9397 * @param {Object} JSONcontainer
9398 */
9399
9400
9401 exports.resetElements = function (JSONcontainer) {
9402 exports.prepareElements(JSONcontainer);
9403 exports.cleanupElements(JSONcontainer);
9404 exports.prepareElements(JSONcontainer);
9405 };
9406 /**
9407 * Allocate or generate an SVG element if needed. Store a reference to it in the JSON container and draw it in the svgContainer
9408 * the JSON container and the SVG container have to be supplied so other svg containers (like the legend) can use this.
9409 *
9410 * @param {string} elementType
9411 * @param {Object} JSONcontainer
9412 * @param {Object} svgContainer
9413 * @returns {Element}
9414 * @private
9415 */
9416
9417
9418 exports.getSVGElement = function (elementType, JSONcontainer, svgContainer) {
9419 var element; // allocate SVG element, if it doesnt yet exist, create one.
9420
9421 if (JSONcontainer.hasOwnProperty(elementType)) {
9422 // this element has been created before
9423 // check if there is an redundant element
9424 if (JSONcontainer[elementType].redundant.length > 0) {
9425 element = JSONcontainer[elementType].redundant[0];
9426 JSONcontainer[elementType].redundant.shift();
9427 } else {
9428 // create a new element and add it to the SVG
9429 element = document.createElementNS('http://www.w3.org/2000/svg', elementType);
9430 svgContainer.appendChild(element);
9431 }
9432 } else {
9433 // create a new element and add it to the SVG, also create a new object in the svgElements to keep track of it.
9434 element = document.createElementNS('http://www.w3.org/2000/svg', elementType);
9435 JSONcontainer[elementType] = {
9436 used: [],
9437 redundant: []
9438 };
9439 svgContainer.appendChild(element);
9440 }
9441
9442 JSONcontainer[elementType].used.push(element);
9443 return element;
9444 };
9445 /**
9446 * Allocate or generate an SVG element if needed. Store a reference to it in the JSON container and draw it in the svgContainer
9447 * the JSON container and the SVG container have to be supplied so other svg containers (like the legend) can use this.
9448 *
9449 * @param {string} elementType
9450 * @param {Object} JSONcontainer
9451 * @param {Element} DOMContainer
9452 * @param {Element} insertBefore
9453 * @returns {*}
9454 */
9455
9456
9457 exports.getDOMElement = function (elementType, JSONcontainer, DOMContainer, insertBefore) {
9458 var element; // allocate DOM element, if it doesnt yet exist, create one.
9459
9460 if (JSONcontainer.hasOwnProperty(elementType)) {
9461 // this element has been created before
9462 // check if there is an redundant element
9463 if (JSONcontainer[elementType].redundant.length > 0) {
9464 element = JSONcontainer[elementType].redundant[0];
9465 JSONcontainer[elementType].redundant.shift();
9466 } else {
9467 // create a new element and add it to the SVG
9468 element = document.createElement(elementType);
9469
9470 if (insertBefore !== undefined) {
9471 DOMContainer.insertBefore(element, insertBefore);
9472 } else {
9473 DOMContainer.appendChild(element);
9474 }
9475 }
9476 } else {
9477 // create a new element and add it to the SVG, also create a new object in the svgElements to keep track of it.
9478 element = document.createElement(elementType);
9479 JSONcontainer[elementType] = {
9480 used: [],
9481 redundant: []
9482 };
9483
9484 if (insertBefore !== undefined) {
9485 DOMContainer.insertBefore(element, insertBefore);
9486 } else {
9487 DOMContainer.appendChild(element);
9488 }
9489 }
9490
9491 JSONcontainer[elementType].used.push(element);
9492 return element;
9493 };
9494 /**
9495 * Draw a point object. This is a separate function because it can also be called by the legend.
9496 * The reason the JSONcontainer and the target SVG svgContainer have to be supplied is so the legend can use these functions
9497 * as well.
9498 *
9499 * @param {number} x
9500 * @param {number} y
9501 * @param {Object} groupTemplate: A template containing the necessary information to draw the datapoint e.g., {style: 'circle', size: 5, className: 'className' }
9502 * @param {Object} JSONcontainer
9503 * @param {Object} svgContainer
9504 * @param {Object} labelObj
9505 * @returns {vis.PointItem}
9506 */
9507
9508
9509 exports.drawPoint = function (x, y, groupTemplate, JSONcontainer, svgContainer, labelObj) {
9510 var point;
9511
9512 if (groupTemplate.style == 'circle') {
9513 point = exports.getSVGElement('circle', JSONcontainer, svgContainer);
9514 point.setAttributeNS(null, "cx", x);
9515 point.setAttributeNS(null, "cy", y);
9516 point.setAttributeNS(null, "r", 0.5 * groupTemplate.size);
9517 } else {
9518 point = exports.getSVGElement('rect', JSONcontainer, svgContainer);
9519 point.setAttributeNS(null, "x", x - 0.5 * groupTemplate.size);
9520 point.setAttributeNS(null, "y", y - 0.5 * groupTemplate.size);
9521 point.setAttributeNS(null, "width", groupTemplate.size);
9522 point.setAttributeNS(null, "height", groupTemplate.size);
9523 }
9524
9525 if (groupTemplate.styles !== undefined) {
9526 point.setAttributeNS(null, "style", groupTemplate.styles);
9527 }
9528
9529 point.setAttributeNS(null, "class", groupTemplate.className + " vis-point"); //handle label
9530
9531 if (labelObj) {
9532 var label = exports.getSVGElement('text', JSONcontainer, svgContainer);
9533
9534 if (labelObj.xOffset) {
9535 x = x + labelObj.xOffset;
9536 }
9537
9538 if (labelObj.yOffset) {
9539 y = y + labelObj.yOffset;
9540 }
9541
9542 if (labelObj.content) {
9543 label.textContent = labelObj.content;
9544 }
9545
9546 if (labelObj.className) {
9547 label.setAttributeNS(null, "class", labelObj.className + " vis-label");
9548 }
9549
9550 label.setAttributeNS(null, "x", x);
9551 label.setAttributeNS(null, "y", y);
9552 }
9553
9554 return point;
9555 };
9556 /**
9557 * draw a bar SVG element centered on the X coordinate
9558 *
9559 * @param {number} x
9560 * @param {number} y
9561 * @param {number} width
9562 * @param {number} height
9563 * @param {string} className
9564 * @param {Object} JSONcontainer
9565 * @param {Object} svgContainer
9566 * @param {string} style
9567 */
9568
9569
9570 exports.drawBar = function (x, y, width, height, className, JSONcontainer, svgContainer, style) {
9571 if (height != 0) {
9572 if (height < 0) {
9573 height *= -1;
9574 y -= height;
9575 }
9576
9577 var rect = exports.getSVGElement('rect', JSONcontainer, svgContainer);
9578 rect.setAttributeNS(null, "x", x - 0.5 * width);
9579 rect.setAttributeNS(null, "y", y);
9580 rect.setAttributeNS(null, "width", width);
9581 rect.setAttributeNS(null, "height", height);
9582 rect.setAttributeNS(null, "class", className);
9583
9584 if (style) {
9585 rect.setAttributeNS(null, "style", style);
9586 }
9587 }
9588 };
9589});
9590var DOMutil_1 = DOMutil.prepareElements;
9591var DOMutil_2 = DOMutil.cleanupElements;
9592var DOMutil_3 = DOMutil.resetElements;
9593var DOMutil_4 = DOMutil.getSVGElement;
9594var DOMutil_5 = DOMutil.getDOMElement;
9595var DOMutil_6 = DOMutil.drawPoint;
9596var DOMutil_7 = DOMutil.drawBar;
9597
9598/**
9599 * vis-data - data
9600 * http://visjs.org/
9601 *
9602 * Manage unstructured data using DataSet. Add, update, and remove data, and listen for changes in the data.
9603 *
9604 * @version 6.2.0
9605 * @date 2019-08-14T22:18:56Z
9606 *
9607 * @copyright (c) 2011-2017 Almende B.V, http://almende.com
9608 * @copyright (c) 2018-2019 visjs contributors, https://github.com/visjs
9609 *
9610 * @license
9611 * vis.js is dual licensed under both
9612 *
9613 * 1. The Apache 2.0 License
9614 * http://www.apache.org/licenses/LICENSE-2.0
9615 *
9616 * and
9617 *
9618 * 2. The MIT License
9619 * http://opensource.org/licenses/MIT
9620 *
9621 * vis.js may be distributed under either license.
9622 */
9623function createCommonjsModule$2(fn, module) {
9624 return module = {
9625 exports: {}
9626 }, fn(module, module.exports), module.exports;
9627}
9628
9629var runtime_1 = createCommonjsModule$2(function (module) {
9630 /**
9631 * Copyright (c) 2014-present, Facebook, Inc.
9632 *
9633 * This source code is licensed under the MIT license found in the
9634 * LICENSE file in the root directory of this source tree.
9635 */
9636 var runtime = function (exports) {
9637 var Op = Object.prototype;
9638 var hasOwn = Op.hasOwnProperty;
9639 var undefined$1; // More compressible than void 0.
9640
9641 var $Symbol = typeof Symbol === "function" ? Symbol : {};
9642 var iteratorSymbol = $Symbol.iterator || "@@iterator";
9643 var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
9644 var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
9645
9646 function wrap(innerFn, outerFn, self, tryLocsList) {
9647 // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
9648 var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
9649 var generator = Object.create(protoGenerator.prototype);
9650 var context = new Context(tryLocsList || []); // The ._invoke method unifies the implementations of the .next,
9651 // .throw, and .return methods.
9652
9653 generator._invoke = makeInvokeMethod(innerFn, self, context);
9654 return generator;
9655 }
9656
9657 exports.wrap = wrap; // Try/catch helper to minimize deoptimizations. Returns a completion
9658 // record like context.tryEntries[i].completion. This interface could
9659 // have been (and was previously) designed to take a closure to be
9660 // invoked without arguments, but in all the cases we care about we
9661 // already have an existing method we want to call, so there's no need
9662 // to create a new function object. We can even get away with assuming
9663 // the method takes exactly one argument, since that happens to be true
9664 // in every case, so we don't have to touch the arguments object. The
9665 // only additional allocation required is the completion record, which
9666 // has a stable shape and so hopefully should be cheap to allocate.
9667
9668 function tryCatch(fn, obj, arg) {
9669 try {
9670 return {
9671 type: "normal",
9672 arg: fn.call(obj, arg)
9673 };
9674 } catch (err) {
9675 return {
9676 type: "throw",
9677 arg: err
9678 };
9679 }
9680 }
9681
9682 var GenStateSuspendedStart = "suspendedStart";
9683 var GenStateSuspendedYield = "suspendedYield";
9684 var GenStateExecuting = "executing";
9685 var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as
9686 // breaking out of the dispatch switch statement.
9687
9688 var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and
9689 // .constructor.prototype properties for functions that return Generator
9690 // objects. For full spec compliance, you may wish to configure your
9691 // minifier not to mangle the names of these two functions.
9692
9693 function Generator() {}
9694
9695 function GeneratorFunction() {}
9696
9697 function GeneratorFunctionPrototype() {} // This is a polyfill for %IteratorPrototype% for environments that
9698 // don't natively support it.
9699
9700
9701 var IteratorPrototype = {};
9702
9703 IteratorPrototype[iteratorSymbol] = function () {
9704 return this;
9705 };
9706
9707 var getProto = Object.getPrototypeOf;
9708 var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
9709
9710 if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
9711 // This environment has a native %IteratorPrototype%; use it instead
9712 // of the polyfill.
9713 IteratorPrototype = NativeIteratorPrototype;
9714 }
9715
9716 var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
9717 GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
9718 GeneratorFunctionPrototype.constructor = GeneratorFunction;
9719 GeneratorFunctionPrototype[toStringTagSymbol] = GeneratorFunction.displayName = "GeneratorFunction"; // Helper for defining the .next, .throw, and .return methods of the
9720 // Iterator interface in terms of a single ._invoke method.
9721
9722 function defineIteratorMethods(prototype) {
9723 ["next", "throw", "return"].forEach(function (method) {
9724 prototype[method] = function (arg) {
9725 return this._invoke(method, arg);
9726 };
9727 });
9728 }
9729
9730 exports.isGeneratorFunction = function (genFun) {
9731 var ctor = typeof genFun === "function" && genFun.constructor;
9732 return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can
9733 // do is to check its .name property.
9734 (ctor.displayName || ctor.name) === "GeneratorFunction" : false;
9735 };
9736
9737 exports.mark = function (genFun) {
9738 if (Object.setPrototypeOf) {
9739 Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
9740 } else {
9741 genFun.__proto__ = GeneratorFunctionPrototype;
9742
9743 if (!(toStringTagSymbol in genFun)) {
9744 genFun[toStringTagSymbol] = "GeneratorFunction";
9745 }
9746 }
9747
9748 genFun.prototype = Object.create(Gp);
9749 return genFun;
9750 }; // Within the body of any async function, `await x` is transformed to
9751 // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
9752 // `hasOwn.call(value, "__await")` to determine if the yielded value is
9753 // meant to be awaited.
9754
9755
9756 exports.awrap = function (arg) {
9757 return {
9758 __await: arg
9759 };
9760 };
9761
9762 function AsyncIterator(generator) {
9763 function invoke(method, arg, resolve, reject) {
9764 var record = tryCatch(generator[method], generator, arg);
9765
9766 if (record.type === "throw") {
9767 reject(record.arg);
9768 } else {
9769 var result = record.arg;
9770 var value = result.value;
9771
9772 if (value && typeof value === "object" && hasOwn.call(value, "__await")) {
9773 return Promise.resolve(value.__await).then(function (value) {
9774 invoke("next", value, resolve, reject);
9775 }, function (err) {
9776 invoke("throw", err, resolve, reject);
9777 });
9778 }
9779
9780 return Promise.resolve(value).then(function (unwrapped) {
9781 // When a yielded Promise is resolved, its final value becomes
9782 // the .value of the Promise<{value,done}> result for the
9783 // current iteration.
9784 result.value = unwrapped;
9785 resolve(result);
9786 }, function (error) {
9787 // If a rejected Promise was yielded, throw the rejection back
9788 // into the async generator function so it can be handled there.
9789 return invoke("throw", error, resolve, reject);
9790 });
9791 }
9792 }
9793
9794 var previousPromise;
9795
9796 function enqueue(method, arg) {
9797 function callInvokeWithMethodAndArg() {
9798 return new Promise(function (resolve, reject) {
9799 invoke(method, arg, resolve, reject);
9800 });
9801 }
9802
9803 return previousPromise = // If enqueue has been called before, then we want to wait until
9804 // all previous Promises have been resolved before calling invoke,
9805 // so that results are always delivered in the correct order. If
9806 // enqueue has not been called before, then it is important to
9807 // call invoke immediately, without waiting on a callback to fire,
9808 // so that the async generator function has the opportunity to do
9809 // any necessary setup in a predictable way. This predictability
9810 // is why the Promise constructor synchronously invokes its
9811 // executor callback, and why async functions synchronously
9812 // execute code before the first await. Since we implement simple
9813 // async functions in terms of async generators, it is especially
9814 // important to get this right, even though it requires care.
9815 previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later
9816 // invocations of the iterator.
9817 callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
9818 } // Define the unified helper method that is used to implement .next,
9819 // .throw, and .return (see defineIteratorMethods).
9820
9821
9822 this._invoke = enqueue;
9823 }
9824
9825 defineIteratorMethods(AsyncIterator.prototype);
9826
9827 AsyncIterator.prototype[asyncIteratorSymbol] = function () {
9828 return this;
9829 };
9830
9831 exports.AsyncIterator = AsyncIterator; // Note that simple async functions are implemented on top of
9832 // AsyncIterator objects; they just return a Promise for the value of
9833 // the final result produced by the iterator.
9834
9835 exports.async = function (innerFn, outerFn, self, tryLocsList) {
9836 var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList));
9837 return exports.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator.
9838 : iter.next().then(function (result) {
9839 return result.done ? result.value : iter.next();
9840 });
9841 };
9842
9843 function makeInvokeMethod(innerFn, self, context) {
9844 var state = GenStateSuspendedStart;
9845 return function invoke(method, arg) {
9846 if (state === GenStateExecuting) {
9847 throw new Error("Generator is already running");
9848 }
9849
9850 if (state === GenStateCompleted) {
9851 if (method === "throw") {
9852 throw arg;
9853 } // Be forgiving, per 25.3.3.3.3 of the spec:
9854 // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
9855
9856
9857 return doneResult();
9858 }
9859
9860 context.method = method;
9861 context.arg = arg;
9862
9863 while (true) {
9864 var delegate = context.delegate;
9865
9866 if (delegate) {
9867 var delegateResult = maybeInvokeDelegate(delegate, context);
9868
9869 if (delegateResult) {
9870 if (delegateResult === ContinueSentinel) continue;
9871 return delegateResult;
9872 }
9873 }
9874
9875 if (context.method === "next") {
9876 // Setting context._sent for legacy support of Babel's
9877 // function.sent implementation.
9878 context.sent = context._sent = context.arg;
9879 } else if (context.method === "throw") {
9880 if (state === GenStateSuspendedStart) {
9881 state = GenStateCompleted;
9882 throw context.arg;
9883 }
9884
9885 context.dispatchException(context.arg);
9886 } else if (context.method === "return") {
9887 context.abrupt("return", context.arg);
9888 }
9889
9890 state = GenStateExecuting;
9891 var record = tryCatch(innerFn, self, context);
9892
9893 if (record.type === "normal") {
9894 // If an exception is thrown from innerFn, we leave state ===
9895 // GenStateExecuting and loop back for another invocation.
9896 state = context.done ? GenStateCompleted : GenStateSuspendedYield;
9897
9898 if (record.arg === ContinueSentinel) {
9899 continue;
9900 }
9901
9902 return {
9903 value: record.arg,
9904 done: context.done
9905 };
9906 } else if (record.type === "throw") {
9907 state = GenStateCompleted; // Dispatch the exception by looping back around to the
9908 // context.dispatchException(context.arg) call above.
9909
9910 context.method = "throw";
9911 context.arg = record.arg;
9912 }
9913 }
9914 };
9915 } // Call delegate.iterator[context.method](context.arg) and handle the
9916 // result, either by returning a { value, done } result from the
9917 // delegate iterator, or by modifying context.method and context.arg,
9918 // setting context.delegate to null, and returning the ContinueSentinel.
9919
9920
9921 function maybeInvokeDelegate(delegate, context) {
9922 var method = delegate.iterator[context.method];
9923
9924 if (method === undefined$1) {
9925 // A .throw or .return when the delegate iterator has no .throw
9926 // method always terminates the yield* loop.
9927 context.delegate = null;
9928
9929 if (context.method === "throw") {
9930 // Note: ["return"] must be used for ES3 parsing compatibility.
9931 if (delegate.iterator["return"]) {
9932 // If the delegate iterator has a return method, give it a
9933 // chance to clean up.
9934 context.method = "return";
9935 context.arg = undefined$1;
9936 maybeInvokeDelegate(delegate, context);
9937
9938 if (context.method === "throw") {
9939 // If maybeInvokeDelegate(context) changed context.method from
9940 // "return" to "throw", let that override the TypeError below.
9941 return ContinueSentinel;
9942 }
9943 }
9944
9945 context.method = "throw";
9946 context.arg = new TypeError("The iterator does not provide a 'throw' method");
9947 }
9948
9949 return ContinueSentinel;
9950 }
9951
9952 var record = tryCatch(method, delegate.iterator, context.arg);
9953
9954 if (record.type === "throw") {
9955 context.method = "throw";
9956 context.arg = record.arg;
9957 context.delegate = null;
9958 return ContinueSentinel;
9959 }
9960
9961 var info = record.arg;
9962
9963 if (!info) {
9964 context.method = "throw";
9965 context.arg = new TypeError("iterator result is not an object");
9966 context.delegate = null;
9967 return ContinueSentinel;
9968 }
9969
9970 if (info.done) {
9971 // Assign the result of the finished delegate to the temporary
9972 // variable specified by delegate.resultName (see delegateYield).
9973 context[delegate.resultName] = info.value; // Resume execution at the desired location (see delegateYield).
9974
9975 context.next = delegate.nextLoc; // If context.method was "throw" but the delegate handled the
9976 // exception, let the outer generator proceed normally. If
9977 // context.method was "next", forget context.arg since it has been
9978 // "consumed" by the delegate iterator. If context.method was
9979 // "return", allow the original .return call to continue in the
9980 // outer generator.
9981
9982 if (context.method !== "return") {
9983 context.method = "next";
9984 context.arg = undefined$1;
9985 }
9986 } else {
9987 // Re-yield the result returned by the delegate method.
9988 return info;
9989 } // The delegate iterator is finished, so forget it and continue with
9990 // the outer generator.
9991
9992
9993 context.delegate = null;
9994 return ContinueSentinel;
9995 } // Define Generator.prototype.{next,throw,return} in terms of the
9996 // unified ._invoke helper method.
9997
9998
9999 defineIteratorMethods(Gp);
10000 Gp[toStringTagSymbol] = "Generator"; // A Generator should always return itself as the iterator object when the
10001 // @@iterator function is called on it. Some browsers' implementations of the
10002 // iterator prototype chain incorrectly implement this, causing the Generator
10003 // object to not be returned from this call. This ensures that doesn't happen.
10004 // See https://github.com/facebook/regenerator/issues/274 for more details.
10005
10006 Gp[iteratorSymbol] = function () {
10007 return this;
10008 };
10009
10010 Gp.toString = function () {
10011 return "[object Generator]";
10012 };
10013
10014 function pushTryEntry(locs) {
10015 var entry = {
10016 tryLoc: locs[0]
10017 };
10018
10019 if (1 in locs) {
10020 entry.catchLoc = locs[1];
10021 }
10022
10023 if (2 in locs) {
10024 entry.finallyLoc = locs[2];
10025 entry.afterLoc = locs[3];
10026 }
10027
10028 this.tryEntries.push(entry);
10029 }
10030
10031 function resetTryEntry(entry) {
10032 var record = entry.completion || {};
10033 record.type = "normal";
10034 delete record.arg;
10035 entry.completion = record;
10036 }
10037
10038 function Context(tryLocsList) {
10039 // The root entry object (effectively a try statement without a catch
10040 // or a finally block) gives us a place to store values thrown from
10041 // locations where there is no enclosing try statement.
10042 this.tryEntries = [{
10043 tryLoc: "root"
10044 }];
10045 tryLocsList.forEach(pushTryEntry, this);
10046 this.reset(true);
10047 }
10048
10049 exports.keys = function (object) {
10050 var keys = [];
10051
10052 for (var key in object) {
10053 keys.push(key);
10054 }
10055
10056 keys.reverse(); // Rather than returning an object with a next method, we keep
10057 // things simple and return the next function itself.
10058
10059 return function next() {
10060 while (keys.length) {
10061 var key = keys.pop();
10062
10063 if (key in object) {
10064 next.value = key;
10065 next.done = false;
10066 return next;
10067 }
10068 } // To avoid creating an additional object, we just hang the .value
10069 // and .done properties off the next function object itself. This
10070 // also ensures that the minifier will not anonymize the function.
10071
10072
10073 next.done = true;
10074 return next;
10075 };
10076 };
10077
10078 function values(iterable) {
10079 if (iterable) {
10080 var iteratorMethod = iterable[iteratorSymbol];
10081
10082 if (iteratorMethod) {
10083 return iteratorMethod.call(iterable);
10084 }
10085
10086 if (typeof iterable.next === "function") {
10087 return iterable;
10088 }
10089
10090 if (!isNaN(iterable.length)) {
10091 var i = -1,
10092 next = function next() {
10093 while (++i < iterable.length) {
10094 if (hasOwn.call(iterable, i)) {
10095 next.value = iterable[i];
10096 next.done = false;
10097 return next;
10098 }
10099 }
10100
10101 next.value = undefined$1;
10102 next.done = true;
10103 return next;
10104 };
10105
10106 return next.next = next;
10107 }
10108 } // Return an iterator with no values.
10109
10110
10111 return {
10112 next: doneResult
10113 };
10114 }
10115
10116 exports.values = values;
10117
10118 function doneResult() {
10119 return {
10120 value: undefined$1,
10121 done: true
10122 };
10123 }
10124
10125 Context.prototype = {
10126 constructor: Context,
10127 reset: function (skipTempReset) {
10128 this.prev = 0;
10129 this.next = 0; // Resetting context._sent for legacy support of Babel's
10130 // function.sent implementation.
10131
10132 this.sent = this._sent = undefined$1;
10133 this.done = false;
10134 this.delegate = null;
10135 this.method = "next";
10136 this.arg = undefined$1;
10137 this.tryEntries.forEach(resetTryEntry);
10138
10139 if (!skipTempReset) {
10140 for (var name in this) {
10141 // Not sure about the optimal order of these conditions:
10142 if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) {
10143 this[name] = undefined$1;
10144 }
10145 }
10146 }
10147 },
10148 stop: function () {
10149 this.done = true;
10150 var rootEntry = this.tryEntries[0];
10151 var rootRecord = rootEntry.completion;
10152
10153 if (rootRecord.type === "throw") {
10154 throw rootRecord.arg;
10155 }
10156
10157 return this.rval;
10158 },
10159 dispatchException: function (exception) {
10160 if (this.done) {
10161 throw exception;
10162 }
10163
10164 var context = this;
10165
10166 function handle(loc, caught) {
10167 record.type = "throw";
10168 record.arg = exception;
10169 context.next = loc;
10170
10171 if (caught) {
10172 // If the dispatched exception was caught by a catch block,
10173 // then let that catch block handle the exception normally.
10174 context.method = "next";
10175 context.arg = undefined$1;
10176 }
10177
10178 return !!caught;
10179 }
10180
10181 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
10182 var entry = this.tryEntries[i];
10183 var record = entry.completion;
10184
10185 if (entry.tryLoc === "root") {
10186 // Exception thrown outside of any try block that could handle
10187 // it, so set the completion value of the entire function to
10188 // throw the exception.
10189 return handle("end");
10190 }
10191
10192 if (entry.tryLoc <= this.prev) {
10193 var hasCatch = hasOwn.call(entry, "catchLoc");
10194 var hasFinally = hasOwn.call(entry, "finallyLoc");
10195
10196 if (hasCatch && hasFinally) {
10197 if (this.prev < entry.catchLoc) {
10198 return handle(entry.catchLoc, true);
10199 } else if (this.prev < entry.finallyLoc) {
10200 return handle(entry.finallyLoc);
10201 }
10202 } else if (hasCatch) {
10203 if (this.prev < entry.catchLoc) {
10204 return handle(entry.catchLoc, true);
10205 }
10206 } else if (hasFinally) {
10207 if (this.prev < entry.finallyLoc) {
10208 return handle(entry.finallyLoc);
10209 }
10210 } else {
10211 throw new Error("try statement without catch or finally");
10212 }
10213 }
10214 }
10215 },
10216 abrupt: function (type, arg) {
10217 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
10218 var entry = this.tryEntries[i];
10219
10220 if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
10221 var finallyEntry = entry;
10222 break;
10223 }
10224 }
10225
10226 if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) {
10227 // Ignore the finally entry if control is not jumping to a
10228 // location outside the try/catch block.
10229 finallyEntry = null;
10230 }
10231
10232 var record = finallyEntry ? finallyEntry.completion : {};
10233 record.type = type;
10234 record.arg = arg;
10235
10236 if (finallyEntry) {
10237 this.method = "next";
10238 this.next = finallyEntry.finallyLoc;
10239 return ContinueSentinel;
10240 }
10241
10242 return this.complete(record);
10243 },
10244 complete: function (record, afterLoc) {
10245 if (record.type === "throw") {
10246 throw record.arg;
10247 }
10248
10249 if (record.type === "break" || record.type === "continue") {
10250 this.next = record.arg;
10251 } else if (record.type === "return") {
10252 this.rval = this.arg = record.arg;
10253 this.method = "return";
10254 this.next = "end";
10255 } else if (record.type === "normal" && afterLoc) {
10256 this.next = afterLoc;
10257 }
10258
10259 return ContinueSentinel;
10260 },
10261 finish: function (finallyLoc) {
10262 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
10263 var entry = this.tryEntries[i];
10264
10265 if (entry.finallyLoc === finallyLoc) {
10266 this.complete(entry.completion, entry.afterLoc);
10267 resetTryEntry(entry);
10268 return ContinueSentinel;
10269 }
10270 }
10271 },
10272 "catch": function (tryLoc) {
10273 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
10274 var entry = this.tryEntries[i];
10275
10276 if (entry.tryLoc === tryLoc) {
10277 var record = entry.completion;
10278
10279 if (record.type === "throw") {
10280 var thrown = record.arg;
10281 resetTryEntry(entry);
10282 }
10283
10284 return thrown;
10285 }
10286 } // The context.catch method must only be called with a location
10287 // argument that corresponds to a known catch block.
10288
10289
10290 throw new Error("illegal catch attempt");
10291 },
10292 delegateYield: function (iterable, resultName, nextLoc) {
10293 this.delegate = {
10294 iterator: values(iterable),
10295 resultName: resultName,
10296 nextLoc: nextLoc
10297 };
10298
10299 if (this.method === "next") {
10300 // Deliberately forget the last sent value so that we don't
10301 // accidentally pass it on to the delegate.
10302 this.arg = undefined$1;
10303 }
10304
10305 return ContinueSentinel;
10306 }
10307 }; // Regardless of whether this script is executing as a CommonJS module
10308 // or not, return the runtime object so that we can declare the variable
10309 // regeneratorRuntime in the outer scope, which allows this module to be
10310 // injected easily by `bin/regenerator --include-runtime script.js`.
10311
10312 return exports;
10313 }( // If this script is executing as a CommonJS module, use module.exports
10314 // as the regeneratorRuntime namespace. Otherwise create a new empty
10315 // object. Either way, the resulting object will be used to initialize
10316 // the regeneratorRuntime variable at the top of this file.
10317 module.exports);
10318
10319 try {
10320 regeneratorRuntime = runtime;
10321 } catch (accidentalStrictMode) {
10322 // This module should not be running in strict mode, so the above
10323 // assignment should always work unless something is misconfigured. Just
10324 // in case runtime.js accidentally runs in strict mode, we can escape
10325 // strict mode using a global Function call. This could conceivably fail
10326 // if a Content Security Policy forbids using Function, but in that case
10327 // the proper solution is to fix the accidental strict mode problem. If
10328 // you've misconfigured your bundler to force strict mode and applied a
10329 // CSP to forbid Function, and you're not willing to fix either of those
10330 // problems, please detail your unique predicament in a GitHub issue.
10331 Function("r", "regeneratorRuntime = r")(runtime);
10332 }
10333});
10334var regenerator = runtime_1;
10335
10336function _defineProperty$1(obj, key, value) {
10337 if (key in obj) {
10338 Object.defineProperty(obj, key, {
10339 value: value,
10340 enumerable: true,
10341 configurable: true,
10342 writable: true
10343 });
10344 } else {
10345 obj[key] = value;
10346 }
10347
10348 return obj;
10349}
10350
10351var defineProperty$7 = _defineProperty$1;
10352
10353function _arrayWithoutHoles$1(arr) {
10354 if (Array.isArray(arr)) {
10355 for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
10356 arr2[i] = arr[i];
10357 }
10358
10359 return arr2;
10360 }
10361}
10362
10363var arrayWithoutHoles$1 = _arrayWithoutHoles$1;
10364
10365function _iterableToArray$1(iter) {
10366 if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
10367}
10368
10369var iterableToArray$1 = _iterableToArray$1;
10370
10371function _nonIterableSpread$1() {
10372 throw new TypeError("Invalid attempt to spread non-iterable instance");
10373}
10374
10375var nonIterableSpread$1 = _nonIterableSpread$1;
10376
10377function _toConsumableArray$1(arr) {
10378 return arrayWithoutHoles$1(arr) || iterableToArray$1(arr) || nonIterableSpread$1();
10379}
10380
10381var toConsumableArray$1 = _toConsumableArray$1;
10382
10383var _typeof_1$1 = createCommonjsModule$2(function (module) {
10384 function _typeof2(obj) {
10385 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
10386 _typeof2 = function _typeof2(obj) {
10387 return typeof obj;
10388 };
10389 } else {
10390 _typeof2 = function _typeof2(obj) {
10391 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
10392 };
10393 }
10394
10395 return _typeof2(obj);
10396 }
10397
10398 function _typeof(obj) {
10399 if (typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol") {
10400 module.exports = _typeof = function _typeof(obj) {
10401 return _typeof2(obj);
10402 };
10403 } else {
10404 module.exports = _typeof = function _typeof(obj) {
10405 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof2(obj);
10406 };
10407 }
10408
10409 return _typeof(obj);
10410 }
10411
10412 module.exports = _typeof;
10413});
10414
10415function _classCallCheck(instance, Constructor) {
10416 if (!(instance instanceof Constructor)) {
10417 throw new TypeError("Cannot call a class as a function");
10418 }
10419}
10420
10421var classCallCheck = _classCallCheck;
10422
10423function _defineProperties(target, props) {
10424 for (var i = 0; i < props.length; i++) {
10425 var descriptor = props[i];
10426 descriptor.enumerable = descriptor.enumerable || false;
10427 descriptor.configurable = true;
10428 if ("value" in descriptor) descriptor.writable = true;
10429 Object.defineProperty(target, descriptor.key, descriptor);
10430 }
10431}
10432
10433function _createClass(Constructor, protoProps, staticProps) {
10434 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
10435 if (staticProps) _defineProperties(Constructor, staticProps);
10436 return Constructor;
10437}
10438
10439var createClass = _createClass;
10440
10441function _assertThisInitialized(self) {
10442 if (self === void 0) {
10443 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
10444 }
10445
10446 return self;
10447}
10448
10449var assertThisInitialized = _assertThisInitialized;
10450
10451function _possibleConstructorReturn(self, call) {
10452 if (call && (_typeof_1$1(call) === "object" || typeof call === "function")) {
10453 return call;
10454 }
10455
10456 return assertThisInitialized(self);
10457}
10458
10459var possibleConstructorReturn = _possibleConstructorReturn;
10460var getPrototypeOf$3 = createCommonjsModule$2(function (module) {
10461 function _getPrototypeOf(o) {
10462 module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
10463 return o.__proto__ || Object.getPrototypeOf(o);
10464 };
10465 return _getPrototypeOf(o);
10466 }
10467
10468 module.exports = _getPrototypeOf;
10469});
10470var setPrototypeOf = createCommonjsModule$2(function (module) {
10471 function _setPrototypeOf(o, p) {
10472 module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
10473 o.__proto__ = p;
10474 return o;
10475 };
10476
10477 return _setPrototypeOf(o, p);
10478 }
10479
10480 module.exports = _setPrototypeOf;
10481});
10482
10483function _inherits(subClass, superClass) {
10484 if (typeof superClass !== "function" && superClass !== null) {
10485 throw new TypeError("Super expression must either be null or a function");
10486 }
10487
10488 subClass.prototype = Object.create(superClass && superClass.prototype, {
10489 constructor: {
10490 value: subClass,
10491 writable: true,
10492 configurable: true
10493 }
10494 });
10495 if (superClass) setPrototypeOf(subClass, superClass);
10496}
10497
10498var inherits = _inherits; // Maps for number <-> hex string conversion
10499
10500var byteToHex$2 = [];
10501
10502for (var i$2 = 0; i$2 < 256; i$2++) {
10503 byteToHex$2[i$2] = (i$2 + 0x100).toString(16).substr(1);
10504}
10505/**
10506 * Represent binary UUID into it's string representation.
10507 *
10508 * @param buf - Buffer containing UUID bytes.
10509 * @param offset - Offset from the start of the buffer where the UUID is saved (not needed if the buffer starts with the UUID).
10510 *
10511 * @returns String representation of the UUID.
10512 */
10513
10514
10515function stringifyUUID$1(buf, offset) {
10516 var i = offset || 0;
10517 var bth = byteToHex$2;
10518 return bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]];
10519}
10520/**
10521 * Generate 16 random bytes to be used as a base for UUID.
10522 *
10523 * @ignore
10524 */
10525
10526
10527var random$1 = function () {
10528 if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
10529 // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto
10530 // Moderately fast, high quality
10531 var _rnds8 = new Uint8Array(16);
10532
10533 return function whatwgRNG() {
10534 crypto.getRandomValues(_rnds8);
10535 return _rnds8;
10536 };
10537 } // Math.random()-based (RNG)
10538 //
10539 // If all else fails, use Math.random().
10540 // It's fast, but is of unspecified quality.
10541
10542
10543 var _rnds = new Array(16);
10544
10545 return function () {
10546 for (var i = 0, r; i < 16; i++) {
10547 if ((i & 0x03) === 0) {
10548 r = Math.random() * 0x100000000;
10549 }
10550
10551 _rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
10552 }
10553
10554 return _rnds;
10555 }; // uuid.js
10556 //
10557 // Copyright (c) 2010-2012 Robert Kieffer
10558 // MIT License - http://opensource.org/licenses/mit-license.php
10559 // Unique ID creation requires a high quality random # generator. We feature
10560 // detect to determine the best RNG source, normalizing to a function that
10561 // returns 128-bits of randomness, since that's what's usually required
10562 // return require('./rng');
10563}();
10564
10565var byteToHex$1$1 = [];
10566
10567for (var i$1$1 = 0; i$1$1 < 256; i$1$1++) {
10568 byteToHex$1$1[i$1$1] = (i$1$1 + 0x100).toString(16).substr(1);
10569} // **`v1()` - Generate time-based UUID**
10570//
10571// Inspired by https://github.com/LiosK/UUID.js
10572// and http://docs.python.org/library/uuid.html
10573// random #'s we need to init node and clockseq
10574
10575
10576var seedBytes$1 = random$1(); // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
10577
10578var defaultNodeId$1 = [seedBytes$1[0] | 0x01, seedBytes$1[1], seedBytes$1[2], seedBytes$1[3], seedBytes$1[4], seedBytes$1[5]]; // Per 4.2.2, randomize (14 bit) clockseq
10579
10580var defaultClockseq$1 = (seedBytes$1[6] << 8 | seedBytes$1[7]) & 0x3fff; // Previous uuid creation time
10581
10582/**
10583 * UUIDv4 options.
10584 */
10585
10586/**
10587 * Generate UUIDv4
10588 *
10589 * @param options - Options to be used instead of default generated values.
10590 * String 'binary' is a shorthand for uuid4({}, new Array(16)).
10591 * @param buf - If present the buffer will be filled with the generated UUID.
10592 * @param offset - Offset of the UUID from the start of the buffer.
10593 *
10594 * @returns UUIDv4
10595 */
10596
10597function uuid4$1() {
10598 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
10599 var buf = arguments.length > 1 ? arguments[1] : undefined;
10600 var offset = arguments.length > 2 ? arguments[2] : undefined; // Deprecated - 'format' argument, as supported in v1.2
10601
10602 var i = buf && offset || 0;
10603
10604 if (typeof options === 'string') {
10605 buf = options === 'binary' ? new Array(16) : undefined;
10606 options = {};
10607 }
10608
10609 var rnds = options.random || (options.rng || random$1)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
10610
10611 rnds[6] = rnds[6] & 0x0f | 0x40;
10612 rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
10613
10614 if (buf) {
10615 for (var ii = 0; ii < 16; ii++) {
10616 buf[i + ii] = rnds[ii];
10617 }
10618 }
10619
10620 return buf || stringifyUUID$1(rnds);
10621} // Rollup will complain about mixing default and named exports in UMD build,
10622
10623
10624function _typeof(obj) {
10625 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
10626 _typeof = function (obj) {
10627 return typeof obj;
10628 };
10629 } else {
10630 _typeof = function (obj) {
10631 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
10632 };
10633 }
10634
10635 return _typeof(obj);
10636}
10637
10638var commonjsGlobal$2 = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
10639
10640function commonjsRequire$2() {
10641 throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
10642}
10643
10644function createCommonjsModule$1$1(fn, module) {
10645 return module = {
10646 exports: {}
10647 }, fn(module, module.exports), module.exports;
10648}
10649
10650var moment$1 = createCommonjsModule$1$1(function (module, exports) {
10651 (function (global, factory) {
10652 module.exports = factory();
10653 })(commonjsGlobal$2, function () {
10654 var hookCallback;
10655
10656 function hooks() {
10657 return hookCallback.apply(null, arguments);
10658 } // This is done to register the method called with moment()
10659 // without creating circular dependencies.
10660
10661
10662 function setHookCallback(callback) {
10663 hookCallback = callback;
10664 }
10665
10666 function isArray(input) {
10667 return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]';
10668 }
10669
10670 function isObject(input) {
10671 // IE8 will treat undefined and null as object if it wasn't for
10672 // input != null
10673 return input != null && Object.prototype.toString.call(input) === '[object Object]';
10674 }
10675
10676 function isObjectEmpty(obj) {
10677 if (Object.getOwnPropertyNames) {
10678 return Object.getOwnPropertyNames(obj).length === 0;
10679 } else {
10680 var k;
10681
10682 for (k in obj) {
10683 if (obj.hasOwnProperty(k)) {
10684 return false;
10685 }
10686 }
10687
10688 return true;
10689 }
10690 }
10691
10692 function isUndefined(input) {
10693 return input === void 0;
10694 }
10695
10696 function isNumber(input) {
10697 return typeof input === 'number' || Object.prototype.toString.call(input) === '[object Number]';
10698 }
10699
10700 function isDate(input) {
10701 return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
10702 }
10703
10704 function map(arr, fn) {
10705 var res = [],
10706 i;
10707
10708 for (i = 0; i < arr.length; ++i) {
10709 res.push(fn(arr[i], i));
10710 }
10711
10712 return res;
10713 }
10714
10715 function hasOwnProp(a, b) {
10716 return Object.prototype.hasOwnProperty.call(a, b);
10717 }
10718
10719 function extend(a, b) {
10720 for (var i in b) {
10721 if (hasOwnProp(b, i)) {
10722 a[i] = b[i];
10723 }
10724 }
10725
10726 if (hasOwnProp(b, 'toString')) {
10727 a.toString = b.toString;
10728 }
10729
10730 if (hasOwnProp(b, 'valueOf')) {
10731 a.valueOf = b.valueOf;
10732 }
10733
10734 return a;
10735 }
10736
10737 function createUTC(input, format, locale, strict) {
10738 return createLocalOrUTC(input, format, locale, strict, true).utc();
10739 }
10740
10741 function defaultParsingFlags() {
10742 // We need to deep clone this object.
10743 return {
10744 empty: false,
10745 unusedTokens: [],
10746 unusedInput: [],
10747 overflow: -2,
10748 charsLeftOver: 0,
10749 nullInput: false,
10750 invalidMonth: null,
10751 invalidFormat: false,
10752 userInvalidated: false,
10753 iso: false,
10754 parsedDateParts: [],
10755 meridiem: null,
10756 rfc2822: false,
10757 weekdayMismatch: false
10758 };
10759 }
10760
10761 function getParsingFlags(m) {
10762 if (m._pf == null) {
10763 m._pf = defaultParsingFlags();
10764 }
10765
10766 return m._pf;
10767 }
10768
10769 var some;
10770
10771 if (Array.prototype.some) {
10772 some = Array.prototype.some;
10773 } else {
10774 some = function (fun) {
10775 var t = Object(this);
10776 var len = t.length >>> 0;
10777
10778 for (var i = 0; i < len; i++) {
10779 if (i in t && fun.call(this, t[i], i, t)) {
10780 return true;
10781 }
10782 }
10783
10784 return false;
10785 };
10786 }
10787
10788 function isValid(m) {
10789 if (m._isValid == null) {
10790 var flags = getParsingFlags(m);
10791 var parsedParts = some.call(flags.parsedDateParts, function (i) {
10792 return i != null;
10793 });
10794 var isNowValid = !isNaN(m._d.getTime()) && flags.overflow < 0 && !flags.empty && !flags.invalidMonth && !flags.invalidWeekday && !flags.weekdayMismatch && !flags.nullInput && !flags.invalidFormat && !flags.userInvalidated && (!flags.meridiem || flags.meridiem && parsedParts);
10795
10796 if (m._strict) {
10797 isNowValid = isNowValid && flags.charsLeftOver === 0 && flags.unusedTokens.length === 0 && flags.bigHour === undefined;
10798 }
10799
10800 if (Object.isFrozen == null || !Object.isFrozen(m)) {
10801 m._isValid = isNowValid;
10802 } else {
10803 return isNowValid;
10804 }
10805 }
10806
10807 return m._isValid;
10808 }
10809
10810 function createInvalid(flags) {
10811 var m = createUTC(NaN);
10812
10813 if (flags != null) {
10814 extend(getParsingFlags(m), flags);
10815 } else {
10816 getParsingFlags(m).userInvalidated = true;
10817 }
10818
10819 return m;
10820 } // Plugins that add properties should also add the key here (null value),
10821 // so we can properly clone ourselves.
10822
10823
10824 var momentProperties = hooks.momentProperties = [];
10825
10826 function copyConfig(to, from) {
10827 var i, prop, val;
10828
10829 if (!isUndefined(from._isAMomentObject)) {
10830 to._isAMomentObject = from._isAMomentObject;
10831 }
10832
10833 if (!isUndefined(from._i)) {
10834 to._i = from._i;
10835 }
10836
10837 if (!isUndefined(from._f)) {
10838 to._f = from._f;
10839 }
10840
10841 if (!isUndefined(from._l)) {
10842 to._l = from._l;
10843 }
10844
10845 if (!isUndefined(from._strict)) {
10846 to._strict = from._strict;
10847 }
10848
10849 if (!isUndefined(from._tzm)) {
10850 to._tzm = from._tzm;
10851 }
10852
10853 if (!isUndefined(from._isUTC)) {
10854 to._isUTC = from._isUTC;
10855 }
10856
10857 if (!isUndefined(from._offset)) {
10858 to._offset = from._offset;
10859 }
10860
10861 if (!isUndefined(from._pf)) {
10862 to._pf = getParsingFlags(from);
10863 }
10864
10865 if (!isUndefined(from._locale)) {
10866 to._locale = from._locale;
10867 }
10868
10869 if (momentProperties.length > 0) {
10870 for (i = 0; i < momentProperties.length; i++) {
10871 prop = momentProperties[i];
10872 val = from[prop];
10873
10874 if (!isUndefined(val)) {
10875 to[prop] = val;
10876 }
10877 }
10878 }
10879
10880 return to;
10881 }
10882
10883 var updateInProgress = false; // Moment prototype object
10884
10885 function Moment(config) {
10886 copyConfig(this, config);
10887 this._d = new Date(config._d != null ? config._d.getTime() : NaN);
10888
10889 if (!this.isValid()) {
10890 this._d = new Date(NaN);
10891 } // Prevent infinite loop in case updateOffset creates new moment
10892 // objects.
10893
10894
10895 if (updateInProgress === false) {
10896 updateInProgress = true;
10897 hooks.updateOffset(this);
10898 updateInProgress = false;
10899 }
10900 }
10901
10902 function isMoment(obj) {
10903 return obj instanceof Moment || obj != null && obj._isAMomentObject != null;
10904 }
10905
10906 function absFloor(number) {
10907 if (number < 0) {
10908 // -0 -> 0
10909 return Math.ceil(number) || 0;
10910 } else {
10911 return Math.floor(number);
10912 }
10913 }
10914
10915 function toInt(argumentForCoercion) {
10916 var coercedNumber = +argumentForCoercion,
10917 value = 0;
10918
10919 if (coercedNumber !== 0 && isFinite(coercedNumber)) {
10920 value = absFloor(coercedNumber);
10921 }
10922
10923 return value;
10924 } // compare two arrays, return the number of differences
10925
10926
10927 function compareArrays(array1, array2, dontConvert) {
10928 var len = Math.min(array1.length, array2.length),
10929 lengthDiff = Math.abs(array1.length - array2.length),
10930 diffs = 0,
10931 i;
10932
10933 for (i = 0; i < len; i++) {
10934 if (dontConvert && array1[i] !== array2[i] || !dontConvert && toInt(array1[i]) !== toInt(array2[i])) {
10935 diffs++;
10936 }
10937 }
10938
10939 return diffs + lengthDiff;
10940 }
10941
10942 function warn(msg) {
10943 if (hooks.suppressDeprecationWarnings === false && typeof console !== 'undefined' && console.warn) {
10944 console.warn('Deprecation warning: ' + msg);
10945 }
10946 }
10947
10948 function deprecate(msg, fn) {
10949 var firstTime = true;
10950 return extend(function () {
10951 if (hooks.deprecationHandler != null) {
10952 hooks.deprecationHandler(null, msg);
10953 }
10954
10955 if (firstTime) {
10956 var args = [];
10957 var arg;
10958
10959 for (var i = 0; i < arguments.length; i++) {
10960 arg = '';
10961
10962 if (typeof arguments[i] === 'object') {
10963 arg += '\n[' + i + '] ';
10964
10965 for (var key in arguments[0]) {
10966 arg += key + ': ' + arguments[0][key] + ', ';
10967 }
10968
10969 arg = arg.slice(0, -2); // Remove trailing comma and space
10970 } else {
10971 arg = arguments[i];
10972 }
10973
10974 args.push(arg);
10975 }
10976
10977 warn(msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + new Error().stack);
10978 firstTime = false;
10979 }
10980
10981 return fn.apply(this, arguments);
10982 }, fn);
10983 }
10984
10985 var deprecations = {};
10986
10987 function deprecateSimple(name, msg) {
10988 if (hooks.deprecationHandler != null) {
10989 hooks.deprecationHandler(name, msg);
10990 }
10991
10992 if (!deprecations[name]) {
10993 warn(msg);
10994 deprecations[name] = true;
10995 }
10996 }
10997
10998 hooks.suppressDeprecationWarnings = false;
10999 hooks.deprecationHandler = null;
11000
11001 function isFunction(input) {
11002 return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
11003 }
11004
11005 function set(config) {
11006 var prop, i;
11007
11008 for (i in config) {
11009 prop = config[i];
11010
11011 if (isFunction(prop)) {
11012 this[i] = prop;
11013 } else {
11014 this['_' + i] = prop;
11015 }
11016 }
11017
11018 this._config = config; // Lenient ordinal parsing accepts just a number in addition to
11019 // number + (possibly) stuff coming from _dayOfMonthOrdinalParse.
11020 // TODO: Remove "ordinalParse" fallback in next major release.
11021
11022 this._dayOfMonthOrdinalParseLenient = new RegExp((this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + '|' + /\d{1,2}/.source);
11023 }
11024
11025 function mergeConfigs(parentConfig, childConfig) {
11026 var res = extend({}, parentConfig),
11027 prop;
11028
11029 for (prop in childConfig) {
11030 if (hasOwnProp(childConfig, prop)) {
11031 if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
11032 res[prop] = {};
11033 extend(res[prop], parentConfig[prop]);
11034 extend(res[prop], childConfig[prop]);
11035 } else if (childConfig[prop] != null) {
11036 res[prop] = childConfig[prop];
11037 } else {
11038 delete res[prop];
11039 }
11040 }
11041 }
11042
11043 for (prop in parentConfig) {
11044 if (hasOwnProp(parentConfig, prop) && !hasOwnProp(childConfig, prop) && isObject(parentConfig[prop])) {
11045 // make sure changes to properties don't modify parent config
11046 res[prop] = extend({}, res[prop]);
11047 }
11048 }
11049
11050 return res;
11051 }
11052
11053 function Locale(config) {
11054 if (config != null) {
11055 this.set(config);
11056 }
11057 }
11058
11059 var keys;
11060
11061 if (Object.keys) {
11062 keys = Object.keys;
11063 } else {
11064 keys = function (obj) {
11065 var i,
11066 res = [];
11067
11068 for (i in obj) {
11069 if (hasOwnProp(obj, i)) {
11070 res.push(i);
11071 }
11072 }
11073
11074 return res;
11075 };
11076 }
11077
11078 var defaultCalendar = {
11079 sameDay: '[Today at] LT',
11080 nextDay: '[Tomorrow at] LT',
11081 nextWeek: 'dddd [at] LT',
11082 lastDay: '[Yesterday at] LT',
11083 lastWeek: '[Last] dddd [at] LT',
11084 sameElse: 'L'
11085 };
11086
11087 function calendar(key, mom, now) {
11088 var output = this._calendar[key] || this._calendar['sameElse'];
11089 return isFunction(output) ? output.call(mom, now) : output;
11090 }
11091
11092 var defaultLongDateFormat = {
11093 LTS: 'h:mm:ss A',
11094 LT: 'h:mm A',
11095 L: 'MM/DD/YYYY',
11096 LL: 'MMMM D, YYYY',
11097 LLL: 'MMMM D, YYYY h:mm A',
11098 LLLL: 'dddd, MMMM D, YYYY h:mm A'
11099 };
11100
11101 function longDateFormat(key) {
11102 var format = this._longDateFormat[key],
11103 formatUpper = this._longDateFormat[key.toUpperCase()];
11104
11105 if (format || !formatUpper) {
11106 return format;
11107 }
11108
11109 this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) {
11110 return val.slice(1);
11111 });
11112 return this._longDateFormat[key];
11113 }
11114
11115 var defaultInvalidDate = 'Invalid date';
11116
11117 function invalidDate() {
11118 return this._invalidDate;
11119 }
11120
11121 var defaultOrdinal = '%d';
11122 var defaultDayOfMonthOrdinalParse = /\d{1,2}/;
11123
11124 function ordinal(number) {
11125 return this._ordinal.replace('%d', number);
11126 }
11127
11128 var defaultRelativeTime = {
11129 future: 'in %s',
11130 past: '%s ago',
11131 s: 'a few seconds',
11132 ss: '%d seconds',
11133 m: 'a minute',
11134 mm: '%d minutes',
11135 h: 'an hour',
11136 hh: '%d hours',
11137 d: 'a day',
11138 dd: '%d days',
11139 M: 'a month',
11140 MM: '%d months',
11141 y: 'a year',
11142 yy: '%d years'
11143 };
11144
11145 function relativeTime(number, withoutSuffix, string, isFuture) {
11146 var output = this._relativeTime[string];
11147 return isFunction(output) ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number);
11148 }
11149
11150 function pastFuture(diff, output) {
11151 var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
11152 return isFunction(format) ? format(output) : format.replace(/%s/i, output);
11153 }
11154
11155 var aliases = {};
11156
11157 function addUnitAlias(unit, shorthand) {
11158 var lowerCase = unit.toLowerCase();
11159 aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
11160 }
11161
11162 function normalizeUnits(units) {
11163 return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined;
11164 }
11165
11166 function normalizeObjectUnits(inputObject) {
11167 var normalizedInput = {},
11168 normalizedProp,
11169 prop;
11170
11171 for (prop in inputObject) {
11172 if (hasOwnProp(inputObject, prop)) {
11173 normalizedProp = normalizeUnits(prop);
11174
11175 if (normalizedProp) {
11176 normalizedInput[normalizedProp] = inputObject[prop];
11177 }
11178 }
11179 }
11180
11181 return normalizedInput;
11182 }
11183
11184 var priorities = {};
11185
11186 function addUnitPriority(unit, priority) {
11187 priorities[unit] = priority;
11188 }
11189
11190 function getPrioritizedUnits(unitsObj) {
11191 var units = [];
11192
11193 for (var u in unitsObj) {
11194 units.push({
11195 unit: u,
11196 priority: priorities[u]
11197 });
11198 }
11199
11200 units.sort(function (a, b) {
11201 return a.priority - b.priority;
11202 });
11203 return units;
11204 }
11205
11206 function zeroFill(number, targetLength, forceSign) {
11207 var absNumber = '' + Math.abs(number),
11208 zerosToFill = targetLength - absNumber.length,
11209 sign = number >= 0;
11210 return (sign ? forceSign ? '+' : '' : '-') + Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber;
11211 }
11212
11213 var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g;
11214 var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;
11215 var formatFunctions = {};
11216 var formatTokenFunctions = {}; // token: 'M'
11217 // padded: ['MM', 2]
11218 // ordinal: 'Mo'
11219 // callback: function () { this.month() + 1 }
11220
11221 function addFormatToken(token, padded, ordinal, callback) {
11222 var func = callback;
11223
11224 if (typeof callback === 'string') {
11225 func = function () {
11226 return this[callback]();
11227 };
11228 }
11229
11230 if (token) {
11231 formatTokenFunctions[token] = func;
11232 }
11233
11234 if (padded) {
11235 formatTokenFunctions[padded[0]] = function () {
11236 return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
11237 };
11238 }
11239
11240 if (ordinal) {
11241 formatTokenFunctions[ordinal] = function () {
11242 return this.localeData().ordinal(func.apply(this, arguments), token);
11243 };
11244 }
11245 }
11246
11247 function removeFormattingTokens(input) {
11248 if (input.match(/\[[\s\S]/)) {
11249 return input.replace(/^\[|\]$/g, '');
11250 }
11251
11252 return input.replace(/\\/g, '');
11253 }
11254
11255 function makeFormatFunction(format) {
11256 var array = format.match(formattingTokens),
11257 i,
11258 length;
11259
11260 for (i = 0, length = array.length; i < length; i++) {
11261 if (formatTokenFunctions[array[i]]) {
11262 array[i] = formatTokenFunctions[array[i]];
11263 } else {
11264 array[i] = removeFormattingTokens(array[i]);
11265 }
11266 }
11267
11268 return function (mom) {
11269 var output = '',
11270 i;
11271
11272 for (i = 0; i < length; i++) {
11273 output += isFunction(array[i]) ? array[i].call(mom, format) : array[i];
11274 }
11275
11276 return output;
11277 };
11278 } // format date using native date object
11279
11280
11281 function formatMoment(m, format) {
11282 if (!m.isValid()) {
11283 return m.localeData().invalidDate();
11284 }
11285
11286 format = expandFormat(format, m.localeData());
11287 formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format);
11288 return formatFunctions[format](m);
11289 }
11290
11291 function expandFormat(format, locale) {
11292 var i = 5;
11293
11294 function replaceLongDateFormatTokens(input) {
11295 return locale.longDateFormat(input) || input;
11296 }
11297
11298 localFormattingTokens.lastIndex = 0;
11299
11300 while (i >= 0 && localFormattingTokens.test(format)) {
11301 format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
11302 localFormattingTokens.lastIndex = 0;
11303 i -= 1;
11304 }
11305
11306 return format;
11307 }
11308
11309 var match1 = /\d/; // 0 - 9
11310
11311 var match2 = /\d\d/; // 00 - 99
11312
11313 var match3 = /\d{3}/; // 000 - 999
11314
11315 var match4 = /\d{4}/; // 0000 - 9999
11316
11317 var match6 = /[+-]?\d{6}/; // -999999 - 999999
11318
11319 var match1to2 = /\d\d?/; // 0 - 99
11320
11321 var match3to4 = /\d\d\d\d?/; // 999 - 9999
11322
11323 var match5to6 = /\d\d\d\d\d\d?/; // 99999 - 999999
11324
11325 var match1to3 = /\d{1,3}/; // 0 - 999
11326
11327 var match1to4 = /\d{1,4}/; // 0 - 9999
11328
11329 var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999
11330
11331 var matchUnsigned = /\d+/; // 0 - inf
11332
11333 var matchSigned = /[+-]?\d+/; // -inf - inf
11334
11335 var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z
11336
11337 var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z
11338
11339 var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123
11340 // any word (or two) characters or numbers including two/three word month in arabic.
11341 // includes scottish gaelic two word and hyphenated months
11342
11343 var matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i;
11344 var regexes = {};
11345
11346 function addRegexToken(token, regex, strictRegex) {
11347 regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) {
11348 return isStrict && strictRegex ? strictRegex : regex;
11349 };
11350 }
11351
11352 function getParseRegexForToken(token, config) {
11353 if (!hasOwnProp(regexes, token)) {
11354 return new RegExp(unescapeFormat(token));
11355 }
11356
11357 return regexes[token](config._strict, config._locale);
11358 } // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
11359
11360
11361 function unescapeFormat(s) {
11362 return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
11363 return p1 || p2 || p3 || p4;
11364 }));
11365 }
11366
11367 function regexEscape(s) {
11368 return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
11369 }
11370
11371 var tokens = {};
11372
11373 function addParseToken(token, callback) {
11374 var i,
11375 func = callback;
11376
11377 if (typeof token === 'string') {
11378 token = [token];
11379 }
11380
11381 if (isNumber(callback)) {
11382 func = function (input, array) {
11383 array[callback] = toInt(input);
11384 };
11385 }
11386
11387 for (i = 0; i < token.length; i++) {
11388 tokens[token[i]] = func;
11389 }
11390 }
11391
11392 function addWeekParseToken(token, callback) {
11393 addParseToken(token, function (input, array, config, token) {
11394 config._w = config._w || {};
11395 callback(input, config._w, config, token);
11396 });
11397 }
11398
11399 function addTimeToArrayFromToken(token, input, config) {
11400 if (input != null && hasOwnProp(tokens, token)) {
11401 tokens[token](input, config._a, config, token);
11402 }
11403 }
11404
11405 var YEAR = 0;
11406 var MONTH = 1;
11407 var DATE = 2;
11408 var HOUR = 3;
11409 var MINUTE = 4;
11410 var SECOND = 5;
11411 var MILLISECOND = 6;
11412 var WEEK = 7;
11413 var WEEKDAY = 8; // FORMATTING
11414
11415 addFormatToken('Y', 0, 0, function () {
11416 var y = this.year();
11417 return y <= 9999 ? '' + y : '+' + y;
11418 });
11419 addFormatToken(0, ['YY', 2], 0, function () {
11420 return this.year() % 100;
11421 });
11422 addFormatToken(0, ['YYYY', 4], 0, 'year');
11423 addFormatToken(0, ['YYYYY', 5], 0, 'year');
11424 addFormatToken(0, ['YYYYYY', 6, true], 0, 'year'); // ALIASES
11425
11426 addUnitAlias('year', 'y'); // PRIORITIES
11427
11428 addUnitPriority('year', 1); // PARSING
11429
11430 addRegexToken('Y', matchSigned);
11431 addRegexToken('YY', match1to2, match2);
11432 addRegexToken('YYYY', match1to4, match4);
11433 addRegexToken('YYYYY', match1to6, match6);
11434 addRegexToken('YYYYYY', match1to6, match6);
11435 addParseToken(['YYYYY', 'YYYYYY'], YEAR);
11436 addParseToken('YYYY', function (input, array) {
11437 array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
11438 });
11439 addParseToken('YY', function (input, array) {
11440 array[YEAR] = hooks.parseTwoDigitYear(input);
11441 });
11442 addParseToken('Y', function (input, array) {
11443 array[YEAR] = parseInt(input, 10);
11444 }); // HELPERS
11445
11446 function daysInYear(year) {
11447 return isLeapYear(year) ? 366 : 365;
11448 }
11449
11450 function isLeapYear(year) {
11451 return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
11452 } // HOOKS
11453
11454
11455 hooks.parseTwoDigitYear = function (input) {
11456 return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
11457 }; // MOMENTS
11458
11459
11460 var getSetYear = makeGetSet('FullYear', true);
11461
11462 function getIsLeapYear() {
11463 return isLeapYear(this.year());
11464 }
11465
11466 function makeGetSet(unit, keepTime) {
11467 return function (value) {
11468 if (value != null) {
11469 set$1(this, unit, value);
11470 hooks.updateOffset(this, keepTime);
11471 return this;
11472 } else {
11473 return get(this, unit);
11474 }
11475 };
11476 }
11477
11478 function get(mom, unit) {
11479 return mom.isValid() ? mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN;
11480 }
11481
11482 function set$1(mom, unit, value) {
11483 if (mom.isValid() && !isNaN(value)) {
11484 if (unit === 'FullYear' && isLeapYear(mom.year()) && mom.month() === 1 && mom.date() === 29) {
11485 mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value, mom.month(), daysInMonth(value, mom.month()));
11486 } else {
11487 mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
11488 }
11489 }
11490 } // MOMENTS
11491
11492
11493 function stringGet(units) {
11494 units = normalizeUnits(units);
11495
11496 if (isFunction(this[units])) {
11497 return this[units]();
11498 }
11499
11500 return this;
11501 }
11502
11503 function stringSet(units, value) {
11504 if (typeof units === 'object') {
11505 units = normalizeObjectUnits(units);
11506 var prioritized = getPrioritizedUnits(units);
11507
11508 for (var i = 0; i < prioritized.length; i++) {
11509 this[prioritized[i].unit](units[prioritized[i].unit]);
11510 }
11511 } else {
11512 units = normalizeUnits(units);
11513
11514 if (isFunction(this[units])) {
11515 return this[units](value);
11516 }
11517 }
11518
11519 return this;
11520 }
11521
11522 function mod(n, x) {
11523 return (n % x + x) % x;
11524 }
11525
11526 var indexOf;
11527
11528 if (Array.prototype.indexOf) {
11529 indexOf = Array.prototype.indexOf;
11530 } else {
11531 indexOf = function (o) {
11532 // I know
11533 var i;
11534
11535 for (i = 0; i < this.length; ++i) {
11536 if (this[i] === o) {
11537 return i;
11538 }
11539 }
11540
11541 return -1;
11542 };
11543 }
11544
11545 function daysInMonth(year, month) {
11546 if (isNaN(year) || isNaN(month)) {
11547 return NaN;
11548 }
11549
11550 var modMonth = mod(month, 12);
11551 year += (month - modMonth) / 12;
11552 return modMonth === 1 ? isLeapYear(year) ? 29 : 28 : 31 - modMonth % 7 % 2;
11553 } // FORMATTING
11554
11555
11556 addFormatToken('M', ['MM', 2], 'Mo', function () {
11557 return this.month() + 1;
11558 });
11559 addFormatToken('MMM', 0, 0, function (format) {
11560 return this.localeData().monthsShort(this, format);
11561 });
11562 addFormatToken('MMMM', 0, 0, function (format) {
11563 return this.localeData().months(this, format);
11564 }); // ALIASES
11565
11566 addUnitAlias('month', 'M'); // PRIORITY
11567
11568 addUnitPriority('month', 8); // PARSING
11569
11570 addRegexToken('M', match1to2);
11571 addRegexToken('MM', match1to2, match2);
11572 addRegexToken('MMM', function (isStrict, locale) {
11573 return locale.monthsShortRegex(isStrict);
11574 });
11575 addRegexToken('MMMM', function (isStrict, locale) {
11576 return locale.monthsRegex(isStrict);
11577 });
11578 addParseToken(['M', 'MM'], function (input, array) {
11579 array[MONTH] = toInt(input) - 1;
11580 });
11581 addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
11582 var month = config._locale.monthsParse(input, token, config._strict); // if we didn't find a month name, mark the date as invalid.
11583
11584
11585 if (month != null) {
11586 array[MONTH] = month;
11587 } else {
11588 getParsingFlags(config).invalidMonth = input;
11589 }
11590 }); // LOCALES
11591
11592 var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/;
11593 var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_');
11594
11595 function localeMonths(m, format) {
11596 if (!m) {
11597 return isArray(this._months) ? this._months : this._months['standalone'];
11598 }
11599
11600 return isArray(this._months) ? this._months[m.month()] : this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()];
11601 }
11602
11603 var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_');
11604
11605 function localeMonthsShort(m, format) {
11606 if (!m) {
11607 return isArray(this._monthsShort) ? this._monthsShort : this._monthsShort['standalone'];
11608 }
11609
11610 return isArray(this._monthsShort) ? this._monthsShort[m.month()] : this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()];
11611 }
11612
11613 function handleStrictParse(monthName, format, strict) {
11614 var i,
11615 ii,
11616 mom,
11617 llc = monthName.toLocaleLowerCase();
11618
11619 if (!this._monthsParse) {
11620 // this is not used
11621 this._monthsParse = [];
11622 this._longMonthsParse = [];
11623 this._shortMonthsParse = [];
11624
11625 for (i = 0; i < 12; ++i) {
11626 mom = createUTC([2000, i]);
11627 this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase();
11628 this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
11629 }
11630 }
11631
11632 if (strict) {
11633 if (format === 'MMM') {
11634 ii = indexOf.call(this._shortMonthsParse, llc);
11635 return ii !== -1 ? ii : null;
11636 } else {
11637 ii = indexOf.call(this._longMonthsParse, llc);
11638 return ii !== -1 ? ii : null;
11639 }
11640 } else {
11641 if (format === 'MMM') {
11642 ii = indexOf.call(this._shortMonthsParse, llc);
11643
11644 if (ii !== -1) {
11645 return ii;
11646 }
11647
11648 ii = indexOf.call(this._longMonthsParse, llc);
11649 return ii !== -1 ? ii : null;
11650 } else {
11651 ii = indexOf.call(this._longMonthsParse, llc);
11652
11653 if (ii !== -1) {
11654 return ii;
11655 }
11656
11657 ii = indexOf.call(this._shortMonthsParse, llc);
11658 return ii !== -1 ? ii : null;
11659 }
11660 }
11661 }
11662
11663 function localeMonthsParse(monthName, format, strict) {
11664 var i, mom, regex;
11665
11666 if (this._monthsParseExact) {
11667 return handleStrictParse.call(this, monthName, format, strict);
11668 }
11669
11670 if (!this._monthsParse) {
11671 this._monthsParse = [];
11672 this._longMonthsParse = [];
11673 this._shortMonthsParse = [];
11674 } // TODO: add sorting
11675 // Sorting makes sure if one month (or abbr) is a prefix of another
11676 // see sorting in computeMonthsParse
11677
11678
11679 for (i = 0; i < 12; i++) {
11680 // make the regex if we don't have it already
11681 mom = createUTC([2000, i]);
11682
11683 if (strict && !this._longMonthsParse[i]) {
11684 this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
11685 this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
11686 }
11687
11688 if (!strict && !this._monthsParse[i]) {
11689 regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
11690 this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
11691 } // test the regex
11692
11693
11694 if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
11695 return i;
11696 } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
11697 return i;
11698 } else if (!strict && this._monthsParse[i].test(monthName)) {
11699 return i;
11700 }
11701 }
11702 } // MOMENTS
11703
11704
11705 function setMonth(mom, value) {
11706 var dayOfMonth;
11707
11708 if (!mom.isValid()) {
11709 // No op
11710 return mom;
11711 }
11712
11713 if (typeof value === 'string') {
11714 if (/^\d+$/.test(value)) {
11715 value = toInt(value);
11716 } else {
11717 value = mom.localeData().monthsParse(value); // TODO: Another silent failure?
11718
11719 if (!isNumber(value)) {
11720 return mom;
11721 }
11722 }
11723 }
11724
11725 dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
11726
11727 mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
11728
11729 return mom;
11730 }
11731
11732 function getSetMonth(value) {
11733 if (value != null) {
11734 setMonth(this, value);
11735 hooks.updateOffset(this, true);
11736 return this;
11737 } else {
11738 return get(this, 'Month');
11739 }
11740 }
11741
11742 function getDaysInMonth() {
11743 return daysInMonth(this.year(), this.month());
11744 }
11745
11746 var defaultMonthsShortRegex = matchWord;
11747
11748 function monthsShortRegex(isStrict) {
11749 if (this._monthsParseExact) {
11750 if (!hasOwnProp(this, '_monthsRegex')) {
11751 computeMonthsParse.call(this);
11752 }
11753
11754 if (isStrict) {
11755 return this._monthsShortStrictRegex;
11756 } else {
11757 return this._monthsShortRegex;
11758 }
11759 } else {
11760 if (!hasOwnProp(this, '_monthsShortRegex')) {
11761 this._monthsShortRegex = defaultMonthsShortRegex;
11762 }
11763
11764 return this._monthsShortStrictRegex && isStrict ? this._monthsShortStrictRegex : this._monthsShortRegex;
11765 }
11766 }
11767
11768 var defaultMonthsRegex = matchWord;
11769
11770 function monthsRegex(isStrict) {
11771 if (this._monthsParseExact) {
11772 if (!hasOwnProp(this, '_monthsRegex')) {
11773 computeMonthsParse.call(this);
11774 }
11775
11776 if (isStrict) {
11777 return this._monthsStrictRegex;
11778 } else {
11779 return this._monthsRegex;
11780 }
11781 } else {
11782 if (!hasOwnProp(this, '_monthsRegex')) {
11783 this._monthsRegex = defaultMonthsRegex;
11784 }
11785
11786 return this._monthsStrictRegex && isStrict ? this._monthsStrictRegex : this._monthsRegex;
11787 }
11788 }
11789
11790 function computeMonthsParse() {
11791 function cmpLenRev(a, b) {
11792 return b.length - a.length;
11793 }
11794
11795 var shortPieces = [],
11796 longPieces = [],
11797 mixedPieces = [],
11798 i,
11799 mom;
11800
11801 for (i = 0; i < 12; i++) {
11802 // make the regex if we don't have it already
11803 mom = createUTC([2000, i]);
11804 shortPieces.push(this.monthsShort(mom, ''));
11805 longPieces.push(this.months(mom, ''));
11806 mixedPieces.push(this.months(mom, ''));
11807 mixedPieces.push(this.monthsShort(mom, ''));
11808 } // Sorting makes sure if one month (or abbr) is a prefix of another it
11809 // will match the longer piece.
11810
11811
11812 shortPieces.sort(cmpLenRev);
11813 longPieces.sort(cmpLenRev);
11814 mixedPieces.sort(cmpLenRev);
11815
11816 for (i = 0; i < 12; i++) {
11817 shortPieces[i] = regexEscape(shortPieces[i]);
11818 longPieces[i] = regexEscape(longPieces[i]);
11819 }
11820
11821 for (i = 0; i < 24; i++) {
11822 mixedPieces[i] = regexEscape(mixedPieces[i]);
11823 }
11824
11825 this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
11826 this._monthsShortRegex = this._monthsRegex;
11827 this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
11828 this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
11829 }
11830
11831 function createDate(y, m, d, h, M, s, ms) {
11832 // can't just apply() to create a date:
11833 // https://stackoverflow.com/q/181348
11834 var date; // the date constructor remaps years 0-99 to 1900-1999
11835
11836 if (y < 100 && y >= 0) {
11837 // preserve leap years using a full 400 year cycle, then reset
11838 date = new Date(y + 400, m, d, h, M, s, ms);
11839
11840 if (isFinite(date.getFullYear())) {
11841 date.setFullYear(y);
11842 }
11843 } else {
11844 date = new Date(y, m, d, h, M, s, ms);
11845 }
11846
11847 return date;
11848 }
11849
11850 function createUTCDate(y) {
11851 var date; // the Date.UTC function remaps years 0-99 to 1900-1999
11852
11853 if (y < 100 && y >= 0) {
11854 var args = Array.prototype.slice.call(arguments); // preserve leap years using a full 400 year cycle, then reset
11855
11856 args[0] = y + 400;
11857 date = new Date(Date.UTC.apply(null, args));
11858
11859 if (isFinite(date.getUTCFullYear())) {
11860 date.setUTCFullYear(y);
11861 }
11862 } else {
11863 date = new Date(Date.UTC.apply(null, arguments));
11864 }
11865
11866 return date;
11867 } // start-of-first-week - start-of-year
11868
11869
11870 function firstWeekOffset(year, dow, doy) {
11871 var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
11872 fwd = 7 + dow - doy,
11873 // first-week day local weekday -- which local weekday is fwd
11874 fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
11875 return -fwdlw + fwd - 1;
11876 } // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
11877
11878
11879 function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
11880 var localWeekday = (7 + weekday - dow) % 7,
11881 weekOffset = firstWeekOffset(year, dow, doy),
11882 dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
11883 resYear,
11884 resDayOfYear;
11885
11886 if (dayOfYear <= 0) {
11887 resYear = year - 1;
11888 resDayOfYear = daysInYear(resYear) + dayOfYear;
11889 } else if (dayOfYear > daysInYear(year)) {
11890 resYear = year + 1;
11891 resDayOfYear = dayOfYear - daysInYear(year);
11892 } else {
11893 resYear = year;
11894 resDayOfYear = dayOfYear;
11895 }
11896
11897 return {
11898 year: resYear,
11899 dayOfYear: resDayOfYear
11900 };
11901 }
11902
11903 function weekOfYear(mom, dow, doy) {
11904 var weekOffset = firstWeekOffset(mom.year(), dow, doy),
11905 week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
11906 resWeek,
11907 resYear;
11908
11909 if (week < 1) {
11910 resYear = mom.year() - 1;
11911 resWeek = week + weeksInYear(resYear, dow, doy);
11912 } else if (week > weeksInYear(mom.year(), dow, doy)) {
11913 resWeek = week - weeksInYear(mom.year(), dow, doy);
11914 resYear = mom.year() + 1;
11915 } else {
11916 resYear = mom.year();
11917 resWeek = week;
11918 }
11919
11920 return {
11921 week: resWeek,
11922 year: resYear
11923 };
11924 }
11925
11926 function weeksInYear(year, dow, doy) {
11927 var weekOffset = firstWeekOffset(year, dow, doy),
11928 weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
11929 return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
11930 } // FORMATTING
11931
11932
11933 addFormatToken('w', ['ww', 2], 'wo', 'week');
11934 addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek'); // ALIASES
11935
11936 addUnitAlias('week', 'w');
11937 addUnitAlias('isoWeek', 'W'); // PRIORITIES
11938
11939 addUnitPriority('week', 5);
11940 addUnitPriority('isoWeek', 5); // PARSING
11941
11942 addRegexToken('w', match1to2);
11943 addRegexToken('ww', match1to2, match2);
11944 addRegexToken('W', match1to2);
11945 addRegexToken('WW', match1to2, match2);
11946 addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) {
11947 week[token.substr(0, 1)] = toInt(input);
11948 }); // HELPERS
11949 // LOCALES
11950
11951 function localeWeek(mom) {
11952 return weekOfYear(mom, this._week.dow, this._week.doy).week;
11953 }
11954
11955 var defaultLocaleWeek = {
11956 dow: 0,
11957 // Sunday is the first day of the week.
11958 doy: 6 // The week that contains Jan 6th is the first week of the year.
11959
11960 };
11961
11962 function localeFirstDayOfWeek() {
11963 return this._week.dow;
11964 }
11965
11966 function localeFirstDayOfYear() {
11967 return this._week.doy;
11968 } // MOMENTS
11969
11970
11971 function getSetWeek(input) {
11972 var week = this.localeData().week(this);
11973 return input == null ? week : this.add((input - week) * 7, 'd');
11974 }
11975
11976 function getSetISOWeek(input) {
11977 var week = weekOfYear(this, 1, 4).week;
11978 return input == null ? week : this.add((input - week) * 7, 'd');
11979 } // FORMATTING
11980
11981
11982 addFormatToken('d', 0, 'do', 'day');
11983 addFormatToken('dd', 0, 0, function (format) {
11984 return this.localeData().weekdaysMin(this, format);
11985 });
11986 addFormatToken('ddd', 0, 0, function (format) {
11987 return this.localeData().weekdaysShort(this, format);
11988 });
11989 addFormatToken('dddd', 0, 0, function (format) {
11990 return this.localeData().weekdays(this, format);
11991 });
11992 addFormatToken('e', 0, 0, 'weekday');
11993 addFormatToken('E', 0, 0, 'isoWeekday'); // ALIASES
11994
11995 addUnitAlias('day', 'd');
11996 addUnitAlias('weekday', 'e');
11997 addUnitAlias('isoWeekday', 'E'); // PRIORITY
11998
11999 addUnitPriority('day', 11);
12000 addUnitPriority('weekday', 11);
12001 addUnitPriority('isoWeekday', 11); // PARSING
12002
12003 addRegexToken('d', match1to2);
12004 addRegexToken('e', match1to2);
12005 addRegexToken('E', match1to2);
12006 addRegexToken('dd', function (isStrict, locale) {
12007 return locale.weekdaysMinRegex(isStrict);
12008 });
12009 addRegexToken('ddd', function (isStrict, locale) {
12010 return locale.weekdaysShortRegex(isStrict);
12011 });
12012 addRegexToken('dddd', function (isStrict, locale) {
12013 return locale.weekdaysRegex(isStrict);
12014 });
12015 addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
12016 var weekday = config._locale.weekdaysParse(input, token, config._strict); // if we didn't get a weekday name, mark the date as invalid
12017
12018
12019 if (weekday != null) {
12020 week.d = weekday;
12021 } else {
12022 getParsingFlags(config).invalidWeekday = input;
12023 }
12024 });
12025 addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
12026 week[token] = toInt(input);
12027 }); // HELPERS
12028
12029 function parseWeekday(input, locale) {
12030 if (typeof input !== 'string') {
12031 return input;
12032 }
12033
12034 if (!isNaN(input)) {
12035 return parseInt(input, 10);
12036 }
12037
12038 input = locale.weekdaysParse(input);
12039
12040 if (typeof input === 'number') {
12041 return input;
12042 }
12043
12044 return null;
12045 }
12046
12047 function parseIsoWeekday(input, locale) {
12048 if (typeof input === 'string') {
12049 return locale.weekdaysParse(input) % 7 || 7;
12050 }
12051
12052 return isNaN(input) ? null : input;
12053 } // LOCALES
12054
12055
12056 function shiftWeekdays(ws, n) {
12057 return ws.slice(n, 7).concat(ws.slice(0, n));
12058 }
12059
12060 var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_');
12061
12062 function localeWeekdays(m, format) {
12063 var weekdays = isArray(this._weekdays) ? this._weekdays : this._weekdays[m && m !== true && this._weekdays.isFormat.test(format) ? 'format' : 'standalone'];
12064 return m === true ? shiftWeekdays(weekdays, this._week.dow) : m ? weekdays[m.day()] : weekdays;
12065 }
12066
12067 var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');
12068
12069 function localeWeekdaysShort(m) {
12070 return m === true ? shiftWeekdays(this._weekdaysShort, this._week.dow) : m ? this._weekdaysShort[m.day()] : this._weekdaysShort;
12071 }
12072
12073 var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_');
12074
12075 function localeWeekdaysMin(m) {
12076 return m === true ? shiftWeekdays(this._weekdaysMin, this._week.dow) : m ? this._weekdaysMin[m.day()] : this._weekdaysMin;
12077 }
12078
12079 function handleStrictParse$1(weekdayName, format, strict) {
12080 var i,
12081 ii,
12082 mom,
12083 llc = weekdayName.toLocaleLowerCase();
12084
12085 if (!this._weekdaysParse) {
12086 this._weekdaysParse = [];
12087 this._shortWeekdaysParse = [];
12088 this._minWeekdaysParse = [];
12089
12090 for (i = 0; i < 7; ++i) {
12091 mom = createUTC([2000, 1]).day(i);
12092 this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase();
12093 this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase();
12094 this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
12095 }
12096 }
12097
12098 if (strict) {
12099 if (format === 'dddd') {
12100 ii = indexOf.call(this._weekdaysParse, llc);
12101 return ii !== -1 ? ii : null;
12102 } else if (format === 'ddd') {
12103 ii = indexOf.call(this._shortWeekdaysParse, llc);
12104 return ii !== -1 ? ii : null;
12105 } else {
12106 ii = indexOf.call(this._minWeekdaysParse, llc);
12107 return ii !== -1 ? ii : null;
12108 }
12109 } else {
12110 if (format === 'dddd') {
12111 ii = indexOf.call(this._weekdaysParse, llc);
12112
12113 if (ii !== -1) {
12114 return ii;
12115 }
12116
12117 ii = indexOf.call(this._shortWeekdaysParse, llc);
12118
12119 if (ii !== -1) {
12120 return ii;
12121 }
12122
12123 ii = indexOf.call(this._minWeekdaysParse, llc);
12124 return ii !== -1 ? ii : null;
12125 } else if (format === 'ddd') {
12126 ii = indexOf.call(this._shortWeekdaysParse, llc);
12127
12128 if (ii !== -1) {
12129 return ii;
12130 }
12131
12132 ii = indexOf.call(this._weekdaysParse, llc);
12133
12134 if (ii !== -1) {
12135 return ii;
12136 }
12137
12138 ii = indexOf.call(this._minWeekdaysParse, llc);
12139 return ii !== -1 ? ii : null;
12140 } else {
12141 ii = indexOf.call(this._minWeekdaysParse, llc);
12142
12143 if (ii !== -1) {
12144 return ii;
12145 }
12146
12147 ii = indexOf.call(this._weekdaysParse, llc);
12148
12149 if (ii !== -1) {
12150 return ii;
12151 }
12152
12153 ii = indexOf.call(this._shortWeekdaysParse, llc);
12154 return ii !== -1 ? ii : null;
12155 }
12156 }
12157 }
12158
12159 function localeWeekdaysParse(weekdayName, format, strict) {
12160 var i, mom, regex;
12161
12162 if (this._weekdaysParseExact) {
12163 return handleStrictParse$1.call(this, weekdayName, format, strict);
12164 }
12165
12166 if (!this._weekdaysParse) {
12167 this._weekdaysParse = [];
12168 this._minWeekdaysParse = [];
12169 this._shortWeekdaysParse = [];
12170 this._fullWeekdaysParse = [];
12171 }
12172
12173 for (i = 0; i < 7; i++) {
12174 // make the regex if we don't have it already
12175 mom = createUTC([2000, 1]).day(i);
12176
12177 if (strict && !this._fullWeekdaysParse[i]) {
12178 this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\\.?') + '$', 'i');
12179 this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$', 'i');
12180 this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$', 'i');
12181 }
12182
12183 if (!this._weekdaysParse[i]) {
12184 regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
12185 this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
12186 } // test the regex
12187
12188
12189 if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) {
12190 return i;
12191 } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) {
12192 return i;
12193 } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) {
12194 return i;
12195 } else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
12196 return i;
12197 }
12198 }
12199 } // MOMENTS
12200
12201
12202 function getSetDayOfWeek(input) {
12203 if (!this.isValid()) {
12204 return input != null ? this : NaN;
12205 }
12206
12207 var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
12208
12209 if (input != null) {
12210 input = parseWeekday(input, this.localeData());
12211 return this.add(input - day, 'd');
12212 } else {
12213 return day;
12214 }
12215 }
12216
12217 function getSetLocaleDayOfWeek(input) {
12218 if (!this.isValid()) {
12219 return input != null ? this : NaN;
12220 }
12221
12222 var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
12223 return input == null ? weekday : this.add(input - weekday, 'd');
12224 }
12225
12226 function getSetISODayOfWeek(input) {
12227 if (!this.isValid()) {
12228 return input != null ? this : NaN;
12229 } // behaves the same as moment#day except
12230 // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
12231 // as a setter, sunday should belong to the previous week.
12232
12233
12234 if (input != null) {
12235 var weekday = parseIsoWeekday(input, this.localeData());
12236 return this.day(this.day() % 7 ? weekday : weekday - 7);
12237 } else {
12238 return this.day() || 7;
12239 }
12240 }
12241
12242 var defaultWeekdaysRegex = matchWord;
12243
12244 function weekdaysRegex(isStrict) {
12245 if (this._weekdaysParseExact) {
12246 if (!hasOwnProp(this, '_weekdaysRegex')) {
12247 computeWeekdaysParse.call(this);
12248 }
12249
12250 if (isStrict) {
12251 return this._weekdaysStrictRegex;
12252 } else {
12253 return this._weekdaysRegex;
12254 }
12255 } else {
12256 if (!hasOwnProp(this, '_weekdaysRegex')) {
12257 this._weekdaysRegex = defaultWeekdaysRegex;
12258 }
12259
12260 return this._weekdaysStrictRegex && isStrict ? this._weekdaysStrictRegex : this._weekdaysRegex;
12261 }
12262 }
12263
12264 var defaultWeekdaysShortRegex = matchWord;
12265
12266 function weekdaysShortRegex(isStrict) {
12267 if (this._weekdaysParseExact) {
12268 if (!hasOwnProp(this, '_weekdaysRegex')) {
12269 computeWeekdaysParse.call(this);
12270 }
12271
12272 if (isStrict) {
12273 return this._weekdaysShortStrictRegex;
12274 } else {
12275 return this._weekdaysShortRegex;
12276 }
12277 } else {
12278 if (!hasOwnProp(this, '_weekdaysShortRegex')) {
12279 this._weekdaysShortRegex = defaultWeekdaysShortRegex;
12280 }
12281
12282 return this._weekdaysShortStrictRegex && isStrict ? this._weekdaysShortStrictRegex : this._weekdaysShortRegex;
12283 }
12284 }
12285
12286 var defaultWeekdaysMinRegex = matchWord;
12287
12288 function weekdaysMinRegex(isStrict) {
12289 if (this._weekdaysParseExact) {
12290 if (!hasOwnProp(this, '_weekdaysRegex')) {
12291 computeWeekdaysParse.call(this);
12292 }
12293
12294 if (isStrict) {
12295 return this._weekdaysMinStrictRegex;
12296 } else {
12297 return this._weekdaysMinRegex;
12298 }
12299 } else {
12300 if (!hasOwnProp(this, '_weekdaysMinRegex')) {
12301 this._weekdaysMinRegex = defaultWeekdaysMinRegex;
12302 }
12303
12304 return this._weekdaysMinStrictRegex && isStrict ? this._weekdaysMinStrictRegex : this._weekdaysMinRegex;
12305 }
12306 }
12307
12308 function computeWeekdaysParse() {
12309 function cmpLenRev(a, b) {
12310 return b.length - a.length;
12311 }
12312
12313 var minPieces = [],
12314 shortPieces = [],
12315 longPieces = [],
12316 mixedPieces = [],
12317 i,
12318 mom,
12319 minp,
12320 shortp,
12321 longp;
12322
12323 for (i = 0; i < 7; i++) {
12324 // make the regex if we don't have it already
12325 mom = createUTC([2000, 1]).day(i);
12326 minp = this.weekdaysMin(mom, '');
12327 shortp = this.weekdaysShort(mom, '');
12328 longp = this.weekdays(mom, '');
12329 minPieces.push(minp);
12330 shortPieces.push(shortp);
12331 longPieces.push(longp);
12332 mixedPieces.push(minp);
12333 mixedPieces.push(shortp);
12334 mixedPieces.push(longp);
12335 } // Sorting makes sure if one weekday (or abbr) is a prefix of another it
12336 // will match the longer piece.
12337
12338
12339 minPieces.sort(cmpLenRev);
12340 shortPieces.sort(cmpLenRev);
12341 longPieces.sort(cmpLenRev);
12342 mixedPieces.sort(cmpLenRev);
12343
12344 for (i = 0; i < 7; i++) {
12345 shortPieces[i] = regexEscape(shortPieces[i]);
12346 longPieces[i] = regexEscape(longPieces[i]);
12347 mixedPieces[i] = regexEscape(mixedPieces[i]);
12348 }
12349
12350 this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
12351 this._weekdaysShortRegex = this._weekdaysRegex;
12352 this._weekdaysMinRegex = this._weekdaysRegex;
12353 this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
12354 this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
12355 this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i');
12356 } // FORMATTING
12357
12358
12359 function hFormat() {
12360 return this.hours() % 12 || 12;
12361 }
12362
12363 function kFormat() {
12364 return this.hours() || 24;
12365 }
12366
12367 addFormatToken('H', ['HH', 2], 0, 'hour');
12368 addFormatToken('h', ['hh', 2], 0, hFormat);
12369 addFormatToken('k', ['kk', 2], 0, kFormat);
12370 addFormatToken('hmm', 0, 0, function () {
12371 return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
12372 });
12373 addFormatToken('hmmss', 0, 0, function () {
12374 return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2);
12375 });
12376 addFormatToken('Hmm', 0, 0, function () {
12377 return '' + this.hours() + zeroFill(this.minutes(), 2);
12378 });
12379 addFormatToken('Hmmss', 0, 0, function () {
12380 return '' + this.hours() + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2);
12381 });
12382
12383 function meridiem(token, lowercase) {
12384 addFormatToken(token, 0, 0, function () {
12385 return this.localeData().meridiem(this.hours(), this.minutes(), lowercase);
12386 });
12387 }
12388
12389 meridiem('a', true);
12390 meridiem('A', false); // ALIASES
12391
12392 addUnitAlias('hour', 'h'); // PRIORITY
12393
12394 addUnitPriority('hour', 13); // PARSING
12395
12396 function matchMeridiem(isStrict, locale) {
12397 return locale._meridiemParse;
12398 }
12399
12400 addRegexToken('a', matchMeridiem);
12401 addRegexToken('A', matchMeridiem);
12402 addRegexToken('H', match1to2);
12403 addRegexToken('h', match1to2);
12404 addRegexToken('k', match1to2);
12405 addRegexToken('HH', match1to2, match2);
12406 addRegexToken('hh', match1to2, match2);
12407 addRegexToken('kk', match1to2, match2);
12408 addRegexToken('hmm', match3to4);
12409 addRegexToken('hmmss', match5to6);
12410 addRegexToken('Hmm', match3to4);
12411 addRegexToken('Hmmss', match5to6);
12412 addParseToken(['H', 'HH'], HOUR);
12413 addParseToken(['k', 'kk'], function (input, array, config) {
12414 var kInput = toInt(input);
12415 array[HOUR] = kInput === 24 ? 0 : kInput;
12416 });
12417 addParseToken(['a', 'A'], function (input, array, config) {
12418 config._isPm = config._locale.isPM(input);
12419 config._meridiem = input;
12420 });
12421 addParseToken(['h', 'hh'], function (input, array, config) {
12422 array[HOUR] = toInt(input);
12423 getParsingFlags(config).bigHour = true;
12424 });
12425 addParseToken('hmm', function (input, array, config) {
12426 var pos = input.length - 2;
12427 array[HOUR] = toInt(input.substr(0, pos));
12428 array[MINUTE] = toInt(input.substr(pos));
12429 getParsingFlags(config).bigHour = true;
12430 });
12431 addParseToken('hmmss', function (input, array, config) {
12432 var pos1 = input.length - 4;
12433 var pos2 = input.length - 2;
12434 array[HOUR] = toInt(input.substr(0, pos1));
12435 array[MINUTE] = toInt(input.substr(pos1, 2));
12436 array[SECOND] = toInt(input.substr(pos2));
12437 getParsingFlags(config).bigHour = true;
12438 });
12439 addParseToken('Hmm', function (input, array, config) {
12440 var pos = input.length - 2;
12441 array[HOUR] = toInt(input.substr(0, pos));
12442 array[MINUTE] = toInt(input.substr(pos));
12443 });
12444 addParseToken('Hmmss', function (input, array, config) {
12445 var pos1 = input.length - 4;
12446 var pos2 = input.length - 2;
12447 array[HOUR] = toInt(input.substr(0, pos1));
12448 array[MINUTE] = toInt(input.substr(pos1, 2));
12449 array[SECOND] = toInt(input.substr(pos2));
12450 }); // LOCALES
12451
12452 function localeIsPM(input) {
12453 // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
12454 // Using charAt should be more compatible.
12455 return (input + '').toLowerCase().charAt(0) === 'p';
12456 }
12457
12458 var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i;
12459
12460 function localeMeridiem(hours, minutes, isLower) {
12461 if (hours > 11) {
12462 return isLower ? 'pm' : 'PM';
12463 } else {
12464 return isLower ? 'am' : 'AM';
12465 }
12466 } // MOMENTS
12467 // Setting the hour should keep the time, because the user explicitly
12468 // specified which hour they want. So trying to maintain the same hour (in
12469 // a new timezone) makes sense. Adding/subtracting hours does not follow
12470 // this rule.
12471
12472
12473 var getSetHour = makeGetSet('Hours', true);
12474 var baseConfig = {
12475 calendar: defaultCalendar,
12476 longDateFormat: defaultLongDateFormat,
12477 invalidDate: defaultInvalidDate,
12478 ordinal: defaultOrdinal,
12479 dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,
12480 relativeTime: defaultRelativeTime,
12481 months: defaultLocaleMonths,
12482 monthsShort: defaultLocaleMonthsShort,
12483 week: defaultLocaleWeek,
12484 weekdays: defaultLocaleWeekdays,
12485 weekdaysMin: defaultLocaleWeekdaysMin,
12486 weekdaysShort: defaultLocaleWeekdaysShort,
12487 meridiemParse: defaultLocaleMeridiemParse
12488 }; // internal storage for locale config files
12489
12490 var locales = {};
12491 var localeFamilies = {};
12492 var globalLocale;
12493
12494 function normalizeLocale(key) {
12495 return key ? key.toLowerCase().replace('_', '-') : key;
12496 } // pick the locale from the array
12497 // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
12498 // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
12499
12500
12501 function chooseLocale(names) {
12502 var i = 0,
12503 j,
12504 next,
12505 locale,
12506 split;
12507
12508 while (i < names.length) {
12509 split = normalizeLocale(names[i]).split('-');
12510 j = split.length;
12511 next = normalizeLocale(names[i + 1]);
12512 next = next ? next.split('-') : null;
12513
12514 while (j > 0) {
12515 locale = loadLocale(split.slice(0, j).join('-'));
12516
12517 if (locale) {
12518 return locale;
12519 }
12520
12521 if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
12522 //the next array item is better than a shallower substring of this one
12523 break;
12524 }
12525
12526 j--;
12527 }
12528
12529 i++;
12530 }
12531
12532 return globalLocale;
12533 }
12534
12535 function loadLocale(name) {
12536 var oldLocale = null; // TODO: Find a better way to register and load all the locales in Node
12537
12538 if (!locales[name] && 'object' !== 'undefined' && module && module.exports) {
12539 try {
12540 oldLocale = globalLocale._abbr;
12541 var aliasedRequire = commonjsRequire$2;
12542 aliasedRequire('./locale/' + name);
12543 getSetGlobalLocale(oldLocale);
12544 } catch (e) {}
12545 }
12546
12547 return locales[name];
12548 } // This function will load locale and then set the global locale. If
12549 // no arguments are passed in, it will simply return the current global
12550 // locale key.
12551
12552
12553 function getSetGlobalLocale(key, values) {
12554 var data;
12555
12556 if (key) {
12557 if (isUndefined(values)) {
12558 data = getLocale(key);
12559 } else {
12560 data = defineLocale(key, values);
12561 }
12562
12563 if (data) {
12564 // moment.duration._locale = moment._locale = data;
12565 globalLocale = data;
12566 } else {
12567 if (typeof console !== 'undefined' && console.warn) {
12568 //warn user if arguments are passed but the locale could not be set
12569 console.warn('Locale ' + key + ' not found. Did you forget to load it?');
12570 }
12571 }
12572 }
12573
12574 return globalLocale._abbr;
12575 }
12576
12577 function defineLocale(name, config) {
12578 if (config !== null) {
12579 var locale,
12580 parentConfig = baseConfig;
12581 config.abbr = name;
12582
12583 if (locales[name] != null) {
12584 deprecateSimple('defineLocaleOverride', 'use moment.updateLocale(localeName, config) to change ' + 'an existing locale. moment.defineLocale(localeName, ' + 'config) should only be used for creating a new locale ' + 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.');
12585 parentConfig = locales[name]._config;
12586 } else if (config.parentLocale != null) {
12587 if (locales[config.parentLocale] != null) {
12588 parentConfig = locales[config.parentLocale]._config;
12589 } else {
12590 locale = loadLocale(config.parentLocale);
12591
12592 if (locale != null) {
12593 parentConfig = locale._config;
12594 } else {
12595 if (!localeFamilies[config.parentLocale]) {
12596 localeFamilies[config.parentLocale] = [];
12597 }
12598
12599 localeFamilies[config.parentLocale].push({
12600 name: name,
12601 config: config
12602 });
12603 return null;
12604 }
12605 }
12606 }
12607
12608 locales[name] = new Locale(mergeConfigs(parentConfig, config));
12609
12610 if (localeFamilies[name]) {
12611 localeFamilies[name].forEach(function (x) {
12612 defineLocale(x.name, x.config);
12613 });
12614 } // backwards compat for now: also set the locale
12615 // make sure we set the locale AFTER all child locales have been
12616 // created, so we won't end up with the child locale set.
12617
12618
12619 getSetGlobalLocale(name);
12620 return locales[name];
12621 } else {
12622 // useful for testing
12623 delete locales[name];
12624 return null;
12625 }
12626 }
12627
12628 function updateLocale(name, config) {
12629 if (config != null) {
12630 var locale,
12631 tmpLocale,
12632 parentConfig = baseConfig; // MERGE
12633
12634 tmpLocale = loadLocale(name);
12635
12636 if (tmpLocale != null) {
12637 parentConfig = tmpLocale._config;
12638 }
12639
12640 config = mergeConfigs(parentConfig, config);
12641 locale = new Locale(config);
12642 locale.parentLocale = locales[name];
12643 locales[name] = locale; // backwards compat for now: also set the locale
12644
12645 getSetGlobalLocale(name);
12646 } else {
12647 // pass null for config to unupdate, useful for tests
12648 if (locales[name] != null) {
12649 if (locales[name].parentLocale != null) {
12650 locales[name] = locales[name].parentLocale;
12651 } else if (locales[name] != null) {
12652 delete locales[name];
12653 }
12654 }
12655 }
12656
12657 return locales[name];
12658 } // returns locale data
12659
12660
12661 function getLocale(key) {
12662 var locale;
12663
12664 if (key && key._locale && key._locale._abbr) {
12665 key = key._locale._abbr;
12666 }
12667
12668 if (!key) {
12669 return globalLocale;
12670 }
12671
12672 if (!isArray(key)) {
12673 //short-circuit everything else
12674 locale = loadLocale(key);
12675
12676 if (locale) {
12677 return locale;
12678 }
12679
12680 key = [key];
12681 }
12682
12683 return chooseLocale(key);
12684 }
12685
12686 function listLocales() {
12687 return keys(locales);
12688 }
12689
12690 function checkOverflow(m) {
12691 var overflow;
12692 var a = m._a;
12693
12694 if (a && getParsingFlags(m).overflow === -2) {
12695 overflow = a[MONTH] < 0 || a[MONTH] > 11 ? MONTH : a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE : a[HOUR] < 0 || a[HOUR] > 24 || a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0) ? HOUR : a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE : a[SECOND] < 0 || a[SECOND] > 59 ? SECOND : a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND : -1;
12696
12697 if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
12698 overflow = DATE;
12699 }
12700
12701 if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
12702 overflow = WEEK;
12703 }
12704
12705 if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
12706 overflow = WEEKDAY;
12707 }
12708
12709 getParsingFlags(m).overflow = overflow;
12710 }
12711
12712 return m;
12713 } // Pick the first defined of two or three arguments.
12714
12715
12716 function defaults(a, b, c) {
12717 if (a != null) {
12718 return a;
12719 }
12720
12721 if (b != null) {
12722 return b;
12723 }
12724
12725 return c;
12726 }
12727
12728 function currentDateArray(config) {
12729 // hooks is actually the exported moment object
12730 var nowValue = new Date(hooks.now());
12731
12732 if (config._useUTC) {
12733 return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()];
12734 }
12735
12736 return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
12737 } // convert an array to a date.
12738 // the array should mirror the parameters below
12739 // note: all values past the year are optional and will default to the lowest possible value.
12740 // [year, month, day , hour, minute, second, millisecond]
12741
12742
12743 function configFromArray(config) {
12744 var i,
12745 date,
12746 input = [],
12747 currentDate,
12748 expectedWeekday,
12749 yearToUse;
12750
12751 if (config._d) {
12752 return;
12753 }
12754
12755 currentDate = currentDateArray(config); //compute day of the year from weeks and weekdays
12756
12757 if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
12758 dayOfYearFromWeekInfo(config);
12759 } //if the day of the year is set, figure out what it is
12760
12761
12762 if (config._dayOfYear != null) {
12763 yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
12764
12765 if (config._dayOfYear > daysInYear(yearToUse) || config._dayOfYear === 0) {
12766 getParsingFlags(config)._overflowDayOfYear = true;
12767 }
12768
12769 date = createUTCDate(yearToUse, 0, config._dayOfYear);
12770 config._a[MONTH] = date.getUTCMonth();
12771 config._a[DATE] = date.getUTCDate();
12772 } // Default to current date.
12773 // * if no year, month, day of month are given, default to today
12774 // * if day of month is given, default month and year
12775 // * if month is given, default only year
12776 // * if year is given, don't default anything
12777
12778
12779 for (i = 0; i < 3 && config._a[i] == null; ++i) {
12780 config._a[i] = input[i] = currentDate[i];
12781 } // Zero out whatever was not defaulted, including time
12782
12783
12784 for (; i < 7; i++) {
12785 config._a[i] = input[i] = config._a[i] == null ? i === 2 ? 1 : 0 : config._a[i];
12786 } // Check for 24:00:00.000
12787
12788
12789 if (config._a[HOUR] === 24 && config._a[MINUTE] === 0 && config._a[SECOND] === 0 && config._a[MILLISECOND] === 0) {
12790 config._nextDay = true;
12791 config._a[HOUR] = 0;
12792 }
12793
12794 config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input);
12795 expectedWeekday = config._useUTC ? config._d.getUTCDay() : config._d.getDay(); // Apply timezone offset from input. The actual utcOffset can be changed
12796 // with parseZone.
12797
12798 if (config._tzm != null) {
12799 config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
12800 }
12801
12802 if (config._nextDay) {
12803 config._a[HOUR] = 24;
12804 } // check for mismatching day of week
12805
12806
12807 if (config._w && typeof config._w.d !== 'undefined' && config._w.d !== expectedWeekday) {
12808 getParsingFlags(config).weekdayMismatch = true;
12809 }
12810 }
12811
12812 function dayOfYearFromWeekInfo(config) {
12813 var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow;
12814 w = config._w;
12815
12816 if (w.GG != null || w.W != null || w.E != null) {
12817 dow = 1;
12818 doy = 4; // TODO: We need to take the current isoWeekYear, but that depends on
12819 // how we interpret now (local, utc, fixed offset). So create
12820 // a now version of current config (take local/utc/offset flags, and
12821 // create now).
12822
12823 weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year);
12824 week = defaults(w.W, 1);
12825 weekday = defaults(w.E, 1);
12826
12827 if (weekday < 1 || weekday > 7) {
12828 weekdayOverflow = true;
12829 }
12830 } else {
12831 dow = config._locale._week.dow;
12832 doy = config._locale._week.doy;
12833 var curWeek = weekOfYear(createLocal(), dow, doy);
12834 weekYear = defaults(w.gg, config._a[YEAR], curWeek.year); // Default to current week.
12835
12836 week = defaults(w.w, curWeek.week);
12837
12838 if (w.d != null) {
12839 // weekday -- low day numbers are considered next week
12840 weekday = w.d;
12841
12842 if (weekday < 0 || weekday > 6) {
12843 weekdayOverflow = true;
12844 }
12845 } else if (w.e != null) {
12846 // local weekday -- counting starts from beginning of week
12847 weekday = w.e + dow;
12848
12849 if (w.e < 0 || w.e > 6) {
12850 weekdayOverflow = true;
12851 }
12852 } else {
12853 // default to beginning of week
12854 weekday = dow;
12855 }
12856 }
12857
12858 if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
12859 getParsingFlags(config)._overflowWeeks = true;
12860 } else if (weekdayOverflow != null) {
12861 getParsingFlags(config)._overflowWeekday = true;
12862 } else {
12863 temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
12864 config._a[YEAR] = temp.year;
12865 config._dayOfYear = temp.dayOfYear;
12866 }
12867 } // iso 8601 regex
12868 // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
12869
12870
12871 var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;
12872 var basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;
12873 var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/;
12874 var isoDates = [['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/], ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/], ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/], ['GGGG-[W]WW', /\d{4}-W\d\d/, false], ['YYYY-DDD', /\d{4}-\d{3}/], ['YYYY-MM', /\d{4}-\d\d/, false], ['YYYYYYMMDD', /[+-]\d{10}/], ['YYYYMMDD', /\d{8}/], // YYYYMM is NOT allowed by the standard
12875 ['GGGG[W]WWE', /\d{4}W\d{3}/], ['GGGG[W]WW', /\d{4}W\d{2}/, false], ['YYYYDDD', /\d{7}/]]; // iso time formats and regexes
12876
12877 var isoTimes = [['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/], ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/], ['HH:mm:ss', /\d\d:\d\d:\d\d/], ['HH:mm', /\d\d:\d\d/], ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/], ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/], ['HHmmss', /\d\d\d\d\d\d/], ['HHmm', /\d\d\d\d/], ['HH', /\d\d/]];
12878 var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i; // date from iso format
12879
12880 function configFromISO(config) {
12881 var i,
12882 l,
12883 string = config._i,
12884 match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
12885 allowTime,
12886 dateFormat,
12887 timeFormat,
12888 tzFormat;
12889
12890 if (match) {
12891 getParsingFlags(config).iso = true;
12892
12893 for (i = 0, l = isoDates.length; i < l; i++) {
12894 if (isoDates[i][1].exec(match[1])) {
12895 dateFormat = isoDates[i][0];
12896 allowTime = isoDates[i][2] !== false;
12897 break;
12898 }
12899 }
12900
12901 if (dateFormat == null) {
12902 config._isValid = false;
12903 return;
12904 }
12905
12906 if (match[3]) {
12907 for (i = 0, l = isoTimes.length; i < l; i++) {
12908 if (isoTimes[i][1].exec(match[3])) {
12909 // match[2] should be 'T' or space
12910 timeFormat = (match[2] || ' ') + isoTimes[i][0];
12911 break;
12912 }
12913 }
12914
12915 if (timeFormat == null) {
12916 config._isValid = false;
12917 return;
12918 }
12919 }
12920
12921 if (!allowTime && timeFormat != null) {
12922 config._isValid = false;
12923 return;
12924 }
12925
12926 if (match[4]) {
12927 if (tzRegex.exec(match[4])) {
12928 tzFormat = 'Z';
12929 } else {
12930 config._isValid = false;
12931 return;
12932 }
12933 }
12934
12935 config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
12936 configFromStringAndFormat(config);
12937 } else {
12938 config._isValid = false;
12939 }
12940 } // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
12941
12942
12943 var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/;
12944
12945 function extractFromRFC2822Strings(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {
12946 var result = [untruncateYear(yearStr), defaultLocaleMonthsShort.indexOf(monthStr), parseInt(dayStr, 10), parseInt(hourStr, 10), parseInt(minuteStr, 10)];
12947
12948 if (secondStr) {
12949 result.push(parseInt(secondStr, 10));
12950 }
12951
12952 return result;
12953 }
12954
12955 function untruncateYear(yearStr) {
12956 var year = parseInt(yearStr, 10);
12957
12958 if (year <= 49) {
12959 return 2000 + year;
12960 } else if (year <= 999) {
12961 return 1900 + year;
12962 }
12963
12964 return year;
12965 }
12966
12967 function preprocessRFC2822(s) {
12968 // Remove comments and folding whitespace and replace multiple-spaces with a single space
12969 return s.replace(/\([^)]*\)|[\n\t]/g, ' ').replace(/(\s\s+)/g, ' ').replace(/^\s\s*/, '').replace(/\s\s*$/, '');
12970 }
12971
12972 function checkWeekday(weekdayStr, parsedInput, config) {
12973 if (weekdayStr) {
12974 // TODO: Replace the vanilla JS Date object with an indepentent day-of-week check.
12975 var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr),
12976 weekdayActual = new Date(parsedInput[0], parsedInput[1], parsedInput[2]).getDay();
12977
12978 if (weekdayProvided !== weekdayActual) {
12979 getParsingFlags(config).weekdayMismatch = true;
12980 config._isValid = false;
12981 return false;
12982 }
12983 }
12984
12985 return true;
12986 }
12987
12988 var obsOffsets = {
12989 UT: 0,
12990 GMT: 0,
12991 EDT: -4 * 60,
12992 EST: -5 * 60,
12993 CDT: -5 * 60,
12994 CST: -6 * 60,
12995 MDT: -6 * 60,
12996 MST: -7 * 60,
12997 PDT: -7 * 60,
12998 PST: -8 * 60
12999 };
13000
13001 function calculateOffset(obsOffset, militaryOffset, numOffset) {
13002 if (obsOffset) {
13003 return obsOffsets[obsOffset];
13004 } else if (militaryOffset) {
13005 // the only allowed military tz is Z
13006 return 0;
13007 } else {
13008 var hm = parseInt(numOffset, 10);
13009 var m = hm % 100,
13010 h = (hm - m) / 100;
13011 return h * 60 + m;
13012 }
13013 } // date and time from ref 2822 format
13014
13015
13016 function configFromRFC2822(config) {
13017 var match = rfc2822.exec(preprocessRFC2822(config._i));
13018
13019 if (match) {
13020 var parsedArray = extractFromRFC2822Strings(match[4], match[3], match[2], match[5], match[6], match[7]);
13021
13022 if (!checkWeekday(match[1], parsedArray, config)) {
13023 return;
13024 }
13025
13026 config._a = parsedArray;
13027 config._tzm = calculateOffset(match[8], match[9], match[10]);
13028 config._d = createUTCDate.apply(null, config._a);
13029
13030 config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
13031
13032 getParsingFlags(config).rfc2822 = true;
13033 } else {
13034 config._isValid = false;
13035 }
13036 } // date from iso format or fallback
13037
13038
13039 function configFromString(config) {
13040 var matched = aspNetJsonRegex.exec(config._i);
13041
13042 if (matched !== null) {
13043 config._d = new Date(+matched[1]);
13044 return;
13045 }
13046
13047 configFromISO(config);
13048
13049 if (config._isValid === false) {
13050 delete config._isValid;
13051 } else {
13052 return;
13053 }
13054
13055 configFromRFC2822(config);
13056
13057 if (config._isValid === false) {
13058 delete config._isValid;
13059 } else {
13060 return;
13061 } // Final attempt, use Input Fallback
13062
13063
13064 hooks.createFromInputFallback(config);
13065 }
13066
13067 hooks.createFromInputFallback = deprecate('value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' + 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' + 'discouraged and will be removed in an upcoming major release. Please refer to ' + 'http://momentjs.com/guides/#/warnings/js-date/ for more info.', function (config) {
13068 config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
13069 }); // constant that refers to the ISO standard
13070
13071 hooks.ISO_8601 = function () {}; // constant that refers to the RFC 2822 form
13072
13073
13074 hooks.RFC_2822 = function () {}; // date from string and format string
13075
13076
13077 function configFromStringAndFormat(config) {
13078 // TODO: Move this to another part of the creation flow to prevent circular deps
13079 if (config._f === hooks.ISO_8601) {
13080 configFromISO(config);
13081 return;
13082 }
13083
13084 if (config._f === hooks.RFC_2822) {
13085 configFromRFC2822(config);
13086 return;
13087 }
13088
13089 config._a = [];
13090 getParsingFlags(config).empty = true; // This array is used to make a Date, either with `new Date` or `Date.UTC`
13091
13092 var string = '' + config._i,
13093 i,
13094 parsedInput,
13095 tokens,
13096 token,
13097 skipped,
13098 stringLength = string.length,
13099 totalParsedInputLength = 0;
13100 tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];
13101
13102 for (i = 0; i < tokens.length; i++) {
13103 token = tokens[i];
13104 parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; // console.log('token', token, 'parsedInput', parsedInput,
13105 // 'regex', getParseRegexForToken(token, config));
13106
13107 if (parsedInput) {
13108 skipped = string.substr(0, string.indexOf(parsedInput));
13109
13110 if (skipped.length > 0) {
13111 getParsingFlags(config).unusedInput.push(skipped);
13112 }
13113
13114 string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
13115 totalParsedInputLength += parsedInput.length;
13116 } // don't parse if it's not a known token
13117
13118
13119 if (formatTokenFunctions[token]) {
13120 if (parsedInput) {
13121 getParsingFlags(config).empty = false;
13122 } else {
13123 getParsingFlags(config).unusedTokens.push(token);
13124 }
13125
13126 addTimeToArrayFromToken(token, parsedInput, config);
13127 } else if (config._strict && !parsedInput) {
13128 getParsingFlags(config).unusedTokens.push(token);
13129 }
13130 } // add remaining unparsed input length to the string
13131
13132
13133 getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength;
13134
13135 if (string.length > 0) {
13136 getParsingFlags(config).unusedInput.push(string);
13137 } // clear _12h flag if hour is <= 12
13138
13139
13140 if (config._a[HOUR] <= 12 && getParsingFlags(config).bigHour === true && config._a[HOUR] > 0) {
13141 getParsingFlags(config).bigHour = undefined;
13142 }
13143
13144 getParsingFlags(config).parsedDateParts = config._a.slice(0);
13145 getParsingFlags(config).meridiem = config._meridiem; // handle meridiem
13146
13147 config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem);
13148 configFromArray(config);
13149 checkOverflow(config);
13150 }
13151
13152 function meridiemFixWrap(locale, hour, meridiem) {
13153 var isPm;
13154
13155 if (meridiem == null) {
13156 // nothing to do
13157 return hour;
13158 }
13159
13160 if (locale.meridiemHour != null) {
13161 return locale.meridiemHour(hour, meridiem);
13162 } else if (locale.isPM != null) {
13163 // Fallback
13164 isPm = locale.isPM(meridiem);
13165
13166 if (isPm && hour < 12) {
13167 hour += 12;
13168 }
13169
13170 if (!isPm && hour === 12) {
13171 hour = 0;
13172 }
13173
13174 return hour;
13175 } else {
13176 // this is not supposed to happen
13177 return hour;
13178 }
13179 } // date from string and array of format strings
13180
13181
13182 function configFromStringAndArray(config) {
13183 var tempConfig, bestMoment, scoreToBeat, i, currentScore;
13184
13185 if (config._f.length === 0) {
13186 getParsingFlags(config).invalidFormat = true;
13187 config._d = new Date(NaN);
13188 return;
13189 }
13190
13191 for (i = 0; i < config._f.length; i++) {
13192 currentScore = 0;
13193 tempConfig = copyConfig({}, config);
13194
13195 if (config._useUTC != null) {
13196 tempConfig._useUTC = config._useUTC;
13197 }
13198
13199 tempConfig._f = config._f[i];
13200 configFromStringAndFormat(tempConfig);
13201
13202 if (!isValid(tempConfig)) {
13203 continue;
13204 } // if there is any input that was not parsed add a penalty for that format
13205
13206
13207 currentScore += getParsingFlags(tempConfig).charsLeftOver; //or tokens
13208
13209 currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
13210 getParsingFlags(tempConfig).score = currentScore;
13211
13212 if (scoreToBeat == null || currentScore < scoreToBeat) {
13213 scoreToBeat = currentScore;
13214 bestMoment = tempConfig;
13215 }
13216 }
13217
13218 extend(config, bestMoment || tempConfig);
13219 }
13220
13221 function configFromObject(config) {
13222 if (config._d) {
13223 return;
13224 }
13225
13226 var i = normalizeObjectUnits(config._i);
13227 config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) {
13228 return obj && parseInt(obj, 10);
13229 });
13230 configFromArray(config);
13231 }
13232
13233 function createFromConfig(config) {
13234 var res = new Moment(checkOverflow(prepareConfig(config)));
13235
13236 if (res._nextDay) {
13237 // Adding is smart enough around DST
13238 res.add(1, 'd');
13239 res._nextDay = undefined;
13240 }
13241
13242 return res;
13243 }
13244
13245 function prepareConfig(config) {
13246 var input = config._i,
13247 format = config._f;
13248 config._locale = config._locale || getLocale(config._l);
13249
13250 if (input === null || format === undefined && input === '') {
13251 return createInvalid({
13252 nullInput: true
13253 });
13254 }
13255
13256 if (typeof input === 'string') {
13257 config._i = input = config._locale.preparse(input);
13258 }
13259
13260 if (isMoment(input)) {
13261 return new Moment(checkOverflow(input));
13262 } else if (isDate(input)) {
13263 config._d = input;
13264 } else if (isArray(format)) {
13265 configFromStringAndArray(config);
13266 } else if (format) {
13267 configFromStringAndFormat(config);
13268 } else {
13269 configFromInput(config);
13270 }
13271
13272 if (!isValid(config)) {
13273 config._d = null;
13274 }
13275
13276 return config;
13277 }
13278
13279 function configFromInput(config) {
13280 var input = config._i;
13281
13282 if (isUndefined(input)) {
13283 config._d = new Date(hooks.now());
13284 } else if (isDate(input)) {
13285 config._d = new Date(input.valueOf());
13286 } else if (typeof input === 'string') {
13287 configFromString(config);
13288 } else if (isArray(input)) {
13289 config._a = map(input.slice(0), function (obj) {
13290 return parseInt(obj, 10);
13291 });
13292 configFromArray(config);
13293 } else if (isObject(input)) {
13294 configFromObject(config);
13295 } else if (isNumber(input)) {
13296 // from milliseconds
13297 config._d = new Date(input);
13298 } else {
13299 hooks.createFromInputFallback(config);
13300 }
13301 }
13302
13303 function createLocalOrUTC(input, format, locale, strict, isUTC) {
13304 var c = {};
13305
13306 if (locale === true || locale === false) {
13307 strict = locale;
13308 locale = undefined;
13309 }
13310
13311 if (isObject(input) && isObjectEmpty(input) || isArray(input) && input.length === 0) {
13312 input = undefined;
13313 } // object construction must be done this way.
13314 // https://github.com/moment/moment/issues/1423
13315
13316
13317 c._isAMomentObject = true;
13318 c._useUTC = c._isUTC = isUTC;
13319 c._l = locale;
13320 c._i = input;
13321 c._f = format;
13322 c._strict = strict;
13323 return createFromConfig(c);
13324 }
13325
13326 function createLocal(input, format, locale, strict) {
13327 return createLocalOrUTC(input, format, locale, strict, false);
13328 }
13329
13330 var prototypeMin = deprecate('moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/', function () {
13331 var other = createLocal.apply(null, arguments);
13332
13333 if (this.isValid() && other.isValid()) {
13334 return other < this ? this : other;
13335 } else {
13336 return createInvalid();
13337 }
13338 });
13339 var prototypeMax = deprecate('moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/', function () {
13340 var other = createLocal.apply(null, arguments);
13341
13342 if (this.isValid() && other.isValid()) {
13343 return other > this ? this : other;
13344 } else {
13345 return createInvalid();
13346 }
13347 }); // Pick a moment m from moments so that m[fn](other) is true for all
13348 // other. This relies on the function fn to be transitive.
13349 //
13350 // moments should either be an array of moment objects or an array, whose
13351 // first element is an array of moment objects.
13352
13353 function pickBy(fn, moments) {
13354 var res, i;
13355
13356 if (moments.length === 1 && isArray(moments[0])) {
13357 moments = moments[0];
13358 }
13359
13360 if (!moments.length) {
13361 return createLocal();
13362 }
13363
13364 res = moments[0];
13365
13366 for (i = 1; i < moments.length; ++i) {
13367 if (!moments[i].isValid() || moments[i][fn](res)) {
13368 res = moments[i];
13369 }
13370 }
13371
13372 return res;
13373 } // TODO: Use [].sort instead?
13374
13375
13376 function min() {
13377 var args = [].slice.call(arguments, 0);
13378 return pickBy('isBefore', args);
13379 }
13380
13381 function max() {
13382 var args = [].slice.call(arguments, 0);
13383 return pickBy('isAfter', args);
13384 }
13385
13386 var now = function () {
13387 return Date.now ? Date.now() : +new Date();
13388 };
13389
13390 var ordering = ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond'];
13391
13392 function isDurationValid(m) {
13393 for (var key in m) {
13394 if (!(indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])))) {
13395 return false;
13396 }
13397 }
13398
13399 var unitHasDecimal = false;
13400
13401 for (var i = 0; i < ordering.length; ++i) {
13402 if (m[ordering[i]]) {
13403 if (unitHasDecimal) {
13404 return false; // only allow non-integers for smallest unit
13405 }
13406
13407 if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) {
13408 unitHasDecimal = true;
13409 }
13410 }
13411 }
13412
13413 return true;
13414 }
13415
13416 function isValid$1() {
13417 return this._isValid;
13418 }
13419
13420 function createInvalid$1() {
13421 return createDuration(NaN);
13422 }
13423
13424 function Duration(duration) {
13425 var normalizedInput = normalizeObjectUnits(duration),
13426 years = normalizedInput.year || 0,
13427 quarters = normalizedInput.quarter || 0,
13428 months = normalizedInput.month || 0,
13429 weeks = normalizedInput.week || normalizedInput.isoWeek || 0,
13430 days = normalizedInput.day || 0,
13431 hours = normalizedInput.hour || 0,
13432 minutes = normalizedInput.minute || 0,
13433 seconds = normalizedInput.second || 0,
13434 milliseconds = normalizedInput.millisecond || 0;
13435 this._isValid = isDurationValid(normalizedInput); // representation for dateAddRemove
13436
13437 this._milliseconds = +milliseconds + seconds * 1e3 + // 1000
13438 minutes * 6e4 + // 1000 * 60
13439 hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
13440 // Because of dateAddRemove treats 24 hours as different from a
13441 // day when working around DST, we need to store them separately
13442
13443 this._days = +days + weeks * 7; // It is impossible to translate months into days without knowing
13444 // which months you are are talking about, so we have to store
13445 // it separately.
13446
13447 this._months = +months + quarters * 3 + years * 12;
13448 this._data = {};
13449 this._locale = getLocale();
13450
13451 this._bubble();
13452 }
13453
13454 function isDuration(obj) {
13455 return obj instanceof Duration;
13456 }
13457
13458 function absRound(number) {
13459 if (number < 0) {
13460 return Math.round(-1 * number) * -1;
13461 } else {
13462 return Math.round(number);
13463 }
13464 } // FORMATTING
13465
13466
13467 function offset(token, separator) {
13468 addFormatToken(token, 0, 0, function () {
13469 var offset = this.utcOffset();
13470 var sign = '+';
13471
13472 if (offset < 0) {
13473 offset = -offset;
13474 sign = '-';
13475 }
13476
13477 return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~offset % 60, 2);
13478 });
13479 }
13480
13481 offset('Z', ':');
13482 offset('ZZ', ''); // PARSING
13483
13484 addRegexToken('Z', matchShortOffset);
13485 addRegexToken('ZZ', matchShortOffset);
13486 addParseToken(['Z', 'ZZ'], function (input, array, config) {
13487 config._useUTC = true;
13488 config._tzm = offsetFromString(matchShortOffset, input);
13489 }); // HELPERS
13490 // timezone chunker
13491 // '+10:00' > ['10', '00']
13492 // '-1530' > ['-15', '30']
13493
13494 var chunkOffset = /([\+\-]|\d\d)/gi;
13495
13496 function offsetFromString(matcher, string) {
13497 var matches = (string || '').match(matcher);
13498
13499 if (matches === null) {
13500 return null;
13501 }
13502
13503 var chunk = matches[matches.length - 1] || [];
13504 var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
13505 var minutes = +(parts[1] * 60) + toInt(parts[2]);
13506 return minutes === 0 ? 0 : parts[0] === '+' ? minutes : -minutes;
13507 } // Return a moment from input, that is local/utc/zone equivalent to model.
13508
13509
13510 function cloneWithOffset(input, model) {
13511 var res, diff;
13512
13513 if (model._isUTC) {
13514 res = model.clone();
13515 diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf(); // Use low-level api, because this fn is low-level api.
13516
13517 res._d.setTime(res._d.valueOf() + diff);
13518
13519 hooks.updateOffset(res, false);
13520 return res;
13521 } else {
13522 return createLocal(input).local();
13523 }
13524 }
13525
13526 function getDateOffset(m) {
13527 // On Firefox.24 Date#getTimezoneOffset returns a floating point.
13528 // https://github.com/moment/moment/pull/1871
13529 return -Math.round(m._d.getTimezoneOffset() / 15) * 15;
13530 } // HOOKS
13531 // This function will be called whenever a moment is mutated.
13532 // It is intended to keep the offset in sync with the timezone.
13533
13534
13535 hooks.updateOffset = function () {}; // MOMENTS
13536 // keepLocalTime = true means only change the timezone, without
13537 // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
13538 // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
13539 // +0200, so we adjust the time as needed, to be valid.
13540 //
13541 // Keeping the time actually adds/subtracts (one hour)
13542 // from the actual represented time. That is why we call updateOffset
13543 // a second time. In case it wants us to change the offset again
13544 // _changeInProgress == true case, then we have to adjust, because
13545 // there is no such time in the given timezone.
13546
13547
13548 function getSetOffset(input, keepLocalTime, keepMinutes) {
13549 var offset = this._offset || 0,
13550 localAdjust;
13551
13552 if (!this.isValid()) {
13553 return input != null ? this : NaN;
13554 }
13555
13556 if (input != null) {
13557 if (typeof input === 'string') {
13558 input = offsetFromString(matchShortOffset, input);
13559
13560 if (input === null) {
13561 return this;
13562 }
13563 } else if (Math.abs(input) < 16 && !keepMinutes) {
13564 input = input * 60;
13565 }
13566
13567 if (!this._isUTC && keepLocalTime) {
13568 localAdjust = getDateOffset(this);
13569 }
13570
13571 this._offset = input;
13572 this._isUTC = true;
13573
13574 if (localAdjust != null) {
13575 this.add(localAdjust, 'm');
13576 }
13577
13578 if (offset !== input) {
13579 if (!keepLocalTime || this._changeInProgress) {
13580 addSubtract(this, createDuration(input - offset, 'm'), 1, false);
13581 } else if (!this._changeInProgress) {
13582 this._changeInProgress = true;
13583 hooks.updateOffset(this, true);
13584 this._changeInProgress = null;
13585 }
13586 }
13587
13588 return this;
13589 } else {
13590 return this._isUTC ? offset : getDateOffset(this);
13591 }
13592 }
13593
13594 function getSetZone(input, keepLocalTime) {
13595 if (input != null) {
13596 if (typeof input !== 'string') {
13597 input = -input;
13598 }
13599
13600 this.utcOffset(input, keepLocalTime);
13601 return this;
13602 } else {
13603 return -this.utcOffset();
13604 }
13605 }
13606
13607 function setOffsetToUTC(keepLocalTime) {
13608 return this.utcOffset(0, keepLocalTime);
13609 }
13610
13611 function setOffsetToLocal(keepLocalTime) {
13612 if (this._isUTC) {
13613 this.utcOffset(0, keepLocalTime);
13614 this._isUTC = false;
13615
13616 if (keepLocalTime) {
13617 this.subtract(getDateOffset(this), 'm');
13618 }
13619 }
13620
13621 return this;
13622 }
13623
13624 function setOffsetToParsedOffset() {
13625 if (this._tzm != null) {
13626 this.utcOffset(this._tzm, false, true);
13627 } else if (typeof this._i === 'string') {
13628 var tZone = offsetFromString(matchOffset, this._i);
13629
13630 if (tZone != null) {
13631 this.utcOffset(tZone);
13632 } else {
13633 this.utcOffset(0, true);
13634 }
13635 }
13636
13637 return this;
13638 }
13639
13640 function hasAlignedHourOffset(input) {
13641 if (!this.isValid()) {
13642 return false;
13643 }
13644
13645 input = input ? createLocal(input).utcOffset() : 0;
13646 return (this.utcOffset() - input) % 60 === 0;
13647 }
13648
13649 function isDaylightSavingTime() {
13650 return this.utcOffset() > this.clone().month(0).utcOffset() || this.utcOffset() > this.clone().month(5).utcOffset();
13651 }
13652
13653 function isDaylightSavingTimeShifted() {
13654 if (!isUndefined(this._isDSTShifted)) {
13655 return this._isDSTShifted;
13656 }
13657
13658 var c = {};
13659 copyConfig(c, this);
13660 c = prepareConfig(c);
13661
13662 if (c._a) {
13663 var other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
13664 this._isDSTShifted = this.isValid() && compareArrays(c._a, other.toArray()) > 0;
13665 } else {
13666 this._isDSTShifted = false;
13667 }
13668
13669 return this._isDSTShifted;
13670 }
13671
13672 function isLocal() {
13673 return this.isValid() ? !this._isUTC : false;
13674 }
13675
13676 function isUtcOffset() {
13677 return this.isValid() ? this._isUTC : false;
13678 }
13679
13680 function isUtc() {
13681 return this.isValid() ? this._isUTC && this._offset === 0 : false;
13682 } // ASP.NET json date format regex
13683
13684
13685 var aspNetRegex = /^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/; // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
13686 // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
13687 // and further modified to allow for strings containing both week and day
13688
13689 var isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
13690
13691 function createDuration(input, key) {
13692 var duration = input,
13693 // matching against regexp is expensive, do it on demand
13694 match = null,
13695 sign,
13696 ret,
13697 diffRes;
13698
13699 if (isDuration(input)) {
13700 duration = {
13701 ms: input._milliseconds,
13702 d: input._days,
13703 M: input._months
13704 };
13705 } else if (isNumber(input)) {
13706 duration = {};
13707
13708 if (key) {
13709 duration[key] = input;
13710 } else {
13711 duration.milliseconds = input;
13712 }
13713 } else if (!!(match = aspNetRegex.exec(input))) {
13714 sign = match[1] === '-' ? -1 : 1;
13715 duration = {
13716 y: 0,
13717 d: toInt(match[DATE]) * sign,
13718 h: toInt(match[HOUR]) * sign,
13719 m: toInt(match[MINUTE]) * sign,
13720 s: toInt(match[SECOND]) * sign,
13721 ms: toInt(absRound(match[MILLISECOND] * 1000)) * sign // the millisecond decimal point is included in the match
13722
13723 };
13724 } else if (!!(match = isoRegex.exec(input))) {
13725 sign = match[1] === '-' ? -1 : 1;
13726 duration = {
13727 y: parseIso(match[2], sign),
13728 M: parseIso(match[3], sign),
13729 w: parseIso(match[4], sign),
13730 d: parseIso(match[5], sign),
13731 h: parseIso(match[6], sign),
13732 m: parseIso(match[7], sign),
13733 s: parseIso(match[8], sign)
13734 };
13735 } else if (duration == null) {
13736 // checks for null or undefined
13737 duration = {};
13738 } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) {
13739 diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to));
13740 duration = {};
13741 duration.ms = diffRes.milliseconds;
13742 duration.M = diffRes.months;
13743 }
13744
13745 ret = new Duration(duration);
13746
13747 if (isDuration(input) && hasOwnProp(input, '_locale')) {
13748 ret._locale = input._locale;
13749 }
13750
13751 return ret;
13752 }
13753
13754 createDuration.fn = Duration.prototype;
13755 createDuration.invalid = createInvalid$1;
13756
13757 function parseIso(inp, sign) {
13758 // We'd normally use ~~inp for this, but unfortunately it also
13759 // converts floats to ints.
13760 // inp may be undefined, so careful calling replace on it.
13761 var res = inp && parseFloat(inp.replace(',', '.')); // apply sign while we're at it
13762
13763 return (isNaN(res) ? 0 : res) * sign;
13764 }
13765
13766 function positiveMomentsDifference(base, other) {
13767 var res = {};
13768 res.months = other.month() - base.month() + (other.year() - base.year()) * 12;
13769
13770 if (base.clone().add(res.months, 'M').isAfter(other)) {
13771 --res.months;
13772 }
13773
13774 res.milliseconds = +other - +base.clone().add(res.months, 'M');
13775 return res;
13776 }
13777
13778 function momentsDifference(base, other) {
13779 var res;
13780
13781 if (!(base.isValid() && other.isValid())) {
13782 return {
13783 milliseconds: 0,
13784 months: 0
13785 };
13786 }
13787
13788 other = cloneWithOffset(other, base);
13789
13790 if (base.isBefore(other)) {
13791 res = positiveMomentsDifference(base, other);
13792 } else {
13793 res = positiveMomentsDifference(other, base);
13794 res.milliseconds = -res.milliseconds;
13795 res.months = -res.months;
13796 }
13797
13798 return res;
13799 } // TODO: remove 'name' arg after deprecation is removed
13800
13801
13802 function createAdder(direction, name) {
13803 return function (val, period) {
13804 var dur, tmp; //invert the arguments, but complain about it
13805
13806 if (period !== null && !isNaN(+period)) {
13807 deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' + 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.');
13808 tmp = val;
13809 val = period;
13810 period = tmp;
13811 }
13812
13813 val = typeof val === 'string' ? +val : val;
13814 dur = createDuration(val, period);
13815 addSubtract(this, dur, direction);
13816 return this;
13817 };
13818 }
13819
13820 function addSubtract(mom, duration, isAdding, updateOffset) {
13821 var milliseconds = duration._milliseconds,
13822 days = absRound(duration._days),
13823 months = absRound(duration._months);
13824
13825 if (!mom.isValid()) {
13826 // No op
13827 return;
13828 }
13829
13830 updateOffset = updateOffset == null ? true : updateOffset;
13831
13832 if (months) {
13833 setMonth(mom, get(mom, 'Month') + months * isAdding);
13834 }
13835
13836 if (days) {
13837 set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);
13838 }
13839
13840 if (milliseconds) {
13841 mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
13842 }
13843
13844 if (updateOffset) {
13845 hooks.updateOffset(mom, days || months);
13846 }
13847 }
13848
13849 var add = createAdder(1, 'add');
13850 var subtract = createAdder(-1, 'subtract');
13851
13852 function getCalendarFormat(myMoment, now) {
13853 var diff = myMoment.diff(now, 'days', true);
13854 return diff < -6 ? 'sameElse' : diff < -1 ? 'lastWeek' : diff < 0 ? 'lastDay' : diff < 1 ? 'sameDay' : diff < 2 ? 'nextDay' : diff < 7 ? 'nextWeek' : 'sameElse';
13855 }
13856
13857 function calendar$1(time, formats) {
13858 // We want to compare the start of today, vs this.
13859 // Getting start-of-today depends on whether we're local/utc/offset or not.
13860 var now = time || createLocal(),
13861 sod = cloneWithOffset(now, this).startOf('day'),
13862 format = hooks.calendarFormat(this, sod) || 'sameElse';
13863 var output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]);
13864 return this.format(output || this.localeData().calendar(format, this, createLocal(now)));
13865 }
13866
13867 function clone() {
13868 return new Moment(this);
13869 }
13870
13871 function isAfter(input, units) {
13872 var localInput = isMoment(input) ? input : createLocal(input);
13873
13874 if (!(this.isValid() && localInput.isValid())) {
13875 return false;
13876 }
13877
13878 units = normalizeUnits(units) || 'millisecond';
13879
13880 if (units === 'millisecond') {
13881 return this.valueOf() > localInput.valueOf();
13882 } else {
13883 return localInput.valueOf() < this.clone().startOf(units).valueOf();
13884 }
13885 }
13886
13887 function isBefore(input, units) {
13888 var localInput = isMoment(input) ? input : createLocal(input);
13889
13890 if (!(this.isValid() && localInput.isValid())) {
13891 return false;
13892 }
13893
13894 units = normalizeUnits(units) || 'millisecond';
13895
13896 if (units === 'millisecond') {
13897 return this.valueOf() < localInput.valueOf();
13898 } else {
13899 return this.clone().endOf(units).valueOf() < localInput.valueOf();
13900 }
13901 }
13902
13903 function isBetween(from, to, units, inclusivity) {
13904 var localFrom = isMoment(from) ? from : createLocal(from),
13905 localTo = isMoment(to) ? to : createLocal(to);
13906
13907 if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) {
13908 return false;
13909 }
13910
13911 inclusivity = inclusivity || '()';
13912 return (inclusivity[0] === '(' ? this.isAfter(localFrom, units) : !this.isBefore(localFrom, units)) && (inclusivity[1] === ')' ? this.isBefore(localTo, units) : !this.isAfter(localTo, units));
13913 }
13914
13915 function isSame(input, units) {
13916 var localInput = isMoment(input) ? input : createLocal(input),
13917 inputMs;
13918
13919 if (!(this.isValid() && localInput.isValid())) {
13920 return false;
13921 }
13922
13923 units = normalizeUnits(units) || 'millisecond';
13924
13925 if (units === 'millisecond') {
13926 return this.valueOf() === localInput.valueOf();
13927 } else {
13928 inputMs = localInput.valueOf();
13929 return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf();
13930 }
13931 }
13932
13933 function isSameOrAfter(input, units) {
13934 return this.isSame(input, units) || this.isAfter(input, units);
13935 }
13936
13937 function isSameOrBefore(input, units) {
13938 return this.isSame(input, units) || this.isBefore(input, units);
13939 }
13940
13941 function diff(input, units, asFloat) {
13942 var that, zoneDelta, output;
13943
13944 if (!this.isValid()) {
13945 return NaN;
13946 }
13947
13948 that = cloneWithOffset(input, this);
13949
13950 if (!that.isValid()) {
13951 return NaN;
13952 }
13953
13954 zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
13955 units = normalizeUnits(units);
13956
13957 switch (units) {
13958 case 'year':
13959 output = monthDiff(this, that) / 12;
13960 break;
13961
13962 case 'month':
13963 output = monthDiff(this, that);
13964 break;
13965
13966 case 'quarter':
13967 output = monthDiff(this, that) / 3;
13968 break;
13969
13970 case 'second':
13971 output = (this - that) / 1e3;
13972 break;
13973 // 1000
13974
13975 case 'minute':
13976 output = (this - that) / 6e4;
13977 break;
13978 // 1000 * 60
13979
13980 case 'hour':
13981 output = (this - that) / 36e5;
13982 break;
13983 // 1000 * 60 * 60
13984
13985 case 'day':
13986 output = (this - that - zoneDelta) / 864e5;
13987 break;
13988 // 1000 * 60 * 60 * 24, negate dst
13989
13990 case 'week':
13991 output = (this - that - zoneDelta) / 6048e5;
13992 break;
13993 // 1000 * 60 * 60 * 24 * 7, negate dst
13994
13995 default:
13996 output = this - that;
13997 }
13998
13999 return asFloat ? output : absFloor(output);
14000 }
14001
14002 function monthDiff(a, b) {
14003 // difference in months
14004 var wholeMonthDiff = (b.year() - a.year()) * 12 + (b.month() - a.month()),
14005 // b is in (anchor - 1 month, anchor + 1 month)
14006 anchor = a.clone().add(wholeMonthDiff, 'months'),
14007 anchor2,
14008 adjust;
14009
14010 if (b - anchor < 0) {
14011 anchor2 = a.clone().add(wholeMonthDiff - 1, 'months'); // linear across the month
14012
14013 adjust = (b - anchor) / (anchor - anchor2);
14014 } else {
14015 anchor2 = a.clone().add(wholeMonthDiff + 1, 'months'); // linear across the month
14016
14017 adjust = (b - anchor) / (anchor2 - anchor);
14018 } //check for negative zero, return zero if negative zero
14019
14020
14021 return -(wholeMonthDiff + adjust) || 0;
14022 }
14023
14024 hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
14025 hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';
14026
14027 function toString() {
14028 return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
14029 }
14030
14031 function toISOString(keepOffset) {
14032 if (!this.isValid()) {
14033 return null;
14034 }
14035
14036 var utc = keepOffset !== true;
14037 var m = utc ? this.clone().utc() : this;
14038
14039 if (m.year() < 0 || m.year() > 9999) {
14040 return formatMoment(m, utc ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ');
14041 }
14042
14043 if (isFunction(Date.prototype.toISOString)) {
14044 // native implementation is ~50x faster, use it when we can
14045 if (utc) {
14046 return this.toDate().toISOString();
14047 } else {
14048 return new Date(this.valueOf() + this.utcOffset() * 60 * 1000).toISOString().replace('Z', formatMoment(m, 'Z'));
14049 }
14050 }
14051
14052 return formatMoment(m, utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ');
14053 }
14054 /**
14055 * Return a human readable representation of a moment that can
14056 * also be evaluated to get a new moment which is the same
14057 *
14058 * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
14059 */
14060
14061
14062 function inspect() {
14063 if (!this.isValid()) {
14064 return 'moment.invalid(/* ' + this._i + ' */)';
14065 }
14066
14067 var func = 'moment';
14068 var zone = '';
14069
14070 if (!this.isLocal()) {
14071 func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
14072 zone = 'Z';
14073 }
14074
14075 var prefix = '[' + func + '("]';
14076 var year = 0 <= this.year() && this.year() <= 9999 ? 'YYYY' : 'YYYYYY';
14077 var datetime = '-MM-DD[T]HH:mm:ss.SSS';
14078 var suffix = zone + '[")]';
14079 return this.format(prefix + year + datetime + suffix);
14080 }
14081
14082 function format(inputString) {
14083 if (!inputString) {
14084 inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat;
14085 }
14086
14087 var output = formatMoment(this, inputString);
14088 return this.localeData().postformat(output);
14089 }
14090
14091 function from(time, withoutSuffix) {
14092 if (this.isValid() && (isMoment(time) && time.isValid() || createLocal(time).isValid())) {
14093 return createDuration({
14094 to: this,
14095 from: time
14096 }).locale(this.locale()).humanize(!withoutSuffix);
14097 } else {
14098 return this.localeData().invalidDate();
14099 }
14100 }
14101
14102 function fromNow(withoutSuffix) {
14103 return this.from(createLocal(), withoutSuffix);
14104 }
14105
14106 function to(time, withoutSuffix) {
14107 if (this.isValid() && (isMoment(time) && time.isValid() || createLocal(time).isValid())) {
14108 return createDuration({
14109 from: this,
14110 to: time
14111 }).locale(this.locale()).humanize(!withoutSuffix);
14112 } else {
14113 return this.localeData().invalidDate();
14114 }
14115 }
14116
14117 function toNow(withoutSuffix) {
14118 return this.to(createLocal(), withoutSuffix);
14119 } // If passed a locale key, it will set the locale for this
14120 // instance. Otherwise, it will return the locale configuration
14121 // variables for this instance.
14122
14123
14124 function locale(key) {
14125 var newLocaleData;
14126
14127 if (key === undefined) {
14128 return this._locale._abbr;
14129 } else {
14130 newLocaleData = getLocale(key);
14131
14132 if (newLocaleData != null) {
14133 this._locale = newLocaleData;
14134 }
14135
14136 return this;
14137 }
14138 }
14139
14140 var lang = deprecate('moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', function (key) {
14141 if (key === undefined) {
14142 return this.localeData();
14143 } else {
14144 return this.locale(key);
14145 }
14146 });
14147
14148 function localeData() {
14149 return this._locale;
14150 }
14151
14152 var MS_PER_SECOND = 1000;
14153 var MS_PER_MINUTE = 60 * MS_PER_SECOND;
14154 var MS_PER_HOUR = 60 * MS_PER_MINUTE;
14155 var MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR; // actual modulo - handles negative numbers (for dates before 1970):
14156
14157 function mod$1(dividend, divisor) {
14158 return (dividend % divisor + divisor) % divisor;
14159 }
14160
14161 function localStartOfDate(y, m, d) {
14162 // the date constructor remaps years 0-99 to 1900-1999
14163 if (y < 100 && y >= 0) {
14164 // preserve leap years using a full 400 year cycle, then reset
14165 return new Date(y + 400, m, d) - MS_PER_400_YEARS;
14166 } else {
14167 return new Date(y, m, d).valueOf();
14168 }
14169 }
14170
14171 function utcStartOfDate(y, m, d) {
14172 // Date.UTC remaps years 0-99 to 1900-1999
14173 if (y < 100 && y >= 0) {
14174 // preserve leap years using a full 400 year cycle, then reset
14175 return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS;
14176 } else {
14177 return Date.UTC(y, m, d);
14178 }
14179 }
14180
14181 function startOf(units) {
14182 var time;
14183 units = normalizeUnits(units);
14184
14185 if (units === undefined || units === 'millisecond' || !this.isValid()) {
14186 return this;
14187 }
14188
14189 var startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
14190
14191 switch (units) {
14192 case 'year':
14193 time = startOfDate(this.year(), 0, 1);
14194 break;
14195
14196 case 'quarter':
14197 time = startOfDate(this.year(), this.month() - this.month() % 3, 1);
14198 break;
14199
14200 case 'month':
14201 time = startOfDate(this.year(), this.month(), 1);
14202 break;
14203
14204 case 'week':
14205 time = startOfDate(this.year(), this.month(), this.date() - this.weekday());
14206 break;
14207
14208 case 'isoWeek':
14209 time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1));
14210 break;
14211
14212 case 'day':
14213 case 'date':
14214 time = startOfDate(this.year(), this.month(), this.date());
14215 break;
14216
14217 case 'hour':
14218 time = this._d.valueOf();
14219 time -= mod$1(time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR);
14220 break;
14221
14222 case 'minute':
14223 time = this._d.valueOf();
14224 time -= mod$1(time, MS_PER_MINUTE);
14225 break;
14226
14227 case 'second':
14228 time = this._d.valueOf();
14229 time -= mod$1(time, MS_PER_SECOND);
14230 break;
14231 }
14232
14233 this._d.setTime(time);
14234
14235 hooks.updateOffset(this, true);
14236 return this;
14237 }
14238
14239 function endOf(units) {
14240 var time;
14241 units = normalizeUnits(units);
14242
14243 if (units === undefined || units === 'millisecond' || !this.isValid()) {
14244 return this;
14245 }
14246
14247 var startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
14248
14249 switch (units) {
14250 case 'year':
14251 time = startOfDate(this.year() + 1, 0, 1) - 1;
14252 break;
14253
14254 case 'quarter':
14255 time = startOfDate(this.year(), this.month() - this.month() % 3 + 3, 1) - 1;
14256 break;
14257
14258 case 'month':
14259 time = startOfDate(this.year(), this.month() + 1, 1) - 1;
14260 break;
14261
14262 case 'week':
14263 time = startOfDate(this.year(), this.month(), this.date() - this.weekday() + 7) - 1;
14264 break;
14265
14266 case 'isoWeek':
14267 time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1) + 7) - 1;
14268 break;
14269
14270 case 'day':
14271 case 'date':
14272 time = startOfDate(this.year(), this.month(), this.date() + 1) - 1;
14273 break;
14274
14275 case 'hour':
14276 time = this._d.valueOf();
14277 time += MS_PER_HOUR - mod$1(time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR) - 1;
14278 break;
14279
14280 case 'minute':
14281 time = this._d.valueOf();
14282 time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1;
14283 break;
14284
14285 case 'second':
14286 time = this._d.valueOf();
14287 time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1;
14288 break;
14289 }
14290
14291 this._d.setTime(time);
14292
14293 hooks.updateOffset(this, true);
14294 return this;
14295 }
14296
14297 function valueOf() {
14298 return this._d.valueOf() - (this._offset || 0) * 60000;
14299 }
14300
14301 function unix() {
14302 return Math.floor(this.valueOf() / 1000);
14303 }
14304
14305 function toDate() {
14306 return new Date(this.valueOf());
14307 }
14308
14309 function toArray() {
14310 var m = this;
14311 return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()];
14312 }
14313
14314 function toObject() {
14315 var m = this;
14316 return {
14317 years: m.year(),
14318 months: m.month(),
14319 date: m.date(),
14320 hours: m.hours(),
14321 minutes: m.minutes(),
14322 seconds: m.seconds(),
14323 milliseconds: m.milliseconds()
14324 };
14325 }
14326
14327 function toJSON() {
14328 // new Date(NaN).toJSON() === null
14329 return this.isValid() ? this.toISOString() : null;
14330 }
14331
14332 function isValid$2() {
14333 return isValid(this);
14334 }
14335
14336 function parsingFlags() {
14337 return extend({}, getParsingFlags(this));
14338 }
14339
14340 function invalidAt() {
14341 return getParsingFlags(this).overflow;
14342 }
14343
14344 function creationData() {
14345 return {
14346 input: this._i,
14347 format: this._f,
14348 locale: this._locale,
14349 isUTC: this._isUTC,
14350 strict: this._strict
14351 };
14352 } // FORMATTING
14353
14354
14355 addFormatToken(0, ['gg', 2], 0, function () {
14356 return this.weekYear() % 100;
14357 });
14358 addFormatToken(0, ['GG', 2], 0, function () {
14359 return this.isoWeekYear() % 100;
14360 });
14361
14362 function addWeekYearFormatToken(token, getter) {
14363 addFormatToken(0, [token, token.length], 0, getter);
14364 }
14365
14366 addWeekYearFormatToken('gggg', 'weekYear');
14367 addWeekYearFormatToken('ggggg', 'weekYear');
14368 addWeekYearFormatToken('GGGG', 'isoWeekYear');
14369 addWeekYearFormatToken('GGGGG', 'isoWeekYear'); // ALIASES
14370
14371 addUnitAlias('weekYear', 'gg');
14372 addUnitAlias('isoWeekYear', 'GG'); // PRIORITY
14373
14374 addUnitPriority('weekYear', 1);
14375 addUnitPriority('isoWeekYear', 1); // PARSING
14376
14377 addRegexToken('G', matchSigned);
14378 addRegexToken('g', matchSigned);
14379 addRegexToken('GG', match1to2, match2);
14380 addRegexToken('gg', match1to2, match2);
14381 addRegexToken('GGGG', match1to4, match4);
14382 addRegexToken('gggg', match1to4, match4);
14383 addRegexToken('GGGGG', match1to6, match6);
14384 addRegexToken('ggggg', match1to6, match6);
14385 addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) {
14386 week[token.substr(0, 2)] = toInt(input);
14387 });
14388 addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
14389 week[token] = hooks.parseTwoDigitYear(input);
14390 }); // MOMENTS
14391
14392 function getSetWeekYear(input) {
14393 return getSetWeekYearHelper.call(this, input, this.week(), this.weekday(), this.localeData()._week.dow, this.localeData()._week.doy);
14394 }
14395
14396 function getSetISOWeekYear(input) {
14397 return getSetWeekYearHelper.call(this, input, this.isoWeek(), this.isoWeekday(), 1, 4);
14398 }
14399
14400 function getISOWeeksInYear() {
14401 return weeksInYear(this.year(), 1, 4);
14402 }
14403
14404 function getWeeksInYear() {
14405 var weekInfo = this.localeData()._week;
14406
14407 return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
14408 }
14409
14410 function getSetWeekYearHelper(input, week, weekday, dow, doy) {
14411 var weeksTarget;
14412
14413 if (input == null) {
14414 return weekOfYear(this, dow, doy).year;
14415 } else {
14416 weeksTarget = weeksInYear(input, dow, doy);
14417
14418 if (week > weeksTarget) {
14419 week = weeksTarget;
14420 }
14421
14422 return setWeekAll.call(this, input, week, weekday, dow, doy);
14423 }
14424 }
14425
14426 function setWeekAll(weekYear, week, weekday, dow, doy) {
14427 var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
14428 date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
14429 this.year(date.getUTCFullYear());
14430 this.month(date.getUTCMonth());
14431 this.date(date.getUTCDate());
14432 return this;
14433 } // FORMATTING
14434
14435
14436 addFormatToken('Q', 0, 'Qo', 'quarter'); // ALIASES
14437
14438 addUnitAlias('quarter', 'Q'); // PRIORITY
14439
14440 addUnitPriority('quarter', 7); // PARSING
14441
14442 addRegexToken('Q', match1);
14443 addParseToken('Q', function (input, array) {
14444 array[MONTH] = (toInt(input) - 1) * 3;
14445 }); // MOMENTS
14446
14447 function getSetQuarter(input) {
14448 return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
14449 } // FORMATTING
14450
14451
14452 addFormatToken('D', ['DD', 2], 'Do', 'date'); // ALIASES
14453
14454 addUnitAlias('date', 'D'); // PRIORITY
14455
14456 addUnitPriority('date', 9); // PARSING
14457
14458 addRegexToken('D', match1to2);
14459 addRegexToken('DD', match1to2, match2);
14460 addRegexToken('Do', function (isStrict, locale) {
14461 // TODO: Remove "ordinalParse" fallback in next major release.
14462 return isStrict ? locale._dayOfMonthOrdinalParse || locale._ordinalParse : locale._dayOfMonthOrdinalParseLenient;
14463 });
14464 addParseToken(['D', 'DD'], DATE);
14465 addParseToken('Do', function (input, array) {
14466 array[DATE] = toInt(input.match(match1to2)[0]);
14467 }); // MOMENTS
14468
14469 var getSetDayOfMonth = makeGetSet('Date', true); // FORMATTING
14470
14471 addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear'); // ALIASES
14472
14473 addUnitAlias('dayOfYear', 'DDD'); // PRIORITY
14474
14475 addUnitPriority('dayOfYear', 4); // PARSING
14476
14477 addRegexToken('DDD', match1to3);
14478 addRegexToken('DDDD', match3);
14479 addParseToken(['DDD', 'DDDD'], function (input, array, config) {
14480 config._dayOfYear = toInt(input);
14481 }); // HELPERS
14482 // MOMENTS
14483
14484 function getSetDayOfYear(input) {
14485 var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1;
14486 return input == null ? dayOfYear : this.add(input - dayOfYear, 'd');
14487 } // FORMATTING
14488
14489
14490 addFormatToken('m', ['mm', 2], 0, 'minute'); // ALIASES
14491
14492 addUnitAlias('minute', 'm'); // PRIORITY
14493
14494 addUnitPriority('minute', 14); // PARSING
14495
14496 addRegexToken('m', match1to2);
14497 addRegexToken('mm', match1to2, match2);
14498 addParseToken(['m', 'mm'], MINUTE); // MOMENTS
14499
14500 var getSetMinute = makeGetSet('Minutes', false); // FORMATTING
14501
14502 addFormatToken('s', ['ss', 2], 0, 'second'); // ALIASES
14503
14504 addUnitAlias('second', 's'); // PRIORITY
14505
14506 addUnitPriority('second', 15); // PARSING
14507
14508 addRegexToken('s', match1to2);
14509 addRegexToken('ss', match1to2, match2);
14510 addParseToken(['s', 'ss'], SECOND); // MOMENTS
14511
14512 var getSetSecond = makeGetSet('Seconds', false); // FORMATTING
14513
14514 addFormatToken('S', 0, 0, function () {
14515 return ~~(this.millisecond() / 100);
14516 });
14517 addFormatToken(0, ['SS', 2], 0, function () {
14518 return ~~(this.millisecond() / 10);
14519 });
14520 addFormatToken(0, ['SSS', 3], 0, 'millisecond');
14521 addFormatToken(0, ['SSSS', 4], 0, function () {
14522 return this.millisecond() * 10;
14523 });
14524 addFormatToken(0, ['SSSSS', 5], 0, function () {
14525 return this.millisecond() * 100;
14526 });
14527 addFormatToken(0, ['SSSSSS', 6], 0, function () {
14528 return this.millisecond() * 1000;
14529 });
14530 addFormatToken(0, ['SSSSSSS', 7], 0, function () {
14531 return this.millisecond() * 10000;
14532 });
14533 addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
14534 return this.millisecond() * 100000;
14535 });
14536 addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
14537 return this.millisecond() * 1000000;
14538 }); // ALIASES
14539
14540 addUnitAlias('millisecond', 'ms'); // PRIORITY
14541
14542 addUnitPriority('millisecond', 16); // PARSING
14543
14544 addRegexToken('S', match1to3, match1);
14545 addRegexToken('SS', match1to3, match2);
14546 addRegexToken('SSS', match1to3, match3);
14547 var token;
14548
14549 for (token = 'SSSS'; token.length <= 9; token += 'S') {
14550 addRegexToken(token, matchUnsigned);
14551 }
14552
14553 function parseMs(input, array) {
14554 array[MILLISECOND] = toInt(('0.' + input) * 1000);
14555 }
14556
14557 for (token = 'S'; token.length <= 9; token += 'S') {
14558 addParseToken(token, parseMs);
14559 } // MOMENTS
14560
14561
14562 var getSetMillisecond = makeGetSet('Milliseconds', false); // FORMATTING
14563
14564 addFormatToken('z', 0, 0, 'zoneAbbr');
14565 addFormatToken('zz', 0, 0, 'zoneName'); // MOMENTS
14566
14567 function getZoneAbbr() {
14568 return this._isUTC ? 'UTC' : '';
14569 }
14570
14571 function getZoneName() {
14572 return this._isUTC ? 'Coordinated Universal Time' : '';
14573 }
14574
14575 var proto = Moment.prototype;
14576 proto.add = add;
14577 proto.calendar = calendar$1;
14578 proto.clone = clone;
14579 proto.diff = diff;
14580 proto.endOf = endOf;
14581 proto.format = format;
14582 proto.from = from;
14583 proto.fromNow = fromNow;
14584 proto.to = to;
14585 proto.toNow = toNow;
14586 proto.get = stringGet;
14587 proto.invalidAt = invalidAt;
14588 proto.isAfter = isAfter;
14589 proto.isBefore = isBefore;
14590 proto.isBetween = isBetween;
14591 proto.isSame = isSame;
14592 proto.isSameOrAfter = isSameOrAfter;
14593 proto.isSameOrBefore = isSameOrBefore;
14594 proto.isValid = isValid$2;
14595 proto.lang = lang;
14596 proto.locale = locale;
14597 proto.localeData = localeData;
14598 proto.max = prototypeMax;
14599 proto.min = prototypeMin;
14600 proto.parsingFlags = parsingFlags;
14601 proto.set = stringSet;
14602 proto.startOf = startOf;
14603 proto.subtract = subtract;
14604 proto.toArray = toArray;
14605 proto.toObject = toObject;
14606 proto.toDate = toDate;
14607 proto.toISOString = toISOString;
14608 proto.inspect = inspect;
14609 proto.toJSON = toJSON;
14610 proto.toString = toString;
14611 proto.unix = unix;
14612 proto.valueOf = valueOf;
14613 proto.creationData = creationData;
14614 proto.year = getSetYear;
14615 proto.isLeapYear = getIsLeapYear;
14616 proto.weekYear = getSetWeekYear;
14617 proto.isoWeekYear = getSetISOWeekYear;
14618 proto.quarter = proto.quarters = getSetQuarter;
14619 proto.month = getSetMonth;
14620 proto.daysInMonth = getDaysInMonth;
14621 proto.week = proto.weeks = getSetWeek;
14622 proto.isoWeek = proto.isoWeeks = getSetISOWeek;
14623 proto.weeksInYear = getWeeksInYear;
14624 proto.isoWeeksInYear = getISOWeeksInYear;
14625 proto.date = getSetDayOfMonth;
14626 proto.day = proto.days = getSetDayOfWeek;
14627 proto.weekday = getSetLocaleDayOfWeek;
14628 proto.isoWeekday = getSetISODayOfWeek;
14629 proto.dayOfYear = getSetDayOfYear;
14630 proto.hour = proto.hours = getSetHour;
14631 proto.minute = proto.minutes = getSetMinute;
14632 proto.second = proto.seconds = getSetSecond;
14633 proto.millisecond = proto.milliseconds = getSetMillisecond;
14634 proto.utcOffset = getSetOffset;
14635 proto.utc = setOffsetToUTC;
14636 proto.local = setOffsetToLocal;
14637 proto.parseZone = setOffsetToParsedOffset;
14638 proto.hasAlignedHourOffset = hasAlignedHourOffset;
14639 proto.isDST = isDaylightSavingTime;
14640 proto.isLocal = isLocal;
14641 proto.isUtcOffset = isUtcOffset;
14642 proto.isUtc = isUtc;
14643 proto.isUTC = isUtc;
14644 proto.zoneAbbr = getZoneAbbr;
14645 proto.zoneName = getZoneName;
14646 proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth);
14647 proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth);
14648 proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear);
14649 proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone);
14650 proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted);
14651
14652 function createUnix(input) {
14653 return createLocal(input * 1000);
14654 }
14655
14656 function createInZone() {
14657 return createLocal.apply(null, arguments).parseZone();
14658 }
14659
14660 function preParsePostFormat(string) {
14661 return string;
14662 }
14663
14664 var proto$1 = Locale.prototype;
14665 proto$1.calendar = calendar;
14666 proto$1.longDateFormat = longDateFormat;
14667 proto$1.invalidDate = invalidDate;
14668 proto$1.ordinal = ordinal;
14669 proto$1.preparse = preParsePostFormat;
14670 proto$1.postformat = preParsePostFormat;
14671 proto$1.relativeTime = relativeTime;
14672 proto$1.pastFuture = pastFuture;
14673 proto$1.set = set;
14674 proto$1.months = localeMonths;
14675 proto$1.monthsShort = localeMonthsShort;
14676 proto$1.monthsParse = localeMonthsParse;
14677 proto$1.monthsRegex = monthsRegex;
14678 proto$1.monthsShortRegex = monthsShortRegex;
14679 proto$1.week = localeWeek;
14680 proto$1.firstDayOfYear = localeFirstDayOfYear;
14681 proto$1.firstDayOfWeek = localeFirstDayOfWeek;
14682 proto$1.weekdays = localeWeekdays;
14683 proto$1.weekdaysMin = localeWeekdaysMin;
14684 proto$1.weekdaysShort = localeWeekdaysShort;
14685 proto$1.weekdaysParse = localeWeekdaysParse;
14686 proto$1.weekdaysRegex = weekdaysRegex;
14687 proto$1.weekdaysShortRegex = weekdaysShortRegex;
14688 proto$1.weekdaysMinRegex = weekdaysMinRegex;
14689 proto$1.isPM = localeIsPM;
14690 proto$1.meridiem = localeMeridiem;
14691
14692 function get$1(format, index, field, setter) {
14693 var locale = getLocale();
14694 var utc = createUTC().set(setter, index);
14695 return locale[field](utc, format);
14696 }
14697
14698 function listMonthsImpl(format, index, field) {
14699 if (isNumber(format)) {
14700 index = format;
14701 format = undefined;
14702 }
14703
14704 format = format || '';
14705
14706 if (index != null) {
14707 return get$1(format, index, field, 'month');
14708 }
14709
14710 var i;
14711 var out = [];
14712
14713 for (i = 0; i < 12; i++) {
14714 out[i] = get$1(format, i, field, 'month');
14715 }
14716
14717 return out;
14718 } // ()
14719 // (5)
14720 // (fmt, 5)
14721 // (fmt)
14722 // (true)
14723 // (true, 5)
14724 // (true, fmt, 5)
14725 // (true, fmt)
14726
14727
14728 function listWeekdaysImpl(localeSorted, format, index, field) {
14729 if (typeof localeSorted === 'boolean') {
14730 if (isNumber(format)) {
14731 index = format;
14732 format = undefined;
14733 }
14734
14735 format = format || '';
14736 } else {
14737 format = localeSorted;
14738 index = format;
14739 localeSorted = false;
14740
14741 if (isNumber(format)) {
14742 index = format;
14743 format = undefined;
14744 }
14745
14746 format = format || '';
14747 }
14748
14749 var locale = getLocale(),
14750 shift = localeSorted ? locale._week.dow : 0;
14751
14752 if (index != null) {
14753 return get$1(format, (index + shift) % 7, field, 'day');
14754 }
14755
14756 var i;
14757 var out = [];
14758
14759 for (i = 0; i < 7; i++) {
14760 out[i] = get$1(format, (i + shift) % 7, field, 'day');
14761 }
14762
14763 return out;
14764 }
14765
14766 function listMonths(format, index) {
14767 return listMonthsImpl(format, index, 'months');
14768 }
14769
14770 function listMonthsShort(format, index) {
14771 return listMonthsImpl(format, index, 'monthsShort');
14772 }
14773
14774 function listWeekdays(localeSorted, format, index) {
14775 return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
14776 }
14777
14778 function listWeekdaysShort(localeSorted, format, index) {
14779 return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
14780 }
14781
14782 function listWeekdaysMin(localeSorted, format, index) {
14783 return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
14784 }
14785
14786 getSetGlobalLocale('en', {
14787 dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
14788 ordinal: function (number) {
14789 var b = number % 10,
14790 output = toInt(number % 100 / 10) === 1 ? 'th' : b === 1 ? 'st' : b === 2 ? 'nd' : b === 3 ? 'rd' : 'th';
14791 return number + output;
14792 }
14793 }); // Side effect imports
14794
14795 hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale);
14796 hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', getLocale);
14797 var mathAbs = Math.abs;
14798
14799 function abs() {
14800 var data = this._data;
14801 this._milliseconds = mathAbs(this._milliseconds);
14802 this._days = mathAbs(this._days);
14803 this._months = mathAbs(this._months);
14804 data.milliseconds = mathAbs(data.milliseconds);
14805 data.seconds = mathAbs(data.seconds);
14806 data.minutes = mathAbs(data.minutes);
14807 data.hours = mathAbs(data.hours);
14808 data.months = mathAbs(data.months);
14809 data.years = mathAbs(data.years);
14810 return this;
14811 }
14812
14813 function addSubtract$1(duration, input, value, direction) {
14814 var other = createDuration(input, value);
14815 duration._milliseconds += direction * other._milliseconds;
14816 duration._days += direction * other._days;
14817 duration._months += direction * other._months;
14818 return duration._bubble();
14819 } // supports only 2.0-style add(1, 's') or add(duration)
14820
14821
14822 function add$1(input, value) {
14823 return addSubtract$1(this, input, value, 1);
14824 } // supports only 2.0-style subtract(1, 's') or subtract(duration)
14825
14826
14827 function subtract$1(input, value) {
14828 return addSubtract$1(this, input, value, -1);
14829 }
14830
14831 function absCeil(number) {
14832 if (number < 0) {
14833 return Math.floor(number);
14834 } else {
14835 return Math.ceil(number);
14836 }
14837 }
14838
14839 function bubble() {
14840 var milliseconds = this._milliseconds;
14841 var days = this._days;
14842 var months = this._months;
14843 var data = this._data;
14844 var seconds, minutes, hours, years, monthsFromDays; // if we have a mix of positive and negative values, bubble down first
14845 // check: https://github.com/moment/moment/issues/2166
14846
14847 if (!(milliseconds >= 0 && days >= 0 && months >= 0 || milliseconds <= 0 && days <= 0 && months <= 0)) {
14848 milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
14849 days = 0;
14850 months = 0;
14851 } // The following code bubbles up values, see the tests for
14852 // examples of what that means.
14853
14854
14855 data.milliseconds = milliseconds % 1000;
14856 seconds = absFloor(milliseconds / 1000);
14857 data.seconds = seconds % 60;
14858 minutes = absFloor(seconds / 60);
14859 data.minutes = minutes % 60;
14860 hours = absFloor(minutes / 60);
14861 data.hours = hours % 24;
14862 days += absFloor(hours / 24); // convert days to months
14863
14864 monthsFromDays = absFloor(daysToMonths(days));
14865 months += monthsFromDays;
14866 days -= absCeil(monthsToDays(monthsFromDays)); // 12 months -> 1 year
14867
14868 years = absFloor(months / 12);
14869 months %= 12;
14870 data.days = days;
14871 data.months = months;
14872 data.years = years;
14873 return this;
14874 }
14875
14876 function daysToMonths(days) {
14877 // 400 years have 146097 days (taking into account leap year rules)
14878 // 400 years have 12 months === 4800
14879 return days * 4800 / 146097;
14880 }
14881
14882 function monthsToDays(months) {
14883 // the reverse of daysToMonths
14884 return months * 146097 / 4800;
14885 }
14886
14887 function as(units) {
14888 if (!this.isValid()) {
14889 return NaN;
14890 }
14891
14892 var days;
14893 var months;
14894 var milliseconds = this._milliseconds;
14895 units = normalizeUnits(units);
14896
14897 if (units === 'month' || units === 'quarter' || units === 'year') {
14898 days = this._days + milliseconds / 864e5;
14899 months = this._months + daysToMonths(days);
14900
14901 switch (units) {
14902 case 'month':
14903 return months;
14904
14905 case 'quarter':
14906 return months / 3;
14907
14908 case 'year':
14909 return months / 12;
14910 }
14911 } else {
14912 // handle milliseconds separately because of floating point math errors (issue #1867)
14913 days = this._days + Math.round(monthsToDays(this._months));
14914
14915 switch (units) {
14916 case 'week':
14917 return days / 7 + milliseconds / 6048e5;
14918
14919 case 'day':
14920 return days + milliseconds / 864e5;
14921
14922 case 'hour':
14923 return days * 24 + milliseconds / 36e5;
14924
14925 case 'minute':
14926 return days * 1440 + milliseconds / 6e4;
14927
14928 case 'second':
14929 return days * 86400 + milliseconds / 1000;
14930 // Math.floor prevents floating point math errors here
14931
14932 case 'millisecond':
14933 return Math.floor(days * 864e5) + milliseconds;
14934
14935 default:
14936 throw new Error('Unknown unit ' + units);
14937 }
14938 }
14939 } // TODO: Use this.as('ms')?
14940
14941
14942 function valueOf$1() {
14943 if (!this.isValid()) {
14944 return NaN;
14945 }
14946
14947 return this._milliseconds + this._days * 864e5 + this._months % 12 * 2592e6 + toInt(this._months / 12) * 31536e6;
14948 }
14949
14950 function makeAs(alias) {
14951 return function () {
14952 return this.as(alias);
14953 };
14954 }
14955
14956 var asMilliseconds = makeAs('ms');
14957 var asSeconds = makeAs('s');
14958 var asMinutes = makeAs('m');
14959 var asHours = makeAs('h');
14960 var asDays = makeAs('d');
14961 var asWeeks = makeAs('w');
14962 var asMonths = makeAs('M');
14963 var asQuarters = makeAs('Q');
14964 var asYears = makeAs('y');
14965
14966 function clone$1() {
14967 return createDuration(this);
14968 }
14969
14970 function get$2(units) {
14971 units = normalizeUnits(units);
14972 return this.isValid() ? this[units + 's']() : NaN;
14973 }
14974
14975 function makeGetter(name) {
14976 return function () {
14977 return this.isValid() ? this._data[name] : NaN;
14978 };
14979 }
14980
14981 var milliseconds = makeGetter('milliseconds');
14982 var seconds = makeGetter('seconds');
14983 var minutes = makeGetter('minutes');
14984 var hours = makeGetter('hours');
14985 var days = makeGetter('days');
14986 var months = makeGetter('months');
14987 var years = makeGetter('years');
14988
14989 function weeks() {
14990 return absFloor(this.days() / 7);
14991 }
14992
14993 var round = Math.round;
14994 var thresholds = {
14995 ss: 44,
14996 // a few seconds to seconds
14997 s: 45,
14998 // seconds to minute
14999 m: 45,
15000 // minutes to hour
15001 h: 22,
15002 // hours to day
15003 d: 26,
15004 // days to month
15005 M: 11 // months to year
15006
15007 }; // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
15008
15009 function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
15010 return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
15011 }
15012
15013 function relativeTime$1(posNegDuration, withoutSuffix, locale) {
15014 var duration = createDuration(posNegDuration).abs();
15015 var seconds = round(duration.as('s'));
15016 var minutes = round(duration.as('m'));
15017 var hours = round(duration.as('h'));
15018 var days = round(duration.as('d'));
15019 var months = round(duration.as('M'));
15020 var years = round(duration.as('y'));
15021 var a = seconds <= thresholds.ss && ['s', seconds] || seconds < thresholds.s && ['ss', seconds] || minutes <= 1 && ['m'] || minutes < thresholds.m && ['mm', minutes] || hours <= 1 && ['h'] || hours < thresholds.h && ['hh', hours] || days <= 1 && ['d'] || days < thresholds.d && ['dd', days] || months <= 1 && ['M'] || months < thresholds.M && ['MM', months] || years <= 1 && ['y'] || ['yy', years];
15022 a[2] = withoutSuffix;
15023 a[3] = +posNegDuration > 0;
15024 a[4] = locale;
15025 return substituteTimeAgo.apply(null, a);
15026 } // This function allows you to set the rounding function for relative time strings
15027
15028
15029 function getSetRelativeTimeRounding(roundingFunction) {
15030 if (roundingFunction === undefined) {
15031 return round;
15032 }
15033
15034 if (typeof roundingFunction === 'function') {
15035 round = roundingFunction;
15036 return true;
15037 }
15038
15039 return false;
15040 } // This function allows you to set a threshold for relative time strings
15041
15042
15043 function getSetRelativeTimeThreshold(threshold, limit) {
15044 if (thresholds[threshold] === undefined) {
15045 return false;
15046 }
15047
15048 if (limit === undefined) {
15049 return thresholds[threshold];
15050 }
15051
15052 thresholds[threshold] = limit;
15053
15054 if (threshold === 's') {
15055 thresholds.ss = limit - 1;
15056 }
15057
15058 return true;
15059 }
15060
15061 function humanize(withSuffix) {
15062 if (!this.isValid()) {
15063 return this.localeData().invalidDate();
15064 }
15065
15066 var locale = this.localeData();
15067 var output = relativeTime$1(this, !withSuffix, locale);
15068
15069 if (withSuffix) {
15070 output = locale.pastFuture(+this, output);
15071 }
15072
15073 return locale.postformat(output);
15074 }
15075
15076 var abs$1 = Math.abs;
15077
15078 function sign(x) {
15079 return (x > 0) - (x < 0) || +x;
15080 }
15081
15082 function toISOString$1() {
15083 // for ISO strings we do not use the normal bubbling rules:
15084 // * milliseconds bubble up until they become hours
15085 // * days do not bubble at all
15086 // * months bubble up until they become years
15087 // This is because there is no context-free conversion between hours and days
15088 // (think of clock changes)
15089 // and also not between days and months (28-31 days per month)
15090 if (!this.isValid()) {
15091 return this.localeData().invalidDate();
15092 }
15093
15094 var seconds = abs$1(this._milliseconds) / 1000;
15095 var days = abs$1(this._days);
15096 var months = abs$1(this._months);
15097 var minutes, hours, years; // 3600 seconds -> 60 minutes -> 1 hour
15098
15099 minutes = absFloor(seconds / 60);
15100 hours = absFloor(minutes / 60);
15101 seconds %= 60;
15102 minutes %= 60; // 12 months -> 1 year
15103
15104 years = absFloor(months / 12);
15105 months %= 12; // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
15106
15107 var Y = years;
15108 var M = months;
15109 var D = days;
15110 var h = hours;
15111 var m = minutes;
15112 var s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : '';
15113 var total = this.asSeconds();
15114
15115 if (!total) {
15116 // this is the same as C#'s (Noda) and python (isodate)...
15117 // but not other JS (goog.date)
15118 return 'P0D';
15119 }
15120
15121 var totalSign = total < 0 ? '-' : '';
15122 var ymSign = sign(this._months) !== sign(total) ? '-' : '';
15123 var daysSign = sign(this._days) !== sign(total) ? '-' : '';
15124 var hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '';
15125 return totalSign + 'P' + (Y ? ymSign + Y + 'Y' : '') + (M ? ymSign + M + 'M' : '') + (D ? daysSign + D + 'D' : '') + (h || m || s ? 'T' : '') + (h ? hmsSign + h + 'H' : '') + (m ? hmsSign + m + 'M' : '') + (s ? hmsSign + s + 'S' : '');
15126 }
15127
15128 var proto$2 = Duration.prototype;
15129 proto$2.isValid = isValid$1;
15130 proto$2.abs = abs;
15131 proto$2.add = add$1;
15132 proto$2.subtract = subtract$1;
15133 proto$2.as = as;
15134 proto$2.asMilliseconds = asMilliseconds;
15135 proto$2.asSeconds = asSeconds;
15136 proto$2.asMinutes = asMinutes;
15137 proto$2.asHours = asHours;
15138 proto$2.asDays = asDays;
15139 proto$2.asWeeks = asWeeks;
15140 proto$2.asMonths = asMonths;
15141 proto$2.asQuarters = asQuarters;
15142 proto$2.asYears = asYears;
15143 proto$2.valueOf = valueOf$1;
15144 proto$2._bubble = bubble;
15145 proto$2.clone = clone$1;
15146 proto$2.get = get$2;
15147 proto$2.milliseconds = milliseconds;
15148 proto$2.seconds = seconds;
15149 proto$2.minutes = minutes;
15150 proto$2.hours = hours;
15151 proto$2.days = days;
15152 proto$2.weeks = weeks;
15153 proto$2.months = months;
15154 proto$2.years = years;
15155 proto$2.humanize = humanize;
15156 proto$2.toISOString = toISOString$1;
15157 proto$2.toString = toISOString$1;
15158 proto$2.toJSON = toISOString$1;
15159 proto$2.locale = locale;
15160 proto$2.localeData = localeData;
15161 proto$2.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1);
15162 proto$2.lang = lang; // Side effect imports
15163 // FORMATTING
15164
15165 addFormatToken('X', 0, 0, 'unix');
15166 addFormatToken('x', 0, 0, 'valueOf'); // PARSING
15167
15168 addRegexToken('x', matchSigned);
15169 addRegexToken('X', matchTimestamp);
15170 addParseToken('X', function (input, array, config) {
15171 config._d = new Date(parseFloat(input, 10) * 1000);
15172 });
15173 addParseToken('x', function (input, array, config) {
15174 config._d = new Date(toInt(input));
15175 }); // Side effect imports
15176
15177 hooks.version = '2.24.0';
15178 setHookCallback(createLocal);
15179 hooks.fn = proto;
15180 hooks.min = min;
15181 hooks.max = max;
15182 hooks.now = now;
15183 hooks.utc = createUTC;
15184 hooks.unix = createUnix;
15185 hooks.months = listMonths;
15186 hooks.isDate = isDate;
15187 hooks.locale = getSetGlobalLocale;
15188 hooks.invalid = createInvalid;
15189 hooks.duration = createDuration;
15190 hooks.isMoment = isMoment;
15191 hooks.weekdays = listWeekdays;
15192 hooks.parseZone = createInZone;
15193 hooks.localeData = getLocale;
15194 hooks.isDuration = isDuration;
15195 hooks.monthsShort = listMonthsShort;
15196 hooks.weekdaysMin = listWeekdaysMin;
15197 hooks.defineLocale = defineLocale;
15198 hooks.updateLocale = updateLocale;
15199 hooks.locales = listLocales;
15200 hooks.weekdaysShort = listWeekdaysShort;
15201 hooks.normalizeUnits = normalizeUnits;
15202 hooks.relativeTimeRounding = getSetRelativeTimeRounding;
15203 hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
15204 hooks.calendarFormat = getCalendarFormat;
15205 hooks.prototype = proto; // currently HTML5 input type only supports 24-hour formats
15206
15207 hooks.HTML5_FMT = {
15208 DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm',
15209 // <input type="datetime-local" />
15210 DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss',
15211 // <input type="datetime-local" step="1" />
15212 DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS',
15213 // <input type="datetime-local" step="0.001" />
15214 DATE: 'YYYY-MM-DD',
15215 // <input type="date" />
15216 TIME: 'HH:mm',
15217 // <input type="time" />
15218 TIME_SECONDS: 'HH:mm:ss',
15219 // <input type="time" step="1" />
15220 TIME_MS: 'HH:mm:ss.SSS',
15221 // <input type="time" step="0.001" />
15222 WEEK: 'GGGG-[W]WW',
15223 // <input type="week" />
15224 MONTH: 'YYYY-MM' // <input type="month" />
15225
15226 };
15227 return hooks;
15228 });
15229}); // Maps for number <-> hex string conversion
15230
15231var byteToHex$2$1 = [];
15232
15233for (var i$2$1 = 0; i$2$1 < 256; i$2$1++) {
15234 byteToHex$2$1[i$2$1] = (i$2$1 + 0x100).toString(16).substr(1);
15235}
15236/**
15237 * Generate 16 random bytes to be used as a base for UUID.
15238 *
15239 * @ignore
15240 */
15241
15242
15243var random$1$1 = function () {
15244 if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
15245 // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto
15246 // Moderately fast, high quality
15247 var _rnds8 = new Uint8Array(16);
15248
15249 return function whatwgRNG() {
15250 crypto.getRandomValues(_rnds8);
15251 return _rnds8;
15252 };
15253 } // Math.random()-based (RNG)
15254 //
15255 // If all else fails, use Math.random().
15256 // It's fast, but is of unspecified quality.
15257
15258
15259 var _rnds = new Array(16);
15260
15261 return function () {
15262 for (var i = 0, r; i < 16; i++) {
15263 if ((i & 0x03) === 0) {
15264 r = Math.random() * 0x100000000;
15265 }
15266
15267 _rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
15268 }
15269
15270 return _rnds;
15271 }; // uuid.js
15272 //
15273 // Copyright (c) 2010-2012 Robert Kieffer
15274 // MIT License - http://opensource.org/licenses/mit-license.php
15275 // Unique ID creation requires a high quality random # generator. We feature
15276 // detect to determine the best RNG source, normalizing to a function that
15277 // returns 128-bits of randomness, since that's what's usually required
15278 // return require('./rng');
15279}();
15280
15281var byteToHex$1$1$1 = [];
15282
15283for (var i$1$1$1 = 0; i$1$1$1 < 256; i$1$1$1++) {
15284 byteToHex$1$1$1[i$1$1$1] = (i$1$1$1 + 0x100).toString(16).substr(1);
15285} // **`v1()` - Generate time-based UUID**
15286//
15287// Inspired by https://github.com/LiosK/UUID.js
15288// and http://docs.python.org/library/uuid.html
15289// random #'s we need to init node and clockseq
15290
15291
15292var seedBytes$1$1 = random$1$1(); // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
15293
15294var defaultNodeId$1$1 = [seedBytes$1$1[0] | 0x01, seedBytes$1$1[1], seedBytes$1$1[2], seedBytes$1$1[3], seedBytes$1$1[4], seedBytes$1$1[5]]; // Per 4.2.2, randomize (14 bit) clockseq
15295
15296var defaultClockseq$1$1 = (seedBytes$1$1[6] << 8 | seedBytes$1$1[7]) & 0x3fff; // Previous uuid creation time
15297// for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
15298// code from http://momentjs.com/
15299
15300var ASPDateRegex$1 = /^\/?Date\((-?\d+)/i; // Hex color
15301
15302/**
15303 * Hue, Saturation, Value.
15304 */
15305
15306/**
15307 * Test whether given object is a number
15308 *
15309 * @param value - Input value of unknown type.
15310 *
15311 * @returns True if number, false otherwise.
15312 */
15313
15314function isNumber$1(value) {
15315 return value instanceof Number || typeof value === 'number';
15316}
15317/**
15318 * Test whether given object is a string
15319 *
15320 * @param value - Input value of unknown type.
15321 *
15322 * @returns True if string, false otherwise.
15323 */
15324
15325
15326function isString$1(value) {
15327 return value instanceof String || typeof value === 'string';
15328}
15329/**
15330 * Test whether given object is a Moment date.
15331 * @TODO: This is basically a workaround, if Moment was imported property it wouldn't necessary as moment.isMoment is a TS type guard.
15332 *
15333 * @param value - Input value of unknown type.
15334 *
15335 * @returns True if Moment instance, false otherwise.
15336 */
15337
15338
15339function isMoment$1(value) {
15340 return moment$1.isMoment(value);
15341}
15342/**
15343 * Copy property from b to a if property present in a.
15344 * If property in b explicitly set to null, delete it if `allowDeletion` set.
15345 *
15346 * Internal helper routine, should not be exported. Not added to `exports` for that reason.
15347 *
15348 * @param a - Target object.
15349 * @param b - Source object.
15350 * @param prop - Name of property to copy from b to a.
15351 * @param allowDeletion if true, delete property in a if explicitly set to null in b
15352 */
15353
15354
15355function copyOrDelete$1(a, b, prop, allowDeletion) {
15356 var doDeletion = false;
15357
15358 if (allowDeletion === true) {
15359 doDeletion = b[prop] === null && a[prop] !== undefined;
15360 }
15361
15362 if (doDeletion) {
15363 delete a[prop];
15364 } else {
15365 a[prop] = b[prop]; // Remember, this is a reference copy!
15366 }
15367}
15368/**
15369 * Deep extend an object a with the properties of object b
15370 *
15371 * @param a - Target object.
15372 * @param b - Source object.
15373 * @param protoExtend - If true, the prototype values will also be extended
15374 * (ie. the options objects that inherit from others will also get the inherited options).
15375 * @param allowDeletion - If true, the values of fields that are null will be deleted.
15376 *
15377 * @returns Argument a.
15378 */
15379
15380
15381function deepExtend$1(a, b) {
15382 var protoExtend = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
15383 var allowDeletion = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
15384
15385 for (var prop in b) {
15386 if (Object.prototype.hasOwnProperty.call(b, prop) || protoExtend === true) {
15387 if (b[prop] && b[prop].constructor === Object) {
15388 if (a[prop] === undefined) {
15389 a[prop] = {};
15390 }
15391
15392 if (a[prop].constructor === Object) {
15393 deepExtend$1(a[prop], b[prop], protoExtend); // NOTE: allowDeletion not propagated!
15394 } else {
15395 copyOrDelete$1(a, b, prop, allowDeletion);
15396 }
15397 } else if (Array.isArray(b[prop])) {
15398 a[prop] = [];
15399
15400 for (var i = 0; i < b[prop].length; i++) {
15401 a[prop].push(b[prop][i]);
15402 }
15403 } else {
15404 copyOrDelete$1(a, b, prop, allowDeletion);
15405 }
15406 }
15407 }
15408
15409 return a;
15410}
15411/**
15412 * Convert an object into another type
15413 *
15414 * @param object - Value of unknown type.
15415 * @param type - Name of the desired type.
15416 *
15417 * @returns Object in the desired type.
15418 * @throws Error
15419 */
15420
15421
15422function convert$1(object, type) {
15423 var match;
15424
15425 if (object === undefined) {
15426 return undefined;
15427 }
15428
15429 if (object === null) {
15430 return null;
15431 }
15432
15433 if (!type) {
15434 return object;
15435 }
15436
15437 if (!(typeof type === 'string') && !(type instanceof String)) {
15438 throw new Error('Type must be a string');
15439 } //noinspection FallthroughInSwitchStatementJS
15440
15441
15442 switch (type) {
15443 case 'boolean':
15444 case 'Boolean':
15445 return Boolean(object);
15446
15447 case 'number':
15448 case 'Number':
15449 if (isString$1(object) && !isNaN(Date.parse(object))) {
15450 return moment$1(object).valueOf();
15451 } else {
15452 // @TODO: I don't think that Number and String constructors are a good idea.
15453 // This could also fail if the object doesn't have valueOf method or if it's redefined.
15454 // For example: Object.create(null) or { valueOf: 7 }.
15455 return Number(object.valueOf());
15456 }
15457
15458 case 'string':
15459 case 'String':
15460 return String(object);
15461
15462 case 'Date':
15463 if (isNumber$1(object)) {
15464 return new Date(object);
15465 }
15466
15467 if (object instanceof Date) {
15468 return new Date(object.valueOf());
15469 } else if (isMoment$1(object)) {
15470 return new Date(object.valueOf());
15471 }
15472
15473 if (isString$1(object)) {
15474 match = ASPDateRegex$1.exec(object);
15475
15476 if (match) {
15477 // object is an ASP date
15478 return new Date(Number(match[1])); // parse number
15479 } else {
15480 return moment$1(new Date(object)).toDate(); // parse string
15481 }
15482 } else {
15483 throw new Error('Cannot convert object of type ' + getType$1(object) + ' to type Date');
15484 }
15485
15486 case 'Moment':
15487 if (isNumber$1(object)) {
15488 return moment$1(object);
15489 }
15490
15491 if (object instanceof Date) {
15492 return moment$1(object.valueOf());
15493 } else if (isMoment$1(object)) {
15494 return moment$1(object);
15495 }
15496
15497 if (isString$1(object)) {
15498 match = ASPDateRegex$1.exec(object);
15499
15500 if (match) {
15501 // object is an ASP date
15502 return moment$1(Number(match[1])); // parse number
15503 } else {
15504 return moment$1(object); // parse string
15505 }
15506 } else {
15507 throw new Error('Cannot convert object of type ' + getType$1(object) + ' to type Date');
15508 }
15509
15510 case 'ISODate':
15511 if (isNumber$1(object)) {
15512 return new Date(object);
15513 } else if (object instanceof Date) {
15514 return object.toISOString();
15515 } else if (isMoment$1(object)) {
15516 return object.toDate().toISOString();
15517 } else if (isString$1(object)) {
15518 match = ASPDateRegex$1.exec(object);
15519
15520 if (match) {
15521 // object is an ASP date
15522 return new Date(Number(match[1])).toISOString(); // parse number
15523 } else {
15524 return moment$1(object).format(); // ISO 8601
15525 }
15526 } else {
15527 throw new Error('Cannot convert object of type ' + getType$1(object) + ' to type ISODate');
15528 }
15529
15530 case 'ASPDate':
15531 if (isNumber$1(object)) {
15532 return '/Date(' + object + ')/';
15533 } else if (object instanceof Date) {
15534 return '/Date(' + object.valueOf() + ')/';
15535 } else if (isString$1(object)) {
15536 match = ASPDateRegex$1.exec(object);
15537
15538 var _value;
15539
15540 if (match) {
15541 // object is an ASP date
15542 _value = new Date(Number(match[1])).valueOf(); // parse number
15543 } else {
15544 _value = new Date(object).valueOf(); // parse string
15545 }
15546
15547 return '/Date(' + _value + ')/';
15548 } else {
15549 throw new Error('Cannot convert object of type ' + getType$1(object) + ' to type ASPDate');
15550 }
15551
15552 default:
15553 var never = type;
15554 throw new Error("Unknown type ".concat(never));
15555 }
15556}
15557/**
15558 * Get the type of an object, for example exports.getType([]) returns 'Array'
15559 *
15560 * @param object - Input value of unknown type.
15561 *
15562 * @returns Detected type.
15563 */
15564
15565
15566function getType$1(object) {
15567 var type = _typeof(object);
15568
15569 if (type === 'object') {
15570 if (object === null) {
15571 return 'null';
15572 }
15573
15574 if (object instanceof Boolean) {
15575 return 'Boolean';
15576 }
15577
15578 if (object instanceof Number) {
15579 return 'Number';
15580 }
15581
15582 if (object instanceof String) {
15583 return 'String';
15584 }
15585
15586 if (Array.isArray(object)) {
15587 return 'Array';
15588 }
15589
15590 if (object instanceof Date) {
15591 return 'Date';
15592 }
15593
15594 return 'Object';
15595 }
15596
15597 if (type === 'number') {
15598 return 'Number';
15599 }
15600
15601 if (type === 'boolean') {
15602 return 'Boolean';
15603 }
15604
15605 if (type === 'string') {
15606 return 'String';
15607 }
15608
15609 if (type === undefined) {
15610 return 'undefined';
15611 }
15612
15613 return type;
15614}
15615/**
15616 * Determine whether a value can be used as an id.
15617 *
15618 * @param value - Input value of unknown type.
15619 *
15620 * @returns True if the value is valid id, false otherwise.
15621 */
15622
15623
15624function isId(value) {
15625 return typeof value === "string" || typeof value === "number";
15626}
15627/* eslint @typescript-eslint/member-ordering: ["error", { "classes": ["field", "constructor", "method"] }] */
15628
15629/**
15630 * A queue.
15631 *
15632 * @typeParam T - The type of method names to be replaced by queued versions.
15633 */
15634
15635
15636var Queue =
15637/*#__PURE__*/
15638function () {
15639 /**
15640 * Construct a new Queue.
15641 *
15642 * @param options - Queue configuration.
15643 */
15644 function Queue(options) {
15645 classCallCheck(this, Queue);
15646 this._queue = [];
15647 this._timeout = null;
15648 this._extended = null; // options
15649
15650 this.delay = null;
15651 this.max = Infinity;
15652 this.setOptions(options);
15653 }
15654 /**
15655 * Update the configuration of the queue.
15656 *
15657 * @param options - Queue configuration.
15658 */
15659
15660
15661 createClass(Queue, [{
15662 key: "setOptions",
15663 value: function setOptions(options) {
15664 if (options && typeof options.delay !== "undefined") {
15665 this.delay = options.delay;
15666 }
15667
15668 if (options && typeof options.max !== "undefined") {
15669 this.max = options.max;
15670 }
15671
15672 this._flushIfNeeded();
15673 }
15674 /**
15675 * Extend an object with queuing functionality.
15676 * The object will be extended with a function flush, and the methods provided in options.replace will be replaced with queued ones.
15677 *
15678 * @param object - The object to be extended.
15679 * @param options - Additional options.
15680 *
15681 * @returns The created queue.
15682 */
15683
15684 }, {
15685 key: "destroy",
15686
15687 /**
15688 * Destroy the queue. The queue will first flush all queued actions, and in case it has extended an object, will restore the original object.
15689 */
15690 value: function destroy() {
15691 this.flush();
15692
15693 if (this._extended) {
15694 var object = this._extended.object;
15695 var methods = this._extended.methods;
15696
15697 for (var i = 0; i < methods.length; i++) {
15698 var method = methods[i];
15699
15700 if (method.original) {
15701 // @TODO: better solution?
15702 object[method.name] = method.original;
15703 } else {
15704 // @TODO: better solution?
15705 delete object[method.name];
15706 }
15707 }
15708
15709 this._extended = null;
15710 }
15711 }
15712 /**
15713 * Replace a method on an object with a queued version.
15714 *
15715 * @param object - Object having the method.
15716 * @param method - The method name.
15717 */
15718
15719 }, {
15720 key: "replace",
15721 value: function replace(object, method) {
15722 var me = this;
15723 var original = object[method];
15724
15725 if (!original) {
15726 throw new Error("Method " + method + " undefined");
15727 }
15728
15729 object[method] = function () {
15730 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
15731 args[_key] = arguments[_key];
15732 } // add this call to the queue
15733
15734
15735 me.queue({
15736 args: args,
15737 fn: original,
15738 context: this
15739 });
15740 };
15741 }
15742 /**
15743 * Queue a call.
15744 *
15745 * @param entry - The function or entry to be queued.
15746 */
15747
15748 }, {
15749 key: "queue",
15750 value: function queue(entry) {
15751 if (typeof entry === "function") {
15752 this._queue.push({
15753 fn: entry
15754 });
15755 } else {
15756 this._queue.push(entry);
15757 }
15758
15759 this._flushIfNeeded();
15760 }
15761 /**
15762 * Check whether the queue needs to be flushed.
15763 */
15764
15765 }, {
15766 key: "_flushIfNeeded",
15767 value: function _flushIfNeeded() {
15768 var _this = this; // flush when the maximum is exceeded.
15769
15770
15771 if (this._queue.length > this.max) {
15772 this.flush();
15773 } // flush after a period of inactivity when a delay is configured
15774
15775
15776 if (this._timeout != null) {
15777 clearTimeout(this._timeout);
15778 this._timeout = null;
15779 }
15780
15781 if (this.queue.length > 0 && typeof this.delay === "number") {
15782 this._timeout = setTimeout(function () {
15783 _this.flush();
15784 }, this.delay);
15785 }
15786 }
15787 /**
15788 * Flush all queued calls
15789 */
15790
15791 }, {
15792 key: "flush",
15793 value: function flush() {
15794 this._queue.splice(0).forEach(function (entry) {
15795 entry.fn.apply(entry.context || entry.fn, entry.args || []);
15796 });
15797 }
15798 }], [{
15799 key: "extend",
15800 value: function extend(object, options) {
15801 var queue = new Queue(options);
15802
15803 if (object.flush !== undefined) {
15804 throw new Error("Target object already has a property flush");
15805 }
15806
15807 object.flush = function () {
15808 queue.flush();
15809 };
15810
15811 var methods = [{
15812 name: "flush",
15813 original: undefined
15814 }];
15815
15816 if (options && options.replace) {
15817 for (var i = 0; i < options.replace.length; i++) {
15818 var name = options.replace[i];
15819 methods.push({
15820 name: name,
15821 // @TODO: better solution?
15822 original: object[name]
15823 }); // @TODO: better solution?
15824
15825 queue.replace(object, name);
15826 }
15827 }
15828
15829 queue._extended = {
15830 object: object,
15831 methods: methods
15832 };
15833 return queue;
15834 }
15835 }]);
15836 return Queue;
15837}();
15838/* eslint-disable @typescript-eslint/member-ordering */
15839
15840/**
15841 * [[DataSet]] code that can be reused in [[DataView]] or other similar implementations of [[DataInterface]].
15842 *
15843 * @typeParam Item - Item type that may or may not have an id.
15844 * @typeParam IdProp - Name of the property that contains the id.
15845 */
15846
15847
15848var DataSetPart =
15849/*#__PURE__*/
15850function () {
15851 function DataSetPart() {
15852 classCallCheck(this, DataSetPart);
15853 this._subscribers = {
15854 "*": [],
15855 add: [],
15856 remove: [],
15857 update: []
15858 };
15859 /**
15860 * @deprecated Use on instead (PS: DataView.subscribe === DataView.on).
15861 */
15862
15863 this.subscribe = DataSetPart.prototype.on;
15864 /**
15865 * @deprecated Use off instead (PS: DataView.unsubscribe === DataView.off).
15866 */
15867
15868 this.unsubscribe = DataSetPart.prototype.off;
15869 }
15870 /**
15871 * Trigger an event
15872 *
15873 * @param event - Event name.
15874 * @param payload - Event payload.
15875 * @param senderId - Id of the sender.
15876 */
15877
15878
15879 createClass(DataSetPart, [{
15880 key: "_trigger",
15881 value: function _trigger(event, payload, senderId) {
15882 if (event === "*") {
15883 throw new Error("Cannot trigger event *");
15884 }
15885
15886 [].concat(toConsumableArray$1(this._subscribers[event]), toConsumableArray$1(this._subscribers["*"])).forEach(function (subscriber) {
15887 subscriber(event, payload, senderId != null ? senderId : null);
15888 });
15889 }
15890 /**
15891 * Subscribe to an event, add an event listener.
15892 *
15893 * @remarks Non-function callbacks are ignored.
15894 *
15895 * @param event - Event name.
15896 * @param callback - Callback method.
15897 */
15898
15899 }, {
15900 key: "on",
15901 value: function on(event, callback) {
15902 if (typeof callback === "function") {
15903 this._subscribers[event].push(callback);
15904 } // @TODO: Maybe throw for invalid callbacks?
15905
15906 }
15907 /**
15908 * Unsubscribe from an event, remove an event listener.
15909 *
15910 * @remarks If the same callback was subscribed more than once **all** occurences will be removed.
15911 *
15912 * @param event - Event name.
15913 * @param callback - Callback method.
15914 */
15915
15916 }, {
15917 key: "off",
15918 value: function off(event, callback) {
15919 this._subscribers[event] = this._subscribers[event].filter(function (subscriber) {
15920 return subscriber !== callback;
15921 });
15922 }
15923 }]);
15924 return DataSetPart;
15925}();
15926
15927function _arrayWithHoles(arr) {
15928 if (Array.isArray(arr)) return arr;
15929}
15930
15931var arrayWithHoles = _arrayWithHoles;
15932
15933function _iterableToArrayLimit(arr, i) {
15934 var _arr = [];
15935 var _n = true;
15936 var _d = false;
15937 var _e = undefined;
15938
15939 try {
15940 for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
15941 _arr.push(_s.value);
15942
15943 if (i && _arr.length === i) break;
15944 }
15945 } catch (err) {
15946 _d = true;
15947 _e = err;
15948 } finally {
15949 try {
15950 if (!_n && _i["return"] != null) _i["return"]();
15951 } finally {
15952 if (_d) throw _e;
15953 }
15954 }
15955
15956 return _arr;
15957}
15958
15959var iterableToArrayLimit = _iterableToArrayLimit;
15960
15961function _nonIterableRest() {
15962 throw new TypeError("Invalid attempt to destructure non-iterable instance");
15963}
15964
15965var nonIterableRest = _nonIterableRest;
15966
15967function _slicedToArray(arr, i) {
15968 return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || nonIterableRest();
15969}
15970
15971var slicedToArray = _slicedToArray;
15972/**
15973 * Data stream
15974 *
15975 * @remarks
15976 * [[DataStream]] offers an always up to date stream of items from a [[DataSet]] or [[DataView]].
15977 * That means that the stream is evaluated at the time of iteration, conversion to another data type or when [[cache]] is called, not when the [[DataStream]] was created.
15978 * Multiple invocations of for example [[toItemArray]] may yield different results (if the data source like for example [[DataSet]] gets modified).
15979 *
15980 * @typeparam Item - The item type this stream is going to work with.
15981 */
15982
15983var DataStream =
15984/*#__PURE__*/
15985function () {
15986 /**
15987 * Create a new data stream.
15988 *
15989 * @param _pairs - The id, item pairs.
15990 */
15991 function DataStream(_pairs) {
15992 classCallCheck(this, DataStream);
15993 this._pairs = _pairs;
15994 }
15995 /**
15996 * Return an iterable of key, value pairs for every entry in the stream.
15997 */
15998
15999
16000 createClass(DataStream, [{
16001 key: Symbol.iterator,
16002 value:
16003 /*#__PURE__*/
16004 regenerator.mark(function value() {
16005 var _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, _step$value, id, item;
16006
16007 return regenerator.wrap(function value$(_context) {
16008 while (1) {
16009 switch (_context.prev = _context.next) {
16010 case 0:
16011 _iteratorNormalCompletion = true;
16012 _didIteratorError = false;
16013 _iteratorError = undefined;
16014 _context.prev = 3;
16015 _iterator = this._pairs[Symbol.iterator]();
16016
16017 case 5:
16018 if (_iteratorNormalCompletion = (_step = _iterator.next()).done) {
16019 _context.next = 12;
16020 break;
16021 }
16022
16023 _step$value = slicedToArray(_step.value, 2), id = _step$value[0], item = _step$value[1];
16024 _context.next = 9;
16025 return [id, item];
16026
16027 case 9:
16028 _iteratorNormalCompletion = true;
16029 _context.next = 5;
16030 break;
16031
16032 case 12:
16033 _context.next = 18;
16034 break;
16035
16036 case 14:
16037 _context.prev = 14;
16038 _context.t0 = _context["catch"](3);
16039 _didIteratorError = true;
16040 _iteratorError = _context.t0;
16041
16042 case 18:
16043 _context.prev = 18;
16044 _context.prev = 19;
16045
16046 if (!_iteratorNormalCompletion && _iterator.return != null) {
16047 _iterator.return();
16048 }
16049
16050 case 21:
16051 _context.prev = 21;
16052
16053 if (!_didIteratorError) {
16054 _context.next = 24;
16055 break;
16056 }
16057
16058 throw _iteratorError;
16059
16060 case 24:
16061 return _context.finish(21);
16062
16063 case 25:
16064 return _context.finish(18);
16065
16066 case 26:
16067 case "end":
16068 return _context.stop();
16069 }
16070 }
16071 }, value, this, [[3, 14, 18, 26], [19,, 21, 25]]);
16072 })
16073 /**
16074 * Return an iterable of key, value pairs for every entry in the stream.
16075 */
16076
16077 }, {
16078 key: "entries",
16079 value:
16080 /*#__PURE__*/
16081 regenerator.mark(function entries() {
16082 var _iteratorNormalCompletion2, _didIteratorError2, _iteratorError2, _iterator2, _step2, _step2$value, id, item;
16083
16084 return regenerator.wrap(function entries$(_context2) {
16085 while (1) {
16086 switch (_context2.prev = _context2.next) {
16087 case 0:
16088 _iteratorNormalCompletion2 = true;
16089 _didIteratorError2 = false;
16090 _iteratorError2 = undefined;
16091 _context2.prev = 3;
16092 _iterator2 = this._pairs[Symbol.iterator]();
16093
16094 case 5:
16095 if (_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done) {
16096 _context2.next = 12;
16097 break;
16098 }
16099
16100 _step2$value = slicedToArray(_step2.value, 2), id = _step2$value[0], item = _step2$value[1];
16101 _context2.next = 9;
16102 return [id, item];
16103
16104 case 9:
16105 _iteratorNormalCompletion2 = true;
16106 _context2.next = 5;
16107 break;
16108
16109 case 12:
16110 _context2.next = 18;
16111 break;
16112
16113 case 14:
16114 _context2.prev = 14;
16115 _context2.t0 = _context2["catch"](3);
16116 _didIteratorError2 = true;
16117 _iteratorError2 = _context2.t0;
16118
16119 case 18:
16120 _context2.prev = 18;
16121 _context2.prev = 19;
16122
16123 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
16124 _iterator2.return();
16125 }
16126
16127 case 21:
16128 _context2.prev = 21;
16129
16130 if (!_didIteratorError2) {
16131 _context2.next = 24;
16132 break;
16133 }
16134
16135 throw _iteratorError2;
16136
16137 case 24:
16138 return _context2.finish(21);
16139
16140 case 25:
16141 return _context2.finish(18);
16142
16143 case 26:
16144 case "end":
16145 return _context2.stop();
16146 }
16147 }
16148 }, entries, this, [[3, 14, 18, 26], [19,, 21, 25]]);
16149 })
16150 /**
16151 * Return an iterable of keys in the stream.
16152 */
16153
16154 }, {
16155 key: "keys",
16156 value:
16157 /*#__PURE__*/
16158 regenerator.mark(function keys() {
16159 var _iteratorNormalCompletion3, _didIteratorError3, _iteratorError3, _iterator3, _step3, _step3$value, id;
16160
16161 return regenerator.wrap(function keys$(_context3) {
16162 while (1) {
16163 switch (_context3.prev = _context3.next) {
16164 case 0:
16165 _iteratorNormalCompletion3 = true;
16166 _didIteratorError3 = false;
16167 _iteratorError3 = undefined;
16168 _context3.prev = 3;
16169 _iterator3 = this._pairs[Symbol.iterator]();
16170
16171 case 5:
16172 if (_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done) {
16173 _context3.next = 12;
16174 break;
16175 }
16176
16177 _step3$value = slicedToArray(_step3.value, 1), id = _step3$value[0];
16178 _context3.next = 9;
16179 return id;
16180
16181 case 9:
16182 _iteratorNormalCompletion3 = true;
16183 _context3.next = 5;
16184 break;
16185
16186 case 12:
16187 _context3.next = 18;
16188 break;
16189
16190 case 14:
16191 _context3.prev = 14;
16192 _context3.t0 = _context3["catch"](3);
16193 _didIteratorError3 = true;
16194 _iteratorError3 = _context3.t0;
16195
16196 case 18:
16197 _context3.prev = 18;
16198 _context3.prev = 19;
16199
16200 if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
16201 _iterator3.return();
16202 }
16203
16204 case 21:
16205 _context3.prev = 21;
16206
16207 if (!_didIteratorError3) {
16208 _context3.next = 24;
16209 break;
16210 }
16211
16212 throw _iteratorError3;
16213
16214 case 24:
16215 return _context3.finish(21);
16216
16217 case 25:
16218 return _context3.finish(18);
16219
16220 case 26:
16221 case "end":
16222 return _context3.stop();
16223 }
16224 }
16225 }, keys, this, [[3, 14, 18, 26], [19,, 21, 25]]);
16226 })
16227 /**
16228 * Return an iterable of values in the stream.
16229 */
16230
16231 }, {
16232 key: "values",
16233 value:
16234 /*#__PURE__*/
16235 regenerator.mark(function values() {
16236 var _iteratorNormalCompletion4, _didIteratorError4, _iteratorError4, _iterator4, _step4, _step4$value, item;
16237
16238 return regenerator.wrap(function values$(_context4) {
16239 while (1) {
16240 switch (_context4.prev = _context4.next) {
16241 case 0:
16242 _iteratorNormalCompletion4 = true;
16243 _didIteratorError4 = false;
16244 _iteratorError4 = undefined;
16245 _context4.prev = 3;
16246 _iterator4 = this._pairs[Symbol.iterator]();
16247
16248 case 5:
16249 if (_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done) {
16250 _context4.next = 12;
16251 break;
16252 }
16253
16254 _step4$value = slicedToArray(_step4.value, 2), item = _step4$value[1];
16255 _context4.next = 9;
16256 return item;
16257
16258 case 9:
16259 _iteratorNormalCompletion4 = true;
16260 _context4.next = 5;
16261 break;
16262
16263 case 12:
16264 _context4.next = 18;
16265 break;
16266
16267 case 14:
16268 _context4.prev = 14;
16269 _context4.t0 = _context4["catch"](3);
16270 _didIteratorError4 = true;
16271 _iteratorError4 = _context4.t0;
16272
16273 case 18:
16274 _context4.prev = 18;
16275 _context4.prev = 19;
16276
16277 if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
16278 _iterator4.return();
16279 }
16280
16281 case 21:
16282 _context4.prev = 21;
16283
16284 if (!_didIteratorError4) {
16285 _context4.next = 24;
16286 break;
16287 }
16288
16289 throw _iteratorError4;
16290
16291 case 24:
16292 return _context4.finish(21);
16293
16294 case 25:
16295 return _context4.finish(18);
16296
16297 case 26:
16298 case "end":
16299 return _context4.stop();
16300 }
16301 }
16302 }, values, this, [[3, 14, 18, 26], [19,, 21, 25]]);
16303 })
16304 /**
16305 * Return an array containing all the ids in this stream.
16306 *
16307 * @remarks
16308 * The array may contain duplicities.
16309 *
16310 * @returns The array with all ids from this stream.
16311 */
16312
16313 }, {
16314 key: "toIdArray",
16315 value: function toIdArray() {
16316 return toConsumableArray$1(this._pairs).map(function (pair) {
16317 return pair[0];
16318 });
16319 }
16320 /**
16321 * Return an array containing all the items in this stream.
16322 *
16323 * @remarks
16324 * The array may contain duplicities.
16325 *
16326 * @returns The array with all items from this stream.
16327 */
16328
16329 }, {
16330 key: "toItemArray",
16331 value: function toItemArray() {
16332 return toConsumableArray$1(this._pairs).map(function (pair) {
16333 return pair[1];
16334 });
16335 }
16336 /**
16337 * Return an array containing all the entries in this stream.
16338 *
16339 * @remarks
16340 * The array may contain duplicities.
16341 *
16342 * @returns The array with all entries from this stream.
16343 */
16344
16345 }, {
16346 key: "toEntryArray",
16347 value: function toEntryArray() {
16348 return toConsumableArray$1(this._pairs);
16349 }
16350 /**
16351 * Return an object map containing all the items in this stream accessible by ids.
16352 *
16353 * @remarks
16354 * In case of duplicate ids (coerced to string so `7 == '7'`) the last encoutered appears in the returned object.
16355 *
16356 * @returns The object map of all id → item pairs from this stream.
16357 */
16358
16359 }, {
16360 key: "toObjectMap",
16361 value: function toObjectMap() {
16362 var map = Object.create(null);
16363 var _iteratorNormalCompletion5 = true;
16364 var _didIteratorError5 = false;
16365 var _iteratorError5 = undefined;
16366
16367 try {
16368 for (var _iterator5 = this._pairs[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
16369 var _step5$value = slicedToArray(_step5.value, 2),
16370 id = _step5$value[0],
16371 item = _step5$value[1];
16372
16373 map[id] = item;
16374 }
16375 } catch (err) {
16376 _didIteratorError5 = true;
16377 _iteratorError5 = err;
16378 } finally {
16379 try {
16380 if (!_iteratorNormalCompletion5 && _iterator5.return != null) {
16381 _iterator5.return();
16382 }
16383 } finally {
16384 if (_didIteratorError5) {
16385 throw _iteratorError5;
16386 }
16387 }
16388 }
16389
16390 return map;
16391 }
16392 /**
16393 * Return a map containing all the items in this stream accessible by ids.
16394 *
16395 * @returns The map of all id → item pairs from this stream.
16396 */
16397
16398 }, {
16399 key: "toMap",
16400 value: function toMap() {
16401 return new Map(this._pairs);
16402 }
16403 /**
16404 * Return a set containing all the (unique) ids in this stream.
16405 *
16406 * @returns The set of all ids from this stream.
16407 */
16408
16409 }, {
16410 key: "toIdSet",
16411 value: function toIdSet() {
16412 return new Set(this.toIdArray());
16413 }
16414 /**
16415 * Return a set containing all the (unique) items in this stream.
16416 *
16417 * @returns The set of all items from this stream.
16418 */
16419
16420 }, {
16421 key: "toItemSet",
16422 value: function toItemSet() {
16423 return new Set(this.toItemArray());
16424 }
16425 /**
16426 * Cache the items from this stream.
16427 *
16428 * @remarks
16429 * This method allows for items to be fetched immediatelly and used (possibly multiple times) later.
16430 * It can also be used to optimize performance as [[DataStream]] would otherwise reevaluate everything upon each iteration.
16431 *
16432 * ## Example
16433 * ```javascript
16434 * const ds = new DataSet([…])
16435 *
16436 * const cachedStream = ds.stream()
16437 * .filter(…)
16438 * .sort(…)
16439 * .map(…)
16440 * .cached(…) // Data are fetched, processed and cached here.
16441 *
16442 * ds.clear()
16443 * chachedStream // Still has all the items.
16444 * ```
16445 *
16446 * @returns A new [[DataStream]] with cached items (detached from the original [[DataSet]]).
16447 */
16448
16449 }, {
16450 key: "cache",
16451 value: function cache() {
16452 return new DataStream(toConsumableArray$1(this._pairs));
16453 }
16454 /**
16455 * Get the distinct values of given property.
16456 *
16457 * @param callback - The function that picks and possibly converts the property.
16458 *
16459 * @typeparam T - The type of the distinct value.
16460 *
16461 * @returns A set of all distinct properties.
16462 */
16463
16464 }, {
16465 key: "distinct",
16466 value: function distinct(callback) {
16467 var set = new Set();
16468 var _iteratorNormalCompletion6 = true;
16469 var _didIteratorError6 = false;
16470 var _iteratorError6 = undefined;
16471
16472 try {
16473 for (var _iterator6 = this._pairs[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
16474 var _step6$value = slicedToArray(_step6.value, 2),
16475 id = _step6$value[0],
16476 item = _step6$value[1];
16477
16478 set.add(callback(item, id));
16479 }
16480 } catch (err) {
16481 _didIteratorError6 = true;
16482 _iteratorError6 = err;
16483 } finally {
16484 try {
16485 if (!_iteratorNormalCompletion6 && _iterator6.return != null) {
16486 _iterator6.return();
16487 }
16488 } finally {
16489 if (_didIteratorError6) {
16490 throw _iteratorError6;
16491 }
16492 }
16493 }
16494
16495 return set;
16496 }
16497 /**
16498 * Filter the items of the stream.
16499 *
16500 * @param callback - The function that decides whether an item will be included.
16501 *
16502 * @returns A new data stream with the filtered items.
16503 */
16504
16505 }, {
16506 key: "filter",
16507 value: function filter(callback) {
16508 var pairs = this._pairs;
16509 return new DataStream(defineProperty$7({}, Symbol.iterator,
16510 /*#__PURE__*/
16511 regenerator.mark(function _callee() {
16512 var _iteratorNormalCompletion7, _didIteratorError7, _iteratorError7, _iterator7, _step7, _step7$value, id, item;
16513
16514 return regenerator.wrap(function _callee$(_context5) {
16515 while (1) {
16516 switch (_context5.prev = _context5.next) {
16517 case 0:
16518 _iteratorNormalCompletion7 = true;
16519 _didIteratorError7 = false;
16520 _iteratorError7 = undefined;
16521 _context5.prev = 3;
16522 _iterator7 = pairs[Symbol.iterator]();
16523
16524 case 5:
16525 if (_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done) {
16526 _context5.next = 13;
16527 break;
16528 }
16529
16530 _step7$value = slicedToArray(_step7.value, 2), id = _step7$value[0], item = _step7$value[1];
16531
16532 if (!callback(item, id)) {
16533 _context5.next = 10;
16534 break;
16535 }
16536
16537 _context5.next = 10;
16538 return [id, item];
16539
16540 case 10:
16541 _iteratorNormalCompletion7 = true;
16542 _context5.next = 5;
16543 break;
16544
16545 case 13:
16546 _context5.next = 19;
16547 break;
16548
16549 case 15:
16550 _context5.prev = 15;
16551 _context5.t0 = _context5["catch"](3);
16552 _didIteratorError7 = true;
16553 _iteratorError7 = _context5.t0;
16554
16555 case 19:
16556 _context5.prev = 19;
16557 _context5.prev = 20;
16558
16559 if (!_iteratorNormalCompletion7 && _iterator7.return != null) {
16560 _iterator7.return();
16561 }
16562
16563 case 22:
16564 _context5.prev = 22;
16565
16566 if (!_didIteratorError7) {
16567 _context5.next = 25;
16568 break;
16569 }
16570
16571 throw _iteratorError7;
16572
16573 case 25:
16574 return _context5.finish(22);
16575
16576 case 26:
16577 return _context5.finish(19);
16578
16579 case 27:
16580 case "end":
16581 return _context5.stop();
16582 }
16583 }
16584 }, _callee, null, [[3, 15, 19, 27], [20,, 22, 26]]);
16585 })));
16586 }
16587 /**
16588 * Execute a callback for each item of the stream.
16589 *
16590 * @param callback - The function that will be invoked for each item.
16591 */
16592
16593 }, {
16594 key: "forEach",
16595 value: function forEach(callback) {
16596 var _iteratorNormalCompletion8 = true;
16597 var _didIteratorError8 = false;
16598 var _iteratorError8 = undefined;
16599
16600 try {
16601 for (var _iterator8 = this._pairs[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) {
16602 var _step8$value = slicedToArray(_step8.value, 2),
16603 id = _step8$value[0],
16604 item = _step8$value[1];
16605
16606 callback(item, id);
16607 }
16608 } catch (err) {
16609 _didIteratorError8 = true;
16610 _iteratorError8 = err;
16611 } finally {
16612 try {
16613 if (!_iteratorNormalCompletion8 && _iterator8.return != null) {
16614 _iterator8.return();
16615 }
16616 } finally {
16617 if (_didIteratorError8) {
16618 throw _iteratorError8;
16619 }
16620 }
16621 }
16622 }
16623 /**
16624 * Map the items into a different type.
16625 *
16626 * @param callback - The function that does the conversion.
16627 *
16628 * @typeparam Mapped - The type of the item after mapping.
16629 *
16630 * @returns A new data stream with the mapped items.
16631 */
16632
16633 }, {
16634 key: "map",
16635 value: function map(callback) {
16636 var pairs = this._pairs;
16637 return new DataStream(defineProperty$7({}, Symbol.iterator,
16638 /*#__PURE__*/
16639 regenerator.mark(function _callee2() {
16640 var _iteratorNormalCompletion9, _didIteratorError9, _iteratorError9, _iterator9, _step9, _step9$value, id, item;
16641
16642 return regenerator.wrap(function _callee2$(_context6) {
16643 while (1) {
16644 switch (_context6.prev = _context6.next) {
16645 case 0:
16646 _iteratorNormalCompletion9 = true;
16647 _didIteratorError9 = false;
16648 _iteratorError9 = undefined;
16649 _context6.prev = 3;
16650 _iterator9 = pairs[Symbol.iterator]();
16651
16652 case 5:
16653 if (_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done) {
16654 _context6.next = 12;
16655 break;
16656 }
16657
16658 _step9$value = slicedToArray(_step9.value, 2), id = _step9$value[0], item = _step9$value[1];
16659 _context6.next = 9;
16660 return [id, callback(item, id)];
16661
16662 case 9:
16663 _iteratorNormalCompletion9 = true;
16664 _context6.next = 5;
16665 break;
16666
16667 case 12:
16668 _context6.next = 18;
16669 break;
16670
16671 case 14:
16672 _context6.prev = 14;
16673 _context6.t0 = _context6["catch"](3);
16674 _didIteratorError9 = true;
16675 _iteratorError9 = _context6.t0;
16676
16677 case 18:
16678 _context6.prev = 18;
16679 _context6.prev = 19;
16680
16681 if (!_iteratorNormalCompletion9 && _iterator9.return != null) {
16682 _iterator9.return();
16683 }
16684
16685 case 21:
16686 _context6.prev = 21;
16687
16688 if (!_didIteratorError9) {
16689 _context6.next = 24;
16690 break;
16691 }
16692
16693 throw _iteratorError9;
16694
16695 case 24:
16696 return _context6.finish(21);
16697
16698 case 25:
16699 return _context6.finish(18);
16700
16701 case 26:
16702 case "end":
16703 return _context6.stop();
16704 }
16705 }
16706 }, _callee2, null, [[3, 14, 18, 26], [19,, 21, 25]]);
16707 })));
16708 }
16709 /**
16710 * Get the item with the maximum value of given property.
16711 *
16712 * @param callback - The function that picks and possibly converts the property.
16713 *
16714 * @returns The item with the maximum if found otherwise null.
16715 */
16716
16717 }, {
16718 key: "max",
16719 value: function max(callback) {
16720 var iter = this._pairs[Symbol.iterator]();
16721
16722 var curr = iter.next();
16723
16724 if (curr.done) {
16725 return null;
16726 }
16727
16728 var maxItem = curr.value[1];
16729 var maxValue = callback(curr.value[1], curr.value[0]);
16730
16731 while (!(curr = iter.next()).done) {
16732 var _curr$value = slicedToArray(curr.value, 2),
16733 id = _curr$value[0],
16734 item = _curr$value[1];
16735
16736 var _value = callback(item, id);
16737
16738 if (_value > maxValue) {
16739 maxValue = _value;
16740 maxItem = item;
16741 }
16742 }
16743
16744 return maxItem;
16745 }
16746 /**
16747 * Get the item with the minimum value of given property.
16748 *
16749 * @param callback - The function that picks and possibly converts the property.
16750 *
16751 * @returns The item with the minimum if found otherwise null.
16752 */
16753
16754 }, {
16755 key: "min",
16756 value: function min(callback) {
16757 var iter = this._pairs[Symbol.iterator]();
16758
16759 var curr = iter.next();
16760
16761 if (curr.done) {
16762 return null;
16763 }
16764
16765 var minItem = curr.value[1];
16766 var minValue = callback(curr.value[1], curr.value[0]);
16767
16768 while (!(curr = iter.next()).done) {
16769 var _curr$value2 = slicedToArray(curr.value, 2),
16770 id = _curr$value2[0],
16771 item = _curr$value2[1];
16772
16773 var _value2 = callback(item, id);
16774
16775 if (_value2 < minValue) {
16776 minValue = _value2;
16777 minItem = item;
16778 }
16779 }
16780
16781 return minItem;
16782 }
16783 /**
16784 * Reduce the items into a single value.
16785 *
16786 * @param callback - The function that does the reduction.
16787 * @param accumulator - The initial value of the accumulator.
16788 *
16789 * @typeparam T - The type of the accumulated value.
16790 *
16791 * @returns The reduced value.
16792 */
16793
16794 }, {
16795 key: "reduce",
16796 value: function reduce(callback, accumulator) {
16797 var _iteratorNormalCompletion10 = true;
16798 var _didIteratorError10 = false;
16799 var _iteratorError10 = undefined;
16800
16801 try {
16802 for (var _iterator10 = this._pairs[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) {
16803 var _step10$value = slicedToArray(_step10.value, 2),
16804 id = _step10$value[0],
16805 item = _step10$value[1];
16806
16807 accumulator = callback(accumulator, item, id);
16808 }
16809 } catch (err) {
16810 _didIteratorError10 = true;
16811 _iteratorError10 = err;
16812 } finally {
16813 try {
16814 if (!_iteratorNormalCompletion10 && _iterator10.return != null) {
16815 _iterator10.return();
16816 }
16817 } finally {
16818 if (_didIteratorError10) {
16819 throw _iteratorError10;
16820 }
16821 }
16822 }
16823
16824 return accumulator;
16825 }
16826 /**
16827 * Sort the items.
16828 *
16829 * @param callback - Item comparator.
16830 *
16831 * @returns A new stream with sorted items.
16832 */
16833
16834 }, {
16835 key: "sort",
16836 value: function sort(callback) {
16837 var _this = this;
16838
16839 return new DataStream(defineProperty$7({}, Symbol.iterator, function () {
16840 return toConsumableArray$1(_this._pairs).sort(function (_ref3, _ref4) {
16841 var _ref5 = slicedToArray(_ref3, 2),
16842 idA = _ref5[0],
16843 itemA = _ref5[1];
16844
16845 var _ref6 = slicedToArray(_ref4, 2),
16846 idB = _ref6[0],
16847 itemB = _ref6[1];
16848
16849 return callback(itemA, itemB, idA, idB);
16850 })[Symbol.iterator]();
16851 }));
16852 }
16853 }]);
16854 return DataStream;
16855}();
16856
16857function ownKeys$2(object, enumerableOnly) {
16858 var keys = Object.keys(object);
16859
16860 if (Object.getOwnPropertySymbols) {
16861 keys.push.apply(keys, Object.getOwnPropertySymbols(object));
16862 }
16863
16864 if (enumerableOnly) keys = keys.filter(function (sym) {
16865 return Object.getOwnPropertyDescriptor(object, sym).enumerable;
16866 });
16867 return keys;
16868}
16869
16870function _objectSpread$1(target) {
16871 for (var i = 1; i < arguments.length; i++) {
16872 var source = arguments[i] != null ? arguments[i] : {};
16873
16874 if (i % 2) {
16875 ownKeys$2(source, true).forEach(function (key) {
16876 defineProperty$7(target, key, source[key]);
16877 });
16878 } else if (Object.getOwnPropertyDescriptors) {
16879 Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
16880 } else {
16881 ownKeys$2(source).forEach(function (key) {
16882 Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
16883 });
16884 }
16885 }
16886
16887 return target;
16888}
16889/**
16890 * # DataSet
16891 *
16892 * Vis.js comes with a flexible DataSet, which can be used to hold and manipulate unstructured data and listen for changes in the data. The DataSet is key/value based. Data items can be added, updated and removed from the DataSet, and one can subscribe to changes in the DataSet. The data in the DataSet can be filtered and ordered, and fields (like dates) can be converted to a specific type. Data can be normalized when appending it to the DataSet as well.
16893 *
16894 * ## Example
16895 *
16896 * The following example shows how to use a DataSet.
16897 *
16898 * ```javascript
16899 * // create a DataSet
16900 * var options = {};
16901 * var data = new vis.DataSet(options);
16902 *
16903 * // add items
16904 * // note that the data items can contain different properties and data formats
16905 * data.add([
16906 * {id: 1, text: 'item 1', date: new Date(2013, 6, 20), group: 1, first: true},
16907 * {id: 2, text: 'item 2', date: '2013-06-23', group: 2},
16908 * {id: 3, text: 'item 3', date: '2013-06-25', group: 2},
16909 * {id: 4, text: 'item 4'}
16910 * ]);
16911 *
16912 * // subscribe to any change in the DataSet
16913 * data.on('*', function (event, properties, senderId) {
16914 * console.log('event', event, properties);
16915 * });
16916 *
16917 * // update an existing item
16918 * data.update({id: 2, group: 1});
16919 *
16920 * // remove an item
16921 * data.remove(4);
16922 *
16923 * // get all ids
16924 * var ids = data.getIds();
16925 * console.log('ids', ids);
16926 *
16927 * // get a specific item
16928 * var item1 = data.get(1);
16929 * console.log('item1', item1);
16930 *
16931 * // retrieve a filtered subset of the data
16932 * var items = data.get({
16933 * filter: function (item) {
16934 * return item.group == 1;
16935 * }
16936 * });
16937 * console.log('filtered items', items);
16938 *
16939 * // retrieve formatted items
16940 * var items = data.get({
16941 * fields: ['id', 'date'],
16942 * type: {
16943 * date: 'ISODate'
16944 * }
16945 * });
16946 * console.log('formatted items', items);
16947 * ```
16948 *
16949 * @typeParam Item - Item type that may or may not have an id.
16950 * @typeParam IdProp - Name of the property that contains the id.
16951 */
16952
16953
16954var DataSet =
16955/*#__PURE__*/
16956function (_DataSetPart) {
16957 inherits(DataSet, _DataSetPart);
16958 /**
16959 * Construct a new DataSet.
16960 *
16961 * @param data - Initial data or options.
16962 * @param options - Options (type error if data is also options).
16963 */
16964
16965 function DataSet(data, options) {
16966 var _this;
16967
16968 classCallCheck(this, DataSet);
16969 _this = possibleConstructorReturn(this, getPrototypeOf$3(DataSet).call(this)); // correctly read optional arguments
16970
16971 if (data && !Array.isArray(data)) {
16972 options = data;
16973 data = [];
16974 }
16975
16976 _this._options = options || {};
16977 _this._data = new Map(); // map with data indexed by id
16978
16979 _this.length = 0; // number of items in the DataSet
16980
16981 _this._idProp = _this._options.fieldId || "id"; // name of the field containing id
16982
16983 _this._type = {}; // internal field types (NOTE: this can differ from this._options.type)
16984 // all variants of a Date are internally stored as Date, so we can convert
16985 // from everything to everything (also from ISODate to Number for example)
16986
16987 if (_this._options.type) {
16988 var fields = Object.keys(_this._options.type);
16989
16990 for (var i = 0, len = fields.length; i < len; i++) {
16991 var field = fields[i];
16992 var value = _this._options.type[field];
16993
16994 if (value == "Date" || value == "ISODate" || value == "ASPDate") {
16995 _this._type[field] = "Date";
16996 } else {
16997 _this._type[field] = value;
16998 }
16999 }
17000 } // add initial data when provided
17001
17002
17003 if (data && data.length) {
17004 _this.add(data);
17005 }
17006
17007 _this.setOptions(options);
17008
17009 return _this;
17010 }
17011 /**
17012 * Set new options.
17013 *
17014 * @param options - The new options.
17015 */
17016
17017
17018 createClass(DataSet, [{
17019 key: "setOptions",
17020 value: function setOptions(options) {
17021 if (options && options.queue !== undefined) {
17022 if (options.queue === false) {
17023 // delete queue if loaded
17024 if (this._queue) {
17025 this._queue.destroy();
17026
17027 delete this._queue;
17028 }
17029 } else {
17030 // create queue and update its options
17031 if (!this._queue) {
17032 this._queue = Queue.extend(this, {
17033 replace: ["add", "update", "remove"]
17034 });
17035 }
17036
17037 if (options.queue && _typeof_1$1(options.queue) === "object") {
17038 this._queue.setOptions(options.queue);
17039 }
17040 }
17041 }
17042 }
17043 /**
17044 * Add a data item or an array with items.
17045 *
17046 * After the items are added to the DataSet, the DataSet will trigger an event `add`. When a `senderId` is provided, this id will be passed with the triggered event to all subscribers.
17047 *
17048 * ## Example
17049 *
17050 * ```javascript
17051 * // create a DataSet
17052 * const data = new vis.DataSet()
17053 *
17054 * // add items
17055 * const ids = data.add([
17056 * { id: 1, text: 'item 1' },
17057 * { id: 2, text: 'item 2' },
17058 * { text: 'item without an id' }
17059 * ])
17060 *
17061 * console.log(ids) // [1, 2, '<UUIDv4>']
17062 * ```
17063 *
17064 * @param data - Items to be added (ids will be generated if missing).
17065 * @param senderId - Sender id.
17066 *
17067 * @returns addedIds - Array with the ids (generated if not present) of the added items.
17068 *
17069 * @throws When an item with the same id as any of the added items already exists.
17070 */
17071
17072 }, {
17073 key: "add",
17074 value: function add(data, senderId) {
17075 var addedIds = [];
17076 var id;
17077
17078 if (Array.isArray(data)) {
17079 // Array
17080 for (var i = 0, len = data.length; i < len; i++) {
17081 id = this._addItem(data[i]);
17082 addedIds.push(id);
17083 }
17084 } else if (data && _typeof_1$1(data) === "object") {
17085 // Single item
17086 id = this._addItem(data);
17087 addedIds.push(id);
17088 } else {
17089 throw new Error("Unknown dataType");
17090 }
17091
17092 if (addedIds.length) {
17093 this._trigger("add", {
17094 items: addedIds
17095 }, senderId);
17096 }
17097
17098 return addedIds;
17099 }
17100 /**
17101 * Update existing items. When an item does not exist, it will be created.
17102 *
17103 * @remarks
17104 * The provided properties will be merged in the existing item. When an item does not exist, it will be created.
17105 *
17106 * After the items are updated, the DataSet will trigger an event `add` for the added items, and an event `update`. When a `senderId` is provided, this id will be passed with the triggered event to all subscribers.
17107 *
17108 * ## Example
17109 *
17110 * ```javascript
17111 * // create a DataSet
17112 * const data = new vis.DataSet([
17113 * { id: 1, text: 'item 1' },
17114 * { id: 2, text: 'item 2' },
17115 * { id: 3, text: 'item 3' }
17116 * ])
17117 *
17118 * // update items
17119 * const ids = data.update([
17120 * { id: 2, text: 'item 2 (updated)' },
17121 * { id: 4, text: 'item 4 (new)' }
17122 * ])
17123 *
17124 * console.log(ids) // [2, 4]
17125 * ```
17126 *
17127 * ## Warning for TypeScript users
17128 * This method may introduce partial items into the data set. Use add or updateOnly instead for better type safety.
17129 *
17130 * @param data - Items to be updated (if the id is already present) or added (if the id is missing).
17131 * @param senderId - Sender id.
17132 *
17133 * @returns updatedIds - The ids of the added (these may be newly generated if there was no id in the item from the data) or updated items.
17134 *
17135 * @throws When the supplied data is neither an item nor an array of items.
17136 */
17137
17138 }, {
17139 key: "update",
17140 value: function update(data, senderId) {
17141 var _this2 = this;
17142
17143 var addedIds = [];
17144 var updatedIds = [];
17145 var oldData = [];
17146 var updatedData = [];
17147 var idProp = this._idProp;
17148
17149 var addOrUpdate = function addOrUpdate(item) {
17150 var origId = item[idProp];
17151
17152 if (origId != null && _this2._data.has(origId)) {
17153 var fullItem = item; // it has an id, therefore it is a fullitem
17154
17155 var oldItem = Object.assign({}, _this2._data.get(origId)); // update item
17156
17157 var id = _this2._updateItem(fullItem);
17158
17159 updatedIds.push(id);
17160 updatedData.push(fullItem);
17161 oldData.push(oldItem);
17162 } else {
17163 // add new item
17164 var _id = _this2._addItem(item);
17165
17166 addedIds.push(_id);
17167 }
17168 };
17169
17170 if (Array.isArray(data)) {
17171 // Array
17172 for (var i = 0, len = data.length; i < len; i++) {
17173 if (data[i] && _typeof_1$1(data[i]) === "object") {
17174 addOrUpdate(data[i]);
17175 } else {
17176 console.warn("Ignoring input item, which is not an object at index " + i);
17177 }
17178 }
17179 } else if (data && _typeof_1$1(data) === "object") {
17180 // Single item
17181 addOrUpdate(data);
17182 } else {
17183 throw new Error("Unknown dataType");
17184 }
17185
17186 if (addedIds.length) {
17187 this._trigger("add", {
17188 items: addedIds
17189 }, senderId);
17190 }
17191
17192 if (updatedIds.length) {
17193 var props = {
17194 items: updatedIds,
17195 oldData: oldData,
17196 data: updatedData
17197 }; // TODO: remove deprecated property 'data' some day
17198 //Object.defineProperty(props, 'data', {
17199 // 'get': (function() {
17200 // console.warn('Property data is deprecated. Use DataSet.get(ids) to retrieve the new data, use the oldData property on this object to get the old data');
17201 // return updatedData;
17202 // }).bind(this)
17203 //});
17204
17205 this._trigger("update", props, senderId);
17206 }
17207
17208 return addedIds.concat(updatedIds);
17209 }
17210 /**
17211 * Update existing items. When an item does not exist, an error will be thrown.
17212 *
17213 * @remarks
17214 * The provided properties will be deeply merged into the existing item.
17215 * When an item does not exist (id not present in the data set or absent), an error will be thrown and nothing will be changed.
17216 *
17217 * After the items are updated, the DataSet will trigger an event `update`.
17218 * When a `senderId` is provided, this id will be passed with the triggered event to all subscribers.
17219 *
17220 * ## Example
17221 *
17222 * ```javascript
17223 * // create a DataSet
17224 * const data = new vis.DataSet([
17225 * { id: 1, text: 'item 1' },
17226 * { id: 2, text: 'item 2' },
17227 * { id: 3, text: 'item 3' },
17228 * ])
17229 *
17230 * // update items
17231 * const ids = data.update([
17232 * { id: 2, text: 'item 2 (updated)' }, // works
17233 * // { id: 4, text: 'item 4 (new)' }, // would throw
17234 * // { text: 'item 4 (new)' }, // would also throw
17235 * ])
17236 *
17237 * console.log(ids) // [2]
17238 * ```
17239 *
17240 * @param data - Updates (the id and optionally other props) to the items in this data set.
17241 * @param senderId - Sender id.
17242 *
17243 * @returns updatedIds - The ids of the updated items.
17244 *
17245 * @throws When the supplied data is neither an item nor an array of items, when the ids are missing.
17246 */
17247
17248 }, {
17249 key: "updateOnly",
17250 value: function updateOnly(data, senderId) {
17251 var _this3 = this;
17252
17253 if (!Array.isArray(data)) {
17254 data = [data];
17255 }
17256
17257 var updateEventData = data.map(function (update) {
17258 var oldData = _this3._data.get(update[_this3._idProp]);
17259
17260 if (oldData == null) {
17261 throw new Error("Updating non-existent items is not allowed.");
17262 }
17263
17264 return {
17265 oldData: oldData,
17266 update: update
17267 };
17268 }).map(function (_ref) {
17269 var oldData = _ref.oldData,
17270 update = _ref.update;
17271 var id = oldData[_this3._idProp];
17272 var updatedData = deepExtend$1(deepExtend$1({}, oldData), update);
17273
17274 _this3._data.set(id, updatedData);
17275
17276 return {
17277 id: id,
17278 oldData: oldData,
17279 updatedData: updatedData
17280 };
17281 });
17282
17283 if (updateEventData.length) {
17284 var props = {
17285 items: updateEventData.map(function (value) {
17286 return value.id;
17287 }),
17288 oldData: updateEventData.map(function (value) {
17289 return value.oldData;
17290 }),
17291 data: updateEventData.map(function (value) {
17292 return value.updatedData;
17293 })
17294 }; // TODO: remove deprecated property 'data' some day
17295 //Object.defineProperty(props, 'data', {
17296 // 'get': (function() {
17297 // console.warn('Property data is deprecated. Use DataSet.get(ids) to retrieve the new data, use the oldData property on this object to get the old data');
17298 // return updatedData;
17299 // }).bind(this)
17300 //});
17301
17302 this._trigger("update", props, senderId);
17303
17304 return props.items;
17305 } else {
17306 return [];
17307 }
17308 }
17309 /** @inheritdoc */
17310
17311 }, {
17312 key: "get",
17313 value: function get(first, second) {
17314 // @TODO: Woudn't it be better to split this into multiple methods?
17315 // parse the arguments
17316 var id = undefined;
17317 var ids = undefined;
17318 var options = undefined;
17319
17320 if (isId(first)) {
17321 // get(id [, options])
17322 id = first;
17323 options = second;
17324 } else if (Array.isArray(first)) {
17325 // get(ids [, options])
17326 ids = first;
17327 options = second;
17328 } else {
17329 // get([, options])
17330 options = first;
17331 } // determine the return type
17332
17333
17334 var returnType = options && options.returnType === "Object" ? "Object" : "Array"; // @TODO: WTF is this? Or am I missing something?
17335 // var returnType
17336 // if (options && options.returnType) {
17337 // var allowedValues = ['Array', 'Object']
17338 // returnType =
17339 // allowedValues.indexOf(options.returnType) == -1
17340 // ? 'Array'
17341 // : options.returnType
17342 // } else {
17343 // returnType = 'Array'
17344 // }
17345 // build options
17346
17347 var type = options && options.type || this._options.type;
17348 var filter = options && options.filter;
17349 var items = [];
17350 var item = null;
17351 var itemIds = null;
17352 var itemId = null; // convert items
17353
17354 if (id != null) {
17355 // return a single item
17356 item = this._getItem(id, type);
17357
17358 if (item && filter && !filter(item)) {
17359 item = null;
17360 }
17361 } else if (ids != null) {
17362 // return a subset of items
17363 for (var i = 0, len = ids.length; i < len; i++) {
17364 item = this._getItem(ids[i], type);
17365
17366 if (item != null && (!filter || filter(item))) {
17367 items.push(item);
17368 }
17369 }
17370 } else {
17371 // return all items
17372 itemIds = toConsumableArray$1(this._data.keys());
17373
17374 for (var _i = 0, _len = itemIds.length; _i < _len; _i++) {
17375 itemId = itemIds[_i];
17376 item = this._getItem(itemId, type);
17377
17378 if (item != null && (!filter || filter(item))) {
17379 items.push(item);
17380 }
17381 }
17382 } // order the results
17383
17384
17385 if (options && options.order && id == undefined) {
17386 this._sort(items, options.order);
17387 } // filter fields of the items
17388
17389
17390 if (options && options.fields) {
17391 var fields = options.fields;
17392
17393 if (id != undefined && item != null) {
17394 item = this._filterFields(item, fields);
17395 } else {
17396 for (var _i2 = 0, _len2 = items.length; _i2 < _len2; _i2++) {
17397 items[_i2] = this._filterFields(items[_i2], fields);
17398 }
17399 }
17400 } // return the results
17401
17402
17403 if (returnType == "Object") {
17404 var result = {};
17405
17406 for (var _i3 = 0, _len3 = items.length; _i3 < _len3; _i3++) {
17407 var resultant = items[_i3]; // @TODO: Shoudn't this be this._fieldId?
17408 // result[resultant.id] = resultant
17409
17410 var _id2 = resultant[this._idProp];
17411 result[_id2] = resultant;
17412 }
17413
17414 return result;
17415 } else {
17416 if (id != null) {
17417 // a single item
17418 return item;
17419 } else {
17420 // just return our array
17421 return items;
17422 }
17423 }
17424 }
17425 /** @inheritdoc */
17426
17427 }, {
17428 key: "getIds",
17429 value: function getIds(options) {
17430 var data = this._data;
17431 var filter = options && options.filter;
17432 var order = options && options.order;
17433 var type = options && options.type || this._options.type;
17434 var itemIds = toConsumableArray$1(data.keys());
17435 var ids = [];
17436 var item;
17437 var items;
17438
17439 if (filter) {
17440 // get filtered items
17441 if (order) {
17442 // create ordered list
17443 items = [];
17444
17445 for (var i = 0, len = itemIds.length; i < len; i++) {
17446 var id = itemIds[i];
17447 item = this._getItem(id, type);
17448
17449 if (filter(item)) {
17450 items.push(item);
17451 }
17452 }
17453
17454 this._sort(items, order);
17455
17456 for (var _i4 = 0, _len4 = items.length; _i4 < _len4; _i4++) {
17457 ids.push(items[_i4][this._idProp]);
17458 }
17459 } else {
17460 // create unordered list
17461 for (var _i5 = 0, _len5 = itemIds.length; _i5 < _len5; _i5++) {
17462 var _id3 = itemIds[_i5];
17463 item = this._getItem(_id3, type);
17464
17465 if (filter(item)) {
17466 ids.push(item[this._idProp]);
17467 }
17468 }
17469 }
17470 } else {
17471 // get all items
17472 if (order) {
17473 // create an ordered list
17474 items = [];
17475
17476 for (var _i6 = 0, _len6 = itemIds.length; _i6 < _len6; _i6++) {
17477 var _id4 = itemIds[_i6];
17478 items.push(data.get(_id4));
17479 }
17480
17481 this._sort(items, order);
17482
17483 for (var _i7 = 0, _len7 = items.length; _i7 < _len7; _i7++) {
17484 ids.push(items[_i7][this._idProp]);
17485 }
17486 } else {
17487 // create unordered list
17488 for (var _i8 = 0, _len8 = itemIds.length; _i8 < _len8; _i8++) {
17489 var _id5 = itemIds[_i8];
17490 item = data.get(_id5);
17491 ids.push(item[this._idProp]);
17492 }
17493 }
17494 }
17495
17496 return ids;
17497 }
17498 /** @inheritdoc */
17499
17500 }, {
17501 key: "getDataSet",
17502 value: function getDataSet() {
17503 return this;
17504 }
17505 /** @inheritdoc */
17506
17507 }, {
17508 key: "forEach",
17509 value: function forEach(callback, options) {
17510 var filter = options && options.filter;
17511 var type = options && options.type || this._options.type;
17512 var data = this._data;
17513 var itemIds = toConsumableArray$1(data.keys());
17514
17515 if (options && options.order) {
17516 // execute forEach on ordered list
17517 var items = this.get(options);
17518
17519 for (var i = 0, len = items.length; i < len; i++) {
17520 var item = items[i];
17521 var id = item[this._idProp];
17522 callback(item, id);
17523 }
17524 } else {
17525 // unordered
17526 for (var _i9 = 0, _len9 = itemIds.length; _i9 < _len9; _i9++) {
17527 var _id6 = itemIds[_i9];
17528
17529 var _item = this._getItem(_id6, type);
17530
17531 if (!filter || filter(_item)) {
17532 callback(_item, _id6);
17533 }
17534 }
17535 }
17536 }
17537 /** @inheritdoc */
17538
17539 }, {
17540 key: "map",
17541 value: function map(callback, options) {
17542 var filter = options && options.filter;
17543 var type = options && options.type || this._options.type;
17544 var mappedItems = [];
17545 var data = this._data;
17546 var itemIds = toConsumableArray$1(data.keys()); // convert and filter items
17547
17548 for (var i = 0, len = itemIds.length; i < len; i++) {
17549 var id = itemIds[i];
17550
17551 var item = this._getItem(id, type);
17552
17553 if (!filter || filter(item)) {
17554 mappedItems.push(callback(item, id));
17555 }
17556 } // order items
17557
17558
17559 if (options && options.order) {
17560 this._sort(mappedItems, options.order);
17561 }
17562
17563 return mappedItems;
17564 }
17565 /**
17566 * Filter the fields of an item.
17567 *
17568 * @param item - The item whose fields should be filtered.
17569 * @param fields - The names of the fields that will be kept.
17570 *
17571 * @typeParam K - Field name type.
17572 *
17573 * @returns The item without any additional fields.
17574 */
17575
17576 }, {
17577 key: "_filterFields",
17578 value: function _filterFields(item, fields) {
17579 if (!item) {
17580 // item is null
17581 return item;
17582 }
17583
17584 return (Array.isArray(fields) ? // Use the supplied array
17585 fields : // Use the keys of the supplied object
17586 Object.keys(fields)).reduce(function (filteredItem, field) {
17587 filteredItem[field] = item[field];
17588 return filteredItem;
17589 }, {});
17590 }
17591 /**
17592 * Sort the provided array with items.
17593 *
17594 * @param items - Items to be sorted in place.
17595 * @param order - A field name or custom sort function.
17596 *
17597 * @typeParam T - The type of the items in the items array.
17598 */
17599
17600 }, {
17601 key: "_sort",
17602 value: function _sort(items, order) {
17603 if (typeof order === "string") {
17604 // order by provided field name
17605 var name = order; // field name
17606
17607 items.sort(function (a, b) {
17608 // @TODO: How to treat missing properties?
17609 var av = a[name];
17610 var bv = b[name];
17611 return av > bv ? 1 : av < bv ? -1 : 0;
17612 });
17613 } else if (typeof order === "function") {
17614 // order by sort function
17615 items.sort(order);
17616 } else {
17617 // TODO: extend order by an Object {field:string, direction:string}
17618 // where direction can be 'asc' or 'desc'
17619 throw new TypeError("Order must be a function or a string");
17620 }
17621 }
17622 /**
17623 * Remove an item or multiple items by “reference” (only the id is used) or by id.
17624 *
17625 * The method ignores removal of non-existing items, and returns an array containing the ids of the items which are actually removed from the DataSet.
17626 *
17627 * After the items are removed, the DataSet will trigger an event `remove` for the removed items. When a `senderId` is provided, this id will be passed with the triggered event to all subscribers.
17628 *
17629 * ## Example
17630 * ```javascript
17631 * // create a DataSet
17632 * const data = new vis.DataSet([
17633 * { id: 1, text: 'item 1' },
17634 * { id: 2, text: 'item 2' },
17635 * { id: 3, text: 'item 3' }
17636 * ])
17637 *
17638 * // remove items
17639 * const ids = data.remove([2, { id: 3 }, 4])
17640 *
17641 * console.log(ids) // [2, 3]
17642 * ```
17643 *
17644 * @param id - One or more items or ids of items to be removed.
17645 * @param senderId - Sender id.
17646 *
17647 * @returns The ids of the removed items.
17648 */
17649
17650 }, {
17651 key: "remove",
17652 value: function remove(id, senderId) {
17653 var removedIds = [];
17654 var removedItems = []; // force everything to be an array for simplicity
17655
17656 var ids = Array.isArray(id) ? id : [id];
17657
17658 for (var i = 0, len = ids.length; i < len; i++) {
17659 var item = this._remove(ids[i]);
17660
17661 if (item) {
17662 var itemId = item[this._idProp];
17663
17664 if (itemId != null) {
17665 removedIds.push(itemId);
17666 removedItems.push(item);
17667 }
17668 }
17669 }
17670
17671 if (removedIds.length) {
17672 this._trigger("remove", {
17673 items: removedIds,
17674 oldData: removedItems
17675 }, senderId);
17676 }
17677
17678 return removedIds;
17679 }
17680 /**
17681 * Remove an item by its id or reference.
17682 *
17683 * @param id - Id of an item or the item itself.
17684 *
17685 * @returns The removed item if removed, null otherwise.
17686 */
17687
17688 }, {
17689 key: "_remove",
17690 value: function _remove(id) {
17691 // @TODO: It origianlly returned the item although the docs say id.
17692 // The code expects the item, so probably an error in the docs.
17693 var ident; // confirm the id to use based on the args type
17694
17695 if (isId(id)) {
17696 ident = id;
17697 } else if (id && _typeof_1$1(id) === "object") {
17698 ident = id[this._idProp]; // look for the identifier field using ._idProp
17699 } // do the removing if the item is found
17700
17701
17702 if (ident != null && this._data.has(ident)) {
17703 var item = this._data.get(ident) || null;
17704
17705 this._data.delete(ident);
17706
17707 --this.length;
17708 return item;
17709 }
17710
17711 return null;
17712 }
17713 /**
17714 * Clear the entire data set.
17715 *
17716 * After the items are removed, the [[DataSet]] will trigger an event `remove` for all removed items. When a `senderId` is provided, this id will be passed with the triggered event to all subscribers.
17717 *
17718 * @param senderId - Sender id.
17719 *
17720 * @returns removedIds - The ids of all removed items.
17721 */
17722
17723 }, {
17724 key: "clear",
17725 value: function clear(senderId) {
17726 var ids = toConsumableArray$1(this._data.keys());
17727 var items = [];
17728
17729 for (var i = 0, len = ids.length; i < len; i++) {
17730 items.push(this._data.get(ids[i]));
17731 }
17732
17733 this._data.clear();
17734
17735 this.length = 0;
17736
17737 this._trigger("remove", {
17738 items: ids,
17739 oldData: items
17740 }, senderId);
17741
17742 return ids;
17743 }
17744 /**
17745 * Find the item with maximum value of a specified field.
17746 *
17747 * @param field - Name of the property that should be searched for max value.
17748 *
17749 * @returns Item containing max value, or null if no items.
17750 */
17751
17752 }, {
17753 key: "max",
17754 value: function max(field) {
17755 var max = null;
17756 var maxField = null;
17757 var _iteratorNormalCompletion = true;
17758 var _didIteratorError = false;
17759 var _iteratorError = undefined;
17760
17761 try {
17762 for (var _iterator = this._data.values()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
17763 var item = _step.value;
17764 var itemField = item[field];
17765
17766 if (typeof itemField === "number" && (maxField == null || itemField > maxField)) {
17767 max = item;
17768 maxField = itemField;
17769 }
17770 }
17771 } catch (err) {
17772 _didIteratorError = true;
17773 _iteratorError = err;
17774 } finally {
17775 try {
17776 if (!_iteratorNormalCompletion && _iterator.return != null) {
17777 _iterator.return();
17778 }
17779 } finally {
17780 if (_didIteratorError) {
17781 throw _iteratorError;
17782 }
17783 }
17784 }
17785
17786 return max || null;
17787 }
17788 /**
17789 * Find the item with minimum value of a specified field.
17790 *
17791 * @param field - Name of the property that should be searched for min value.
17792 *
17793 * @returns Item containing min value, or null if no items.
17794 */
17795
17796 }, {
17797 key: "min",
17798 value: function min(field) {
17799 var min = null;
17800 var minField = null;
17801 var _iteratorNormalCompletion2 = true;
17802 var _didIteratorError2 = false;
17803 var _iteratorError2 = undefined;
17804
17805 try {
17806 for (var _iterator2 = this._data.values()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
17807 var item = _step2.value;
17808 var itemField = item[field];
17809
17810 if (typeof itemField === "number" && (minField == null || itemField < minField)) {
17811 min = item;
17812 minField = itemField;
17813 }
17814 }
17815 } catch (err) {
17816 _didIteratorError2 = true;
17817 _iteratorError2 = err;
17818 } finally {
17819 try {
17820 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
17821 _iterator2.return();
17822 }
17823 } finally {
17824 if (_didIteratorError2) {
17825 throw _iteratorError2;
17826 }
17827 }
17828 }
17829
17830 return min || null;
17831 }
17832 /**
17833 * Find all distinct values of a specified field
17834 *
17835 * @param prop - The property name whose distinct values should be returned.
17836 *
17837 * @returns Unordered array containing all distinct values. Items without specified property are ignored.
17838 */
17839
17840 }, {
17841 key: "distinct",
17842 value: function distinct(prop) {
17843 var data = this._data;
17844 var itemIds = toConsumableArray$1(data.keys());
17845 var values = [];
17846 var fieldType = this._options.type && this._options.type[prop] || null;
17847 var count = 0;
17848
17849 for (var i = 0, len = itemIds.length; i < len; i++) {
17850 var id = itemIds[i];
17851 var item = data.get(id);
17852 var value = item[prop];
17853 var exists = false;
17854
17855 for (var j = 0; j < count; j++) {
17856 if (values[j] == value) {
17857 exists = true;
17858 break;
17859 }
17860 }
17861
17862 if (!exists && value !== undefined) {
17863 values[count] = value;
17864 count++;
17865 }
17866 }
17867
17868 if (fieldType) {
17869 for (var _i10 = 0, _len10 = values.length; _i10 < _len10; _i10++) {
17870 values[_i10] = convert$1(values[_i10], fieldType);
17871 }
17872 }
17873
17874 return values;
17875 }
17876 /**
17877 * Add a single item. Will fail when an item with the same id already exists.
17878 *
17879 * @param item - A new item to be added.
17880 *
17881 * @returns Added item's id. An id is generated when it is not present in the item.
17882 */
17883
17884 }, {
17885 key: "_addItem",
17886 value: function _addItem(item) {
17887 var id = item[this._idProp];
17888
17889 if (id != null) {
17890 // check whether this id is already taken
17891 if (this._data.has(id)) {
17892 // item already exists
17893 throw new Error("Cannot add item: item with id " + id + " already exists");
17894 }
17895 } else {
17896 // generate an id
17897 id = uuid4$1();
17898 item[this._idProp] = id;
17899 }
17900
17901 var d = {};
17902 var fields = Object.keys(item);
17903
17904 for (var i = 0, len = fields.length; i < len; i++) {
17905 var field = fields[i];
17906 var fieldType = this._type[field]; // type may be undefined
17907
17908 d[field] = convert$1(item[field], fieldType);
17909 }
17910
17911 this._data.set(id, d);
17912
17913 ++this.length;
17914 return id;
17915 }
17916 /**
17917 * Get an item. Fields can be converted to a specific type
17918 *
17919 * @param id - Id of the requested item.
17920 * @param types - Property name to type name object map of type converstions.
17921 *
17922 * @returns The item, optionally after type conversion.
17923 */
17924
17925 }, {
17926 key: "_getItem",
17927 value: function _getItem(id, types) {
17928 // @TODO: I have no idea how to type this.
17929 // get the item from the dataset
17930 var raw = this._data.get(id);
17931
17932 if (!raw) {
17933 return null;
17934 } // convert the items field types
17935
17936
17937 var converted;
17938 var fields = Object.keys(raw);
17939
17940 if (types) {
17941 converted = {};
17942
17943 for (var i = 0, len = fields.length; i < len; i++) {
17944 var field = fields[i];
17945 var value = raw[field];
17946 converted[field] = convert$1(value, types[field]);
17947 }
17948 } else {
17949 // no field types specified, no converting needed
17950 converted = _objectSpread$1({}, raw);
17951 }
17952
17953 if (converted[this._idProp] == null) {
17954 converted[this._idProp] = raw.id;
17955 }
17956
17957 return converted;
17958 }
17959 /**
17960 * Update a single item: merge with existing item.
17961 * Will fail when the item has no id, or when there does not exist an item with the same id.
17962 *
17963 * @param item - The new item
17964 *
17965 * @returns The id of the updated item.
17966 */
17967
17968 }, {
17969 key: "_updateItem",
17970 value: function _updateItem(item) {
17971 var id = item[this._idProp];
17972
17973 if (id == null) {
17974 throw new Error("Cannot update item: item has no id (item: " + JSON.stringify(item) + ")");
17975 }
17976
17977 var d = this._data.get(id);
17978
17979 if (!d) {
17980 // item doesn't exist
17981 throw new Error("Cannot update item: no item with id " + id + " found");
17982 } // merge with current item
17983
17984
17985 var fields = Object.keys(item);
17986
17987 for (var i = 0, len = fields.length; i < len; i++) {
17988 var field = fields[i];
17989 var fieldType = this._type[field]; // type may be undefined
17990
17991 d[field] = convert$1(item[field], fieldType);
17992 }
17993
17994 return id;
17995 }
17996 /** @inheritdoc */
17997
17998 }, {
17999 key: "stream",
18000 value: function stream(ids) {
18001 if (ids) {
18002 var data = this._data;
18003 return new DataStream(defineProperty$7({}, Symbol.iterator,
18004 /*#__PURE__*/
18005 regenerator.mark(function _callee() {
18006 var _iteratorNormalCompletion3, _didIteratorError3, _iteratorError3, _iterator3, _step3, id, item;
18007
18008 return regenerator.wrap(function _callee$(_context) {
18009 while (1) {
18010 switch (_context.prev = _context.next) {
18011 case 0:
18012 _iteratorNormalCompletion3 = true;
18013 _didIteratorError3 = false;
18014 _iteratorError3 = undefined;
18015 _context.prev = 3;
18016 _iterator3 = ids[Symbol.iterator]();
18017
18018 case 5:
18019 if (_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done) {
18020 _context.next = 14;
18021 break;
18022 }
18023
18024 id = _step3.value;
18025 item = data.get(id);
18026
18027 if (!(item != null)) {
18028 _context.next = 11;
18029 break;
18030 }
18031
18032 _context.next = 11;
18033 return [id, item];
18034
18035 case 11:
18036 _iteratorNormalCompletion3 = true;
18037 _context.next = 5;
18038 break;
18039
18040 case 14:
18041 _context.next = 20;
18042 break;
18043
18044 case 16:
18045 _context.prev = 16;
18046 _context.t0 = _context["catch"](3);
18047 _didIteratorError3 = true;
18048 _iteratorError3 = _context.t0;
18049
18050 case 20:
18051 _context.prev = 20;
18052 _context.prev = 21;
18053
18054 if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
18055 _iterator3.return();
18056 }
18057
18058 case 23:
18059 _context.prev = 23;
18060
18061 if (!_didIteratorError3) {
18062 _context.next = 26;
18063 break;
18064 }
18065
18066 throw _iteratorError3;
18067
18068 case 26:
18069 return _context.finish(23);
18070
18071 case 27:
18072 return _context.finish(20);
18073
18074 case 28:
18075 case "end":
18076 return _context.stop();
18077 }
18078 }
18079 }, _callee, null, [[3, 16, 20, 28], [21,, 23, 27]]);
18080 })));
18081 } else {
18082 return new DataStream(defineProperty$7({}, Symbol.iterator, this._data.entries.bind(this._data)));
18083 }
18084 }
18085 }]);
18086 return DataSet;
18087}(DataSetPart);
18088/**
18089 * DataView
18090 *
18091 * A DataView offers a filtered and/or formatted view on a DataSet. One can subscribe to changes in a DataView, and easily get filtered or formatted data without having to specify filters and field types all the time.
18092 *
18093 * ## Example
18094 * ```javascript
18095 * // create a DataSet
18096 * var data = new vis.DataSet();
18097 * data.add([
18098 * {id: 1, text: 'item 1', date: new Date(2013, 6, 20), group: 1, first: true},
18099 * {id: 2, text: 'item 2', date: '2013-06-23', group: 2},
18100 * {id: 3, text: 'item 3', date: '2013-06-25', group: 2},
18101 * {id: 4, text: 'item 4'}
18102 * ]);
18103 *
18104 * // create a DataView
18105 * // the view will only contain items having a property group with value 1,
18106 * // and will only output fields id, text, and date.
18107 * var view = new vis.DataView(data, {
18108 * filter: function (item) {
18109 * return (item.group == 1);
18110 * },
18111 * fields: ['id', 'text', 'date']
18112 * });
18113 *
18114 * // subscribe to any change in the DataView
18115 * view.on('*', function (event, properties, senderId) {
18116 * console.log('event', event, properties);
18117 * });
18118 *
18119 * // update an item in the data set
18120 * data.update({id: 2, group: 1});
18121 *
18122 * // get all ids in the view
18123 * var ids = view.getIds();
18124 * console.log('ids', ids); // will output [1, 2]
18125 *
18126 * // get all items in the view
18127 * var items = view.get();
18128 * ```
18129 *
18130 * @typeParam Item - Item type that may or may not have an id.
18131 * @typeParam IdProp - Name of the property that contains the id.
18132 */
18133
18134
18135var DataView =
18136/*#__PURE__*/
18137function (_DataSetPart) {
18138 inherits(DataView, _DataSetPart);
18139 /**
18140 * Create a DataView.
18141 *
18142 * @param data - The instance containing data (directly or indirectly).
18143 * @param options - Options to configure this data view.
18144 */
18145
18146 function DataView(data, options) {
18147 var _this;
18148
18149 classCallCheck(this, DataView);
18150 _this = possibleConstructorReturn(this, getPrototypeOf$3(DataView).call(this));
18151 /** @inheritdoc */
18152
18153 _this.length = 0;
18154 _this._ids = new Set(); // ids of the items currently in memory (just contains a boolean true)
18155
18156 _this._options = options || {};
18157 _this._listener = _this._onEvent.bind(assertThisInitialized(_this));
18158
18159 _this.setData(data);
18160
18161 return _this;
18162 } // TODO: implement a function .config() to dynamically update things like configured filter
18163 // and trigger changes accordingly
18164
18165 /**
18166 * Set a data source for the view.
18167 *
18168 * @param data - The instance containing data (directly or indirectly).
18169 */
18170
18171
18172 createClass(DataView, [{
18173 key: "setData",
18174 value: function setData(data) {
18175 if (this._data) {
18176 // unsubscribe from current dataset
18177 if (this._data.off) {
18178 this._data.off("*", this._listener);
18179 } // trigger a remove of all items in memory
18180
18181
18182 var ids = this._data.getIds({
18183 filter: this._options.filter
18184 });
18185
18186 var items = this._data.get(ids);
18187
18188 this._ids.clear();
18189
18190 this.length = 0;
18191
18192 this._trigger("remove", {
18193 items: ids,
18194 oldData: items
18195 });
18196 }
18197
18198 if (data != null) {
18199 this._data = data; // trigger an add of all added items
18200
18201 var _ids = this._data.getIds({
18202 filter: this._options.filter
18203 });
18204
18205 for (var i = 0, len = _ids.length; i < len; i++) {
18206 var id = _ids[i];
18207
18208 this._ids.add(id);
18209 }
18210
18211 this.length = _ids.length;
18212
18213 this._trigger("add", {
18214 items: _ids
18215 });
18216 } else {
18217 this._data = new DataSet();
18218 } // subscribe to new dataset
18219
18220
18221 if (this._data.on) {
18222 this._data.on("*", this._listener);
18223 }
18224 }
18225 /**
18226 * Refresh the DataView.
18227 * Useful when the DataView has a filter function containing a variable parameter.
18228 */
18229
18230 }, {
18231 key: "refresh",
18232 value: function refresh() {
18233 var ids = this._data.getIds({
18234 filter: this._options.filter
18235 });
18236
18237 var oldIds = toConsumableArray$1(this._ids);
18238 var newIds = {};
18239 var addedIds = [];
18240 var removedIds = [];
18241 var removedItems = []; // check for additions
18242
18243 for (var i = 0, len = ids.length; i < len; i++) {
18244 var id = ids[i];
18245 newIds[id] = true;
18246
18247 if (!this._ids.has(id)) {
18248 addedIds.push(id);
18249
18250 this._ids.add(id);
18251 }
18252 } // check for removals
18253
18254
18255 for (var _i = 0, _len = oldIds.length; _i < _len; _i++) {
18256 var _id = oldIds[_i];
18257
18258 var item = this._data.get(_id);
18259
18260 if (item == null) {
18261 // @TODO: Investigate.
18262 // Doesn't happen during tests or examples.
18263 // Is it really impossible or could it eventually happen?
18264 // How to handle it if it does? The types guarantee non-nullable items.
18265 console.error("If you see this, report it please.");
18266 } else if (!newIds[_id]) {
18267 removedIds.push(_id);
18268 removedItems.push(item);
18269
18270 this._ids.delete(_id);
18271 }
18272 }
18273
18274 this.length += addedIds.length - removedIds.length; // trigger events
18275
18276 if (addedIds.length) {
18277 this._trigger("add", {
18278 items: addedIds
18279 });
18280 }
18281
18282 if (removedIds.length) {
18283 this._trigger("remove", {
18284 items: removedIds,
18285 oldData: removedItems
18286 });
18287 }
18288 }
18289 /** @inheritdoc */
18290
18291 }, {
18292 key: "get",
18293 value: function get(first, second) {
18294 if (this._data == null) {
18295 return null;
18296 } // parse the arguments
18297
18298
18299 var ids = null;
18300 var options;
18301
18302 if (isId(first) || Array.isArray(first)) {
18303 ids = first;
18304 options = second;
18305 } else {
18306 options = first;
18307 } // extend the options with the default options and provided options
18308
18309
18310 var viewOptions = Object.assign({}, this._options, options); // create a combined filter method when needed
18311
18312 var thisFilter = this._options.filter;
18313 var optionsFilter = options && options.filter;
18314
18315 if (thisFilter && optionsFilter) {
18316 viewOptions.filter = function (item) {
18317 return thisFilter(item) && optionsFilter(item);
18318 };
18319 }
18320
18321 if (ids == null) {
18322 return this._data.get(viewOptions);
18323 } else {
18324 return this._data.get(ids, viewOptions);
18325 }
18326 }
18327 /** @inheritdoc */
18328
18329 }, {
18330 key: "getIds",
18331 value: function getIds(options) {
18332 if (this._data.length) {
18333 var defaultFilter = this._options.filter;
18334 var optionsFilter = options != null ? options.filter : null;
18335 var filter;
18336
18337 if (optionsFilter) {
18338 if (defaultFilter) {
18339 filter = function filter(item) {
18340 return defaultFilter(item) && optionsFilter(item);
18341 };
18342 } else {
18343 filter = optionsFilter;
18344 }
18345 } else {
18346 filter = defaultFilter;
18347 }
18348
18349 return this._data.getIds({
18350 filter: filter,
18351 order: options && options.order
18352 });
18353 } else {
18354 return [];
18355 }
18356 }
18357 /** @inheritdoc */
18358
18359 }, {
18360 key: "forEach",
18361 value: function forEach(callback, options) {
18362 if (this._data) {
18363 var defaultFilter = this._options.filter;
18364 var optionsFilter = options && options.filter;
18365 var filter;
18366
18367 if (optionsFilter) {
18368 if (defaultFilter) {
18369 filter = function filter(item) {
18370 return defaultFilter(item) && optionsFilter(item);
18371 };
18372 } else {
18373 filter = optionsFilter;
18374 }
18375 } else {
18376 filter = defaultFilter;
18377 }
18378
18379 this._data.forEach(callback, {
18380 filter: filter,
18381 order: options && options.order
18382 });
18383 }
18384 }
18385 /** @inheritdoc */
18386
18387 }, {
18388 key: "map",
18389 value: function map(callback, options) {
18390 if (this._data) {
18391 var defaultFilter = this._options.filter;
18392 var optionsFilter = options && options.filter;
18393 var filter;
18394
18395 if (optionsFilter) {
18396 if (defaultFilter) {
18397 filter = function filter(item) {
18398 return defaultFilter(item) && optionsFilter(item);
18399 };
18400 } else {
18401 filter = optionsFilter;
18402 }
18403 } else {
18404 filter = defaultFilter;
18405 }
18406
18407 return this._data.map(callback, {
18408 filter: filter,
18409 order: options && options.order
18410 });
18411 } else {
18412 return [];
18413 }
18414 }
18415 /** @inheritdoc */
18416
18417 }, {
18418 key: "getDataSet",
18419 value: function getDataSet() {
18420 return this._data.getDataSet();
18421 }
18422 /** @inheritdoc */
18423
18424 }, {
18425 key: "stream",
18426 value: function stream(ids) {
18427 return this._data.stream(ids || defineProperty$7({}, Symbol.iterator, this._ids.keys.bind(this._ids)));
18428 }
18429 /**
18430 * Event listener. Will propagate all events from the connected data set to the subscribers of the DataView, but will filter the items and only trigger when there are changes in the filtered data set.
18431 *
18432 * @param event - The name of the event.
18433 * @param params - Parameters of the event.
18434 * @param senderId - Id supplied by the sender.
18435 */
18436
18437 }, {
18438 key: "_onEvent",
18439 value: function _onEvent(event, params, senderId) {
18440 if (!params || !params.items || !this._data) {
18441 return;
18442 }
18443
18444 var ids = params.items;
18445 var addedIds = [];
18446 var updatedIds = [];
18447 var removedIds = [];
18448 var oldItems = [];
18449 var updatedItems = [];
18450 var removedItems = [];
18451
18452 switch (event) {
18453 case "add":
18454 // filter the ids of the added items
18455 for (var i = 0, len = ids.length; i < len; i++) {
18456 var id = ids[i];
18457 var item = this.get(id);
18458
18459 if (item) {
18460 this._ids.add(id);
18461
18462 addedIds.push(id);
18463 }
18464 }
18465
18466 break;
18467
18468 case "update":
18469 // determine the event from the views viewpoint: an updated
18470 // item can be added, updated, or removed from this view.
18471 for (var _i2 = 0, _len2 = ids.length; _i2 < _len2; _i2++) {
18472 var _id2 = ids[_i2];
18473
18474 var _item = this.get(_id2);
18475
18476 if (_item) {
18477 if (this._ids.has(_id2)) {
18478 updatedIds.push(_id2);
18479 updatedItems.push(params.data[_i2]);
18480 oldItems.push(params.oldData[_i2]);
18481 } else {
18482 this._ids.add(_id2);
18483
18484 addedIds.push(_id2);
18485 }
18486 } else {
18487 if (this._ids.has(_id2)) {
18488 this._ids.delete(_id2);
18489
18490 removedIds.push(_id2);
18491 removedItems.push(params.oldData[_i2]);
18492 }
18493 }
18494 }
18495
18496 break;
18497
18498 case "remove":
18499 // filter the ids of the removed items
18500 for (var _i3 = 0, _len3 = ids.length; _i3 < _len3; _i3++) {
18501 var _id3 = ids[_i3];
18502
18503 if (this._ids.has(_id3)) {
18504 this._ids.delete(_id3);
18505
18506 removedIds.push(_id3);
18507 removedItems.push(params.oldData[_i3]);
18508 }
18509 }
18510
18511 break;
18512 }
18513
18514 this.length += addedIds.length - removedIds.length;
18515
18516 if (addedIds.length) {
18517 this._trigger("add", {
18518 items: addedIds
18519 }, senderId);
18520 }
18521
18522 if (updatedIds.length) {
18523 this._trigger("update", {
18524 items: updatedIds,
18525 oldData: oldItems,
18526 data: updatedItems
18527 }, senderId);
18528 }
18529
18530 if (removedIds.length) {
18531 this._trigger("remove", {
18532 items: removedIds,
18533 oldData: removedItems
18534 }, senderId);
18535 }
18536 }
18537 }]);
18538 return DataView;
18539}(DataSetPart);
18540
18541var index = {
18542 DataSet: DataSet,
18543 DataView: DataView,
18544 Queue: Queue
18545};
18546
18547function _typeof$1(obj) {
18548 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
18549 _typeof$1 = function (obj) {
18550 return typeof obj;
18551 };
18552 } else {
18553 _typeof$1 = function (obj) {
18554 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
18555 };
18556 }
18557
18558 return _typeof$1(obj);
18559}
18560
18561function _classCallCheck$1(instance, Constructor) {
18562 if (!(instance instanceof Constructor)) {
18563 throw new TypeError("Cannot call a class as a function");
18564 }
18565}
18566
18567function _defineProperties$1(target, props) {
18568 for (var i = 0; i < props.length; i++) {
18569 var descriptor = props[i];
18570 descriptor.enumerable = descriptor.enumerable || false;
18571 descriptor.configurable = true;
18572 if ("value" in descriptor) descriptor.writable = true;
18573 Object.defineProperty(target, descriptor.key, descriptor);
18574 }
18575}
18576
18577function _createClass$1(Constructor, protoProps, staticProps) {
18578 if (protoProps) _defineProperties$1(Constructor.prototype, protoProps);
18579 if (staticProps) _defineProperties$1(Constructor, staticProps);
18580 return Constructor;
18581}
18582
18583/**
18584 * Expose `Emitter`.
18585 */
18586var emitterComponent = Emitter;
18587/**
18588 * Initialize a new `Emitter`.
18589 *
18590 * @api public
18591 */
18592
18593function Emitter(obj) {
18594 if (obj) return mixin(obj);
18595}
18596/**
18597 * Mixin the emitter properties.
18598 *
18599 * @param {Object} obj
18600 * @return {Object}
18601 * @api private
18602 */
18603
18604function mixin(obj) {
18605 for (var key in Emitter.prototype) {
18606 obj[key] = Emitter.prototype[key];
18607 }
18608
18609 return obj;
18610}
18611/**
18612 * Listen on the given `event` with `fn`.
18613 *
18614 * @param {String} event
18615 * @param {Function} fn
18616 * @return {Emitter}
18617 * @api public
18618 */
18619
18620
18621Emitter.prototype.on = Emitter.prototype.addEventListener = function (event, fn) {
18622 this._callbacks = this._callbacks || {};
18623 (this._callbacks[event] = this._callbacks[event] || []).push(fn);
18624 return this;
18625};
18626/**
18627 * Adds an `event` listener that will be invoked a single
18628 * time then automatically removed.
18629 *
18630 * @param {String} event
18631 * @param {Function} fn
18632 * @return {Emitter}
18633 * @api public
18634 */
18635
18636
18637Emitter.prototype.once = function (event, fn) {
18638 var self = this;
18639 this._callbacks = this._callbacks || {};
18640
18641 function on() {
18642 self.off(event, on);
18643 fn.apply(this, arguments);
18644 }
18645
18646 on.fn = fn;
18647 this.on(event, on);
18648 return this;
18649};
18650/**
18651 * Remove the given callback for `event` or all
18652 * registered callbacks.
18653 *
18654 * @param {String} event
18655 * @param {Function} fn
18656 * @return {Emitter}
18657 * @api public
18658 */
18659
18660
18661Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function (event, fn) {
18662 this._callbacks = this._callbacks || {}; // all
18663
18664 if (0 == arguments.length) {
18665 this._callbacks = {};
18666 return this;
18667 } // specific event
18668
18669
18670 var callbacks = this._callbacks[event];
18671 if (!callbacks) return this; // remove all handlers
18672
18673 if (1 == arguments.length) {
18674 delete this._callbacks[event];
18675 return this;
18676 } // remove specific handler
18677
18678
18679 var cb;
18680
18681 for (var i = 0; i < callbacks.length; i++) {
18682 cb = callbacks[i];
18683
18684 if (cb === fn || cb.fn === fn) {
18685 callbacks.splice(i, 1);
18686 break;
18687 }
18688 }
18689
18690 return this;
18691};
18692/**
18693 * Emit `event` with the given args.
18694 *
18695 * @param {String} event
18696 * @param {Mixed} ...
18697 * @return {Emitter}
18698 */
18699
18700
18701Emitter.prototype.emit = function (event) {
18702 this._callbacks = this._callbacks || {};
18703 var args = [].slice.call(arguments, 1),
18704 callbacks = this._callbacks[event];
18705
18706 if (callbacks) {
18707 callbacks = callbacks.slice(0);
18708
18709 for (var i = 0, len = callbacks.length; i < len; ++i) {
18710 callbacks[i].apply(this, args);
18711 }
18712 }
18713
18714 return this;
18715};
18716/**
18717 * Return array of callbacks for `event`.
18718 *
18719 * @param {String} event
18720 * @return {Array}
18721 * @api public
18722 */
18723
18724
18725Emitter.prototype.listeners = function (event) {
18726 this._callbacks = this._callbacks || {};
18727 return this._callbacks[event] || [];
18728};
18729/**
18730 * Check if this emitter has `event` handlers.
18731 *
18732 * @param {String} event
18733 * @return {Boolean}
18734 * @api public
18735 */
18736
18737
18738Emitter.prototype.hasListeners = function (event) {
18739 return !!this.listeners(event).length;
18740};
18741
18742/**
18743 * @prototype Point3d
18744 * @param {number} [x]
18745 * @param {number} [y]
18746 * @param {number} [z]
18747 */
18748function Point3d(x, y, z) {
18749 this.x = x !== undefined ? x : 0;
18750 this.y = y !== undefined ? y : 0;
18751 this.z = z !== undefined ? z : 0;
18752}
18753/**
18754 * Subtract the two provided points, returns a-b
18755 * @param {Point3d} a
18756 * @param {Point3d} b
18757 * @return {Point3d} a-b
18758 */
18759
18760
18761Point3d.subtract = function (a, b) {
18762 var sub = new Point3d();
18763 sub.x = a.x - b.x;
18764 sub.y = a.y - b.y;
18765 sub.z = a.z - b.z;
18766 return sub;
18767};
18768/**
18769 * Add the two provided points, returns a+b
18770 * @param {Point3d} a
18771 * @param {Point3d} b
18772 * @return {Point3d} a+b
18773 */
18774
18775
18776Point3d.add = function (a, b) {
18777 var sum = new Point3d();
18778 sum.x = a.x + b.x;
18779 sum.y = a.y + b.y;
18780 sum.z = a.z + b.z;
18781 return sum;
18782};
18783/**
18784 * Calculate the average of two 3d points
18785 * @param {Point3d} a
18786 * @param {Point3d} b
18787 * @return {Point3d} The average, (a+b)/2
18788 */
18789
18790
18791Point3d.avg = function (a, b) {
18792 return new Point3d((a.x + b.x) / 2, (a.y + b.y) / 2, (a.z + b.z) / 2);
18793};
18794/**
18795 * Calculate the cross product of the two provided points, returns axb
18796 * Documentation: http://en.wikipedia.org/wiki/Cross_product
18797 * @param {Point3d} a
18798 * @param {Point3d} b
18799 * @return {Point3d} cross product axb
18800 */
18801
18802
18803Point3d.crossProduct = function (a, b) {
18804 var crossproduct = new Point3d();
18805 crossproduct.x = a.y * b.z - a.z * b.y;
18806 crossproduct.y = a.z * b.x - a.x * b.z;
18807 crossproduct.z = a.x * b.y - a.y * b.x;
18808 return crossproduct;
18809};
18810/**
18811 * Rtrieve the length of the vector (or the distance from this point to the origin
18812 * @return {number} length
18813 */
18814
18815
18816Point3d.prototype.length = function () {
18817 return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
18818};
18819
18820var Point3d_1 = Point3d;
18821
18822/**
18823 * @prototype Point2d
18824 * @param {number} [x]
18825 * @param {number} [y]
18826 */
18827function Point2d(x, y) {
18828 this.x = x !== undefined ? x : 0;
18829 this.y = y !== undefined ? y : 0;
18830}
18831
18832var Point2d_1 = Point2d;
18833
18834/**
18835 * An html slider control with start/stop/prev/next buttons
18836 *
18837 * @constructor Slider
18838 * @param {Element} container The element where the slider will be created
18839 * @param {Object} options Available options:
18840 * {boolean} visible If true (default) the
18841 * slider is visible.
18842 */
18843
18844function Slider(container, options) {
18845 if (container === undefined) {
18846 throw new Error('No container element defined');
18847 }
18848
18849 this.container = container;
18850 this.visible = options && options.visible != undefined ? options.visible : true;
18851
18852 if (this.visible) {
18853 this.frame = document.createElement('DIV'); //this.frame.style.backgroundColor = '#E5E5E5';
18854
18855 this.frame.style.width = '100%';
18856 this.frame.style.position = 'relative';
18857 this.container.appendChild(this.frame);
18858 this.frame.prev = document.createElement('INPUT');
18859 this.frame.prev.type = 'BUTTON';
18860 this.frame.prev.value = 'Prev';
18861 this.frame.appendChild(this.frame.prev);
18862 this.frame.play = document.createElement('INPUT');
18863 this.frame.play.type = 'BUTTON';
18864 this.frame.play.value = 'Play';
18865 this.frame.appendChild(this.frame.play);
18866 this.frame.next = document.createElement('INPUT');
18867 this.frame.next.type = 'BUTTON';
18868 this.frame.next.value = 'Next';
18869 this.frame.appendChild(this.frame.next);
18870 this.frame.bar = document.createElement('INPUT');
18871 this.frame.bar.type = 'BUTTON';
18872 this.frame.bar.style.position = 'absolute';
18873 this.frame.bar.style.border = '1px solid red';
18874 this.frame.bar.style.width = '100px';
18875 this.frame.bar.style.height = '6px';
18876 this.frame.bar.style.borderRadius = '2px';
18877 this.frame.bar.style.MozBorderRadius = '2px';
18878 this.frame.bar.style.border = '1px solid #7F7F7F';
18879 this.frame.bar.style.backgroundColor = '#E5E5E5';
18880 this.frame.appendChild(this.frame.bar);
18881 this.frame.slide = document.createElement('INPUT');
18882 this.frame.slide.type = 'BUTTON';
18883 this.frame.slide.style.margin = '0px';
18884 this.frame.slide.value = ' ';
18885 this.frame.slide.style.position = 'relative';
18886 this.frame.slide.style.left = '-100px';
18887 this.frame.appendChild(this.frame.slide); // create events
18888
18889 var me = this;
18890
18891 this.frame.slide.onmousedown = function (event) {
18892 me._onMouseDown(event);
18893 };
18894
18895 this.frame.prev.onclick = function (event) {
18896 me.prev(event);
18897 };
18898
18899 this.frame.play.onclick = function (event) {
18900 me.togglePlay(event);
18901 };
18902
18903 this.frame.next.onclick = function (event) {
18904 me.next(event);
18905 };
18906 }
18907
18908 this.onChangeCallback = undefined;
18909 this.values = [];
18910 this.index = undefined;
18911 this.playTimeout = undefined;
18912 this.playInterval = 1000; // milliseconds
18913
18914 this.playLoop = true;
18915}
18916/**
18917 * Select the previous index
18918 */
18919
18920
18921Slider.prototype.prev = function () {
18922 var index = this.getIndex();
18923
18924 if (index > 0) {
18925 index--;
18926 this.setIndex(index);
18927 }
18928};
18929/**
18930 * Select the next index
18931 */
18932
18933
18934Slider.prototype.next = function () {
18935 var index = this.getIndex();
18936
18937 if (index < this.values.length - 1) {
18938 index++;
18939 this.setIndex(index);
18940 }
18941};
18942/**
18943 * Select the next index
18944 */
18945
18946
18947Slider.prototype.playNext = function () {
18948 var start = new Date();
18949 var index = this.getIndex();
18950
18951 if (index < this.values.length - 1) {
18952 index++;
18953 this.setIndex(index);
18954 } else if (this.playLoop) {
18955 // jump to the start
18956 index = 0;
18957 this.setIndex(index);
18958 }
18959
18960 var end = new Date();
18961 var diff = end - start; // calculate how much time it to to set the index and to execute the callback
18962 // function.
18963
18964 var interval = Math.max(this.playInterval - diff, 0); // document.title = diff // TODO: cleanup
18965
18966 var me = this;
18967 this.playTimeout = setTimeout(function () {
18968 me.playNext();
18969 }, interval);
18970};
18971/**
18972 * Toggle start or stop playing
18973 */
18974
18975
18976Slider.prototype.togglePlay = function () {
18977 if (this.playTimeout === undefined) {
18978 this.play();
18979 } else {
18980 this.stop();
18981 }
18982};
18983/**
18984 * Start playing
18985 */
18986
18987
18988Slider.prototype.play = function () {
18989 // Test whether already playing
18990 if (this.playTimeout) return;
18991 this.playNext();
18992
18993 if (this.frame) {
18994 this.frame.play.value = 'Stop';
18995 }
18996};
18997/**
18998 * Stop playing
18999 */
19000
19001
19002Slider.prototype.stop = function () {
19003 clearInterval(this.playTimeout);
19004 this.playTimeout = undefined;
19005
19006 if (this.frame) {
19007 this.frame.play.value = 'Play';
19008 }
19009};
19010/**
19011 * Set a callback function which will be triggered when the value of the
19012 * slider bar has changed.
19013 *
19014 * @param {function} callback
19015 */
19016
19017
19018Slider.prototype.setOnChangeCallback = function (callback) {
19019 this.onChangeCallback = callback;
19020};
19021/**
19022 * Set the interval for playing the list
19023 * @param {number} interval The interval in milliseconds
19024 */
19025
19026
19027Slider.prototype.setPlayInterval = function (interval) {
19028 this.playInterval = interval;
19029};
19030/**
19031 * Retrieve the current play interval
19032 * @return {number} interval The interval in milliseconds
19033 */
19034
19035
19036Slider.prototype.getPlayInterval = function () {
19037 return this.playInterval;
19038};
19039/**
19040 * Set looping on or off
19041 * @param {boolean} doLoop If true, the slider will jump to the start when
19042 * the end is passed, and will jump to the end
19043 * when the start is passed.
19044 *
19045 */
19046
19047
19048Slider.prototype.setPlayLoop = function (doLoop) {
19049 this.playLoop = doLoop;
19050};
19051/**
19052 * Execute the onchange callback function
19053 */
19054
19055
19056Slider.prototype.onChange = function () {
19057 if (this.onChangeCallback !== undefined) {
19058 this.onChangeCallback();
19059 }
19060};
19061/**
19062 * redraw the slider on the correct place
19063 */
19064
19065
19066Slider.prototype.redraw = function () {
19067 if (this.frame) {
19068 // resize the bar
19069 this.frame.bar.style.top = this.frame.clientHeight / 2 - this.frame.bar.offsetHeight / 2 + 'px';
19070 this.frame.bar.style.width = this.frame.clientWidth - this.frame.prev.clientWidth - this.frame.play.clientWidth - this.frame.next.clientWidth - 30 + 'px'; // position the slider button
19071
19072 var left = this.indexToLeft(this.index);
19073 this.frame.slide.style.left = left + 'px';
19074 }
19075};
19076/**
19077 * Set the list with values for the slider
19078 * @param {Array} values A javascript array with values (any type)
19079 */
19080
19081
19082Slider.prototype.setValues = function (values) {
19083 this.values = values;
19084 if (this.values.length > 0) this.setIndex(0);else this.index = undefined;
19085};
19086/**
19087 * Select a value by its index
19088 * @param {number} index
19089 */
19090
19091
19092Slider.prototype.setIndex = function (index) {
19093 if (index < this.values.length) {
19094 this.index = index;
19095 this.redraw();
19096 this.onChange();
19097 } else {
19098 throw new Error('Index out of range');
19099 }
19100};
19101/**
19102 * retrieve the index of the currently selected vaue
19103 * @return {number} index
19104 */
19105
19106
19107Slider.prototype.getIndex = function () {
19108 return this.index;
19109};
19110/**
19111 * retrieve the currently selected value
19112 * @return {*} value
19113 */
19114
19115
19116Slider.prototype.get = function () {
19117 return this.values[this.index];
19118};
19119
19120Slider.prototype._onMouseDown = function (event) {
19121 // only react on left mouse button down
19122 var leftButtonDown = event.which ? event.which === 1 : event.button === 1;
19123 if (!leftButtonDown) return;
19124 this.startClientX = event.clientX;
19125 this.startSlideX = parseFloat(this.frame.slide.style.left);
19126 this.frame.style.cursor = 'move'; // add event listeners to handle moving the contents
19127 // we store the function onmousemove and onmouseup in the graph, so we can
19128 // remove the eventlisteners lateron in the function mouseUp()
19129
19130 var me = this;
19131
19132 this.onmousemove = function (event) {
19133 me._onMouseMove(event);
19134 };
19135
19136 this.onmouseup = function (event) {
19137 me._onMouseUp(event);
19138 };
19139
19140 util.addEventListener(document, 'mousemove', this.onmousemove);
19141 util.addEventListener(document, 'mouseup', this.onmouseup);
19142 util.preventDefault(event);
19143};
19144
19145Slider.prototype.leftToIndex = function (left) {
19146 var width = parseFloat(this.frame.bar.style.width) - this.frame.slide.clientWidth - 10;
19147 var x = left - 3;
19148 var index = Math.round(x / width * (this.values.length - 1));
19149 if (index < 0) index = 0;
19150 if (index > this.values.length - 1) index = this.values.length - 1;
19151 return index;
19152};
19153
19154Slider.prototype.indexToLeft = function (index) {
19155 var width = parseFloat(this.frame.bar.style.width) - this.frame.slide.clientWidth - 10;
19156 var x = index / (this.values.length - 1) * width;
19157 var left = x + 3;
19158 return left;
19159};
19160
19161Slider.prototype._onMouseMove = function (event) {
19162 var diff = event.clientX - this.startClientX;
19163 var x = this.startSlideX + diff;
19164 var index = this.leftToIndex(x);
19165 this.setIndex(index);
19166 util.preventDefault();
19167};
19168
19169Slider.prototype._onMouseUp = function (event) {
19170 // eslint-disable-line no-unused-vars
19171 this.frame.style.cursor = 'auto'; // remove event listeners
19172
19173 util.removeEventListener(document, 'mousemove', this.onmousemove);
19174 util.removeEventListener(document, 'mouseup', this.onmouseup);
19175 util.preventDefault();
19176};
19177
19178var Slider_1 = Slider;
19179
19180/**
19181 * @prototype StepNumber
19182 * The class StepNumber is an iterator for Numbers. You provide a start and end
19183 * value, and a best step size. StepNumber itself rounds to fixed values and
19184 * a finds the step that best fits the provided step.
19185 *
19186 * If prettyStep is true, the step size is chosen as close as possible to the
19187 * provided step, but being a round value like 1, 2, 5, 10, 20, 50, ....
19188 *
19189 * Example usage:
19190 * var step = new StepNumber(0, 10, 2.5, true);
19191 * step.start();
19192 * while (!step.end()) {
19193 * alert(step.getCurrent());
19194 * step.next();
19195 * }
19196 *
19197 * Version: 1.0
19198 *
19199 * @param {number} start The start value
19200 * @param {number} end The end value
19201 * @param {number} step Optional. Step size. Must be a positive value.
19202 * @param {boolean} prettyStep Optional. If true, the step size is rounded
19203 * To a pretty step size (like 1, 2, 5, 10, 20, 50, ...)
19204 */
19205function StepNumber(start, end, step, prettyStep) {
19206 // set default values
19207 this._start = 0;
19208 this._end = 0;
19209 this._step = 1;
19210 this.prettyStep = true;
19211 this.precision = 5;
19212 this._current = 0;
19213 this.setRange(start, end, step, prettyStep);
19214}
19215/**
19216 * Check for input values, to prevent disasters from happening
19217 *
19218 * Source: http://stackoverflow.com/a/1830844
19219 *
19220 * @param {string} n
19221 * @returns {boolean}
19222 */
19223
19224
19225StepNumber.prototype.isNumeric = function (n) {
19226 return !isNaN(parseFloat(n)) && isFinite(n);
19227};
19228/**
19229 * Set a new range: start, end and step.
19230 *
19231 * @param {number} start The start value
19232 * @param {number} end The end value
19233 * @param {number} step Optional. Step size. Must be a positive value.
19234 * @param {boolean} prettyStep Optional. If true, the step size is rounded
19235 * To a pretty step size (like 1, 2, 5, 10, 20, 50, ...)
19236 */
19237
19238
19239StepNumber.prototype.setRange = function (start, end, step, prettyStep) {
19240 if (!this.isNumeric(start)) {
19241 throw new Error('Parameter \'start\' is not numeric; value: ' + start);
19242 }
19243
19244 if (!this.isNumeric(end)) {
19245 throw new Error('Parameter \'end\' is not numeric; value: ' + start);
19246 }
19247
19248 if (!this.isNumeric(step)) {
19249 throw new Error('Parameter \'step\' is not numeric; value: ' + start);
19250 }
19251
19252 this._start = start ? start : 0;
19253 this._end = end ? end : 0;
19254 this.setStep(step, prettyStep);
19255};
19256/**
19257 * Set a new step size
19258 * @param {number} step New step size. Must be a positive value
19259 * @param {boolean} prettyStep Optional. If true, the provided step is rounded
19260 * to a pretty step size (like 1, 2, 5, 10, 20, 50, ...)
19261 */
19262
19263
19264StepNumber.prototype.setStep = function (step, prettyStep) {
19265 if (step === undefined || step <= 0) return;
19266 if (prettyStep !== undefined) this.prettyStep = prettyStep;
19267 if (this.prettyStep === true) this._step = StepNumber.calculatePrettyStep(step);else this._step = step;
19268};
19269/**
19270 * Calculate a nice step size, closest to the desired step size.
19271 * Returns a value in one of the ranges 1*10^n, 2*10^n, or 5*10^n, where n is an
19272 * integer Number. For example 1, 2, 5, 10, 20, 50, etc...
19273 * @param {number} step Desired step size
19274 * @return {number} Nice step size
19275 */
19276
19277
19278StepNumber.calculatePrettyStep = function (step) {
19279 var log10 = function log10(x) {
19280 return Math.log(x) / Math.LN10;
19281 }; // try three steps (multiple of 1, 2, or 5
19282
19283
19284 var step1 = Math.pow(10, Math.round(log10(step))),
19285 step2 = 2 * Math.pow(10, Math.round(log10(step / 2))),
19286 step5 = 5 * Math.pow(10, Math.round(log10(step / 5))); // choose the best step (closest to minimum step)
19287
19288 var prettyStep = step1;
19289 if (Math.abs(step2 - step) <= Math.abs(prettyStep - step)) prettyStep = step2;
19290 if (Math.abs(step5 - step) <= Math.abs(prettyStep - step)) prettyStep = step5; // for safety
19291
19292 if (prettyStep <= 0) {
19293 prettyStep = 1;
19294 }
19295
19296 return prettyStep;
19297};
19298/**
19299 * returns the current value of the step
19300 * @return {number} current value
19301 */
19302
19303
19304StepNumber.prototype.getCurrent = function () {
19305 return parseFloat(this._current.toPrecision(this.precision));
19306};
19307/**
19308 * returns the current step size
19309 * @return {number} current step size
19310 */
19311
19312
19313StepNumber.prototype.getStep = function () {
19314 return this._step;
19315};
19316/**
19317 * Set the current to its starting value.
19318 *
19319 * By default, this will be the largest value smaller than start, which
19320 * is a multiple of the step size.
19321 *
19322 * Parameters checkFirst is optional, default false.
19323 * If set to true, move the current value one step if smaller than start.
19324 *
19325 * @param {boolean} [checkFirst=false]
19326 */
19327
19328
19329StepNumber.prototype.start = function (checkFirst) {
19330 if (checkFirst === undefined) {
19331 checkFirst = false;
19332 }
19333
19334 this._current = this._start - this._start % this._step;
19335
19336 if (checkFirst) {
19337 if (this.getCurrent() < this._start) {
19338 this.next();
19339 }
19340 }
19341};
19342/**
19343 * Do a step, add the step size to the current value
19344 */
19345
19346
19347StepNumber.prototype.next = function () {
19348 this._current += this._step;
19349};
19350/**
19351 * Returns true whether the end is reached
19352 * @return {boolean} True if the current value has passed the end value.
19353 */
19354
19355
19356StepNumber.prototype.end = function () {
19357 return this._current > this._end;
19358};
19359
19360var StepNumber_1 = StepNumber;
19361
19362/**
19363 * The camera is mounted on a (virtual) camera arm. The camera arm can rotate
19364 * The camera is always looking in the direction of the origin of the arm.
19365 * This way, the camera always rotates around one fixed point, the location
19366 * of the camera arm.
19367 *
19368 * Documentation:
19369 * http://en.wikipedia.org/wiki/3D_projection
19370 * @class Camera
19371 */
19372
19373function Camera() {
19374 this.armLocation = new Point3d_1();
19375 this.armRotation = {};
19376 this.armRotation.horizontal = 0;
19377 this.armRotation.vertical = 0;
19378 this.armLength = 1.7;
19379 this.cameraOffset = new Point3d_1();
19380 this.offsetMultiplier = 0.6;
19381 this.cameraLocation = new Point3d_1();
19382 this.cameraRotation = new Point3d_1(0.5 * Math.PI, 0, 0);
19383 this.calculateCameraOrientation();
19384}
19385/**
19386 * Set offset camera in camera coordinates
19387 * @param {number} x offset by camera horisontal
19388 * @param {number} y offset by camera vertical
19389 */
19390
19391
19392Camera.prototype.setOffset = function (x, y) {
19393 var abs = Math.abs,
19394 sign = Math.sign,
19395 mul = this.offsetMultiplier,
19396 border = this.armLength * mul;
19397
19398 if (abs(x) > border) {
19399 x = sign(x) * border;
19400 }
19401
19402 if (abs(y) > border) {
19403 y = sign(y) * border;
19404 }
19405
19406 this.cameraOffset.x = x;
19407 this.cameraOffset.y = y;
19408 this.calculateCameraOrientation();
19409};
19410/**
19411 * Get camera offset by horizontal and vertical
19412 * @returns {number}
19413 */
19414
19415
19416Camera.prototype.getOffset = function () {
19417 return this.cameraOffset;
19418};
19419/**
19420 * Set the location (origin) of the arm
19421 * @param {number} x Normalized value of x
19422 * @param {number} y Normalized value of y
19423 * @param {number} z Normalized value of z
19424 */
19425
19426
19427Camera.prototype.setArmLocation = function (x, y, z) {
19428 this.armLocation.x = x;
19429 this.armLocation.y = y;
19430 this.armLocation.z = z;
19431 this.calculateCameraOrientation();
19432};
19433/**
19434 * Set the rotation of the camera arm
19435 * @param {number} horizontal The horizontal rotation, between 0 and 2*PI.
19436 * Optional, can be left undefined.
19437 * @param {number} vertical The vertical rotation, between 0 and 0.5*PI
19438 * if vertical=0.5*PI, the graph is shown from the
19439 * top. Optional, can be left undefined.
19440 */
19441
19442
19443Camera.prototype.setArmRotation = function (horizontal, vertical) {
19444 if (horizontal !== undefined) {
19445 this.armRotation.horizontal = horizontal;
19446 }
19447
19448 if (vertical !== undefined) {
19449 this.armRotation.vertical = vertical;
19450 if (this.armRotation.vertical < 0) this.armRotation.vertical = 0;
19451 if (this.armRotation.vertical > 0.5 * Math.PI) this.armRotation.vertical = 0.5 * Math.PI;
19452 }
19453
19454 if (horizontal !== undefined || vertical !== undefined) {
19455 this.calculateCameraOrientation();
19456 }
19457};
19458/**
19459 * Retrieve the current arm rotation
19460 * @return {object} An object with parameters horizontal and vertical
19461 */
19462
19463
19464Camera.prototype.getArmRotation = function () {
19465 var rot = {};
19466 rot.horizontal = this.armRotation.horizontal;
19467 rot.vertical = this.armRotation.vertical;
19468 return rot;
19469};
19470/**
19471 * Set the (normalized) length of the camera arm.
19472 * @param {number} length A length between 0.71 and 5.0
19473 */
19474
19475
19476Camera.prototype.setArmLength = function (length) {
19477 if (length === undefined) return;
19478 this.armLength = length; // Radius must be larger than the corner of the graph,
19479 // which has a distance of sqrt(0.5^2+0.5^2) = 0.71 from the center of the
19480 // graph
19481
19482 if (this.armLength < 0.71) this.armLength = 0.71;
19483 if (this.armLength > 5.0) this.armLength = 5.0;
19484 this.setOffset(this.cameraOffset.x, this.cameraOffset.y);
19485 this.calculateCameraOrientation();
19486};
19487/**
19488 * Retrieve the arm length
19489 * @return {number} length
19490 */
19491
19492
19493Camera.prototype.getArmLength = function () {
19494 return this.armLength;
19495};
19496/**
19497 * Retrieve the camera location
19498 * @return {Point3d} cameraLocation
19499 */
19500
19501
19502Camera.prototype.getCameraLocation = function () {
19503 return this.cameraLocation;
19504};
19505/**
19506 * Retrieve the camera rotation
19507 * @return {Point3d} cameraRotation
19508 */
19509
19510
19511Camera.prototype.getCameraRotation = function () {
19512 return this.cameraRotation;
19513};
19514/**
19515 * Calculate the location and rotation of the camera based on the
19516 * position and orientation of the camera arm
19517 */
19518
19519
19520Camera.prototype.calculateCameraOrientation = function () {
19521 // calculate location of the camera
19522 this.cameraLocation.x = this.armLocation.x - this.armLength * Math.sin(this.armRotation.horizontal) * Math.cos(this.armRotation.vertical);
19523 this.cameraLocation.y = this.armLocation.y - this.armLength * Math.cos(this.armRotation.horizontal) * Math.cos(this.armRotation.vertical);
19524 this.cameraLocation.z = this.armLocation.z + this.armLength * Math.sin(this.armRotation.vertical); // calculate rotation of the camera
19525
19526 this.cameraRotation.x = Math.PI / 2 - this.armRotation.vertical;
19527 this.cameraRotation.y = 0;
19528 this.cameraRotation.z = -this.armRotation.horizontal;
19529 var xa = this.cameraRotation.x;
19530 var za = this.cameraRotation.z;
19531 var dx = this.cameraOffset.x;
19532 var dy = this.cameraOffset.y;
19533 var sin = Math.sin,
19534 cos = Math.cos;
19535 this.cameraLocation.x = this.cameraLocation.x + dx * cos(za) + dy * -sin(za) * cos(xa);
19536 this.cameraLocation.y = this.cameraLocation.y + dx * sin(za) + dy * cos(za) * cos(xa);
19537 this.cameraLocation.z = this.cameraLocation.z + dy * sin(xa);
19538};
19539
19540var Camera_1 = Camera;
19541
19542// This modules handles the options for Graph3d.
19543//
19544////////////////////////////////////////////////////////////////////////////////
19545// enumerate the available styles
19546
19547var STYLE = {
19548 BAR: 0,
19549 BARCOLOR: 1,
19550 BARSIZE: 2,
19551 DOT: 3,
19552 DOTLINE: 4,
19553 DOTCOLOR: 5,
19554 DOTSIZE: 6,
19555 GRID: 7,
19556 LINE: 8,
19557 SURFACE: 9
19558}; // The string representations of the styles
19559
19560var STYLENAME = {
19561 'dot': STYLE.DOT,
19562 'dot-line': STYLE.DOTLINE,
19563 'dot-color': STYLE.DOTCOLOR,
19564 'dot-size': STYLE.DOTSIZE,
19565 'line': STYLE.LINE,
19566 'grid': STYLE.GRID,
19567 'surface': STYLE.SURFACE,
19568 'bar': STYLE.BAR,
19569 'bar-color': STYLE.BARCOLOR,
19570 'bar-size': STYLE.BARSIZE
19571};
19572/**
19573 * Field names in the options hash which are of relevance to the user.
19574 *
19575 * Specifically, these are the fields which require no special handling,
19576 * and can be directly copied over.
19577 */
19578
19579var OPTIONKEYS = ['width', 'height', 'filterLabel', 'legendLabel', 'xLabel', 'yLabel', 'zLabel', 'xValueLabel', 'yValueLabel', 'zValueLabel', 'showXAxis', 'showYAxis', 'showZAxis', 'showGrid', 'showPerspective', 'showShadow', 'keepAspectRatio', 'rotateAxisLabels', 'verticalRatio', 'dotSizeRatio', 'dotSizeMinFraction', 'dotSizeMaxFraction', 'showAnimationControls', 'animationInterval', 'animationPreload', 'animationAutoStart', 'axisColor', 'axisFontSize', 'axisFontType', 'gridColor', 'xCenter', 'yCenter', 'zoomable', 'tooltipDelay', 'ctrlToZoom'];
19580/**
19581 * Field names in the options hash which are of relevance to the user.
19582 *
19583 * Same as OPTIONKEYS, but internally these fields are stored with
19584 * prefix 'default' in the name.
19585 */
19586
19587var PREFIXEDOPTIONKEYS = ['xBarWidth', 'yBarWidth', 'valueMin', 'valueMax', 'xMin', 'xMax', 'xStep', 'yMin', 'yMax', 'yStep', 'zMin', 'zMax', 'zStep']; // Placeholder for DEFAULTS reference
19588
19589var DEFAULTS = undefined;
19590/**
19591 * Check if given hash is empty.
19592 *
19593 * Source: http://stackoverflow.com/a/679937
19594 *
19595 * @param {object} obj
19596 * @returns {boolean}
19597 */
19598
19599function isEmpty(obj) {
19600 for (var prop in obj) {
19601 if (obj.hasOwnProperty(prop)) return false;
19602 }
19603
19604 return true;
19605}
19606/**
19607 * Make first letter of parameter upper case.
19608 *
19609 * Source: http://stackoverflow.com/a/1026087
19610 *
19611 * @param {string} str
19612 * @returns {string}
19613 */
19614
19615
19616function capitalize(str) {
19617 if (str === undefined || str === "" || typeof str != "string") {
19618 return str;
19619 }
19620
19621 return str.charAt(0).toUpperCase() + str.slice(1);
19622}
19623/**
19624 * Add a prefix to a field name, taking style guide into account
19625 *
19626 * @param {string} prefix
19627 * @param {string} fieldName
19628 * @returns {string}
19629 */
19630
19631
19632function prefixFieldName(prefix, fieldName) {
19633 if (prefix === undefined || prefix === "") {
19634 return fieldName;
19635 }
19636
19637 return prefix + capitalize(fieldName);
19638}
19639/**
19640 * Forcibly copy fields from src to dst in a controlled manner.
19641 *
19642 * A given field in dst will always be overwitten. If this field
19643 * is undefined or not present in src, the field in dst will
19644 * be explicitly set to undefined.
19645 *
19646 * The intention here is to be able to reset all option fields.
19647 *
19648 * Only the fields mentioned in array 'fields' will be handled.
19649 *
19650 * @param {object} src
19651 * @param {object} dst
19652 * @param {array<string>} fields array with names of fields to copy
19653 * @param {string} [prefix] prefix to use for the target fields.
19654 */
19655
19656
19657function forceCopy(src, dst, fields, prefix) {
19658 var srcKey;
19659 var dstKey;
19660
19661 for (var i = 0; i < fields.length; ++i) {
19662 srcKey = fields[i];
19663 dstKey = prefixFieldName(prefix, srcKey);
19664 dst[dstKey] = src[srcKey];
19665 }
19666}
19667/**
19668 * Copy fields from src to dst in a safe and controlled manner.
19669 *
19670 * Only the fields mentioned in array 'fields' will be copied over,
19671 * and only if these are actually defined.
19672 *
19673 * @param {object} src
19674 * @param {object} dst
19675 * @param {array<string>} fields array with names of fields to copy
19676 * @param {string} [prefix] prefix to use for the target fields.
19677 */
19678
19679
19680function safeCopy(src, dst, fields, prefix) {
19681 var srcKey;
19682 var dstKey;
19683
19684 for (var i = 0; i < fields.length; ++i) {
19685 srcKey = fields[i];
19686 if (src[srcKey] === undefined) continue;
19687 dstKey = prefixFieldName(prefix, srcKey);
19688 dst[dstKey] = src[srcKey];
19689 }
19690}
19691/**
19692 * Initialize dst with the values in src.
19693 *
19694 * src is the hash with the default values.
19695 * A reference DEFAULTS to this hash is stored locally for
19696 * further handling.
19697 *
19698 * For now, dst is assumed to be a Graph3d instance.
19699 * @param {object} src
19700 * @param {object} dst
19701 */
19702
19703
19704function setDefaults(src, dst) {
19705 if (src === undefined || isEmpty(src)) {
19706 throw new Error('No DEFAULTS passed');
19707 }
19708
19709 if (dst === undefined) {
19710 throw new Error('No dst passed');
19711 } // Remember defaults for future reference
19712
19713
19714 DEFAULTS = src; // Handle the defaults which can be simply copied over
19715
19716 forceCopy(src, dst, OPTIONKEYS);
19717 forceCopy(src, dst, PREFIXEDOPTIONKEYS, 'default'); // Handle the more complex ('special') fields
19718
19719 setSpecialSettings(src, dst); // Following are internal fields, not part of the user settings
19720
19721 dst.margin = 10; // px
19722
19723 dst.showGrayBottom = false; // TODO: this does not work correctly
19724
19725 dst.showTooltip = false;
19726 dst.onclick_callback = null;
19727 dst.eye = new Point3d_1(0, 0, -1); // TODO: set eye.z about 3/4 of the width of the window?
19728}
19729/**
19730 *
19731 * @param {object} options
19732 * @param {object} dst
19733 */
19734
19735
19736function setOptions(options, dst) {
19737 if (options === undefined) {
19738 return;
19739 }
19740
19741 if (dst === undefined) {
19742 throw new Error('No dst passed');
19743 }
19744
19745 if (DEFAULTS === undefined || isEmpty(DEFAULTS)) {
19746 throw new Error('DEFAULTS not set for module Settings');
19747 } // Handle the parameters which can be simply copied over
19748
19749
19750 safeCopy(options, dst, OPTIONKEYS);
19751 safeCopy(options, dst, PREFIXEDOPTIONKEYS, 'default'); // Handle the more complex ('special') fields
19752
19753 setSpecialSettings(options, dst);
19754}
19755/**
19756 * Special handling for certain parameters
19757 *
19758 * 'Special' here means: setting requires more than a simple copy
19759 *
19760 * @param {object} src
19761 * @param {object} dst
19762 */
19763
19764
19765function setSpecialSettings(src, dst) {
19766 if (src.backgroundColor !== undefined) {
19767 setBackgroundColor(src.backgroundColor, dst);
19768 }
19769
19770 setDataColor(src.dataColor, dst);
19771 setStyle(src.style, dst);
19772 setShowLegend(src.showLegend, dst);
19773 setCameraPosition(src.cameraPosition, dst); // As special fields go, this is an easy one; just a translation of the name.
19774 // Can't use this.tooltip directly, because that field exists internally
19775
19776 if (src.tooltip !== undefined) {
19777 dst.showTooltip = src.tooltip;
19778 }
19779
19780 if (src.onclick != undefined) {
19781 dst.onclick_callback = src.onclick;
19782 }
19783
19784 if (src.tooltipStyle !== undefined) {
19785 util.selectiveDeepExtend(['tooltipStyle'], dst, src);
19786 }
19787}
19788/**
19789 * Set the value of setting 'showLegend'
19790 *
19791 * This depends on the value of the style fields, so it must be called
19792 * after the style field has been initialized.
19793 *
19794 * @param {boolean} showLegend
19795 * @param {object} dst
19796 */
19797
19798
19799function setShowLegend(showLegend, dst) {
19800 if (showLegend === undefined) {
19801 // If the default was auto, make a choice for this field
19802 var isAutoByDefault = DEFAULTS.showLegend === undefined;
19803
19804 if (isAutoByDefault) {
19805 // these styles default to having legends
19806 var isLegendGraphStyle = dst.style === STYLE.DOTCOLOR || dst.style === STYLE.DOTSIZE;
19807 dst.showLegend = isLegendGraphStyle;
19808 }
19809 } else {
19810 dst.showLegend = showLegend;
19811 }
19812}
19813/**
19814 * Retrieve the style index from given styleName
19815 * @param {string} styleName Style name such as 'dot', 'grid', 'dot-line'
19816 * @return {number} styleNumber Enumeration value representing the style, or -1
19817 * when not found
19818 */
19819
19820
19821function getStyleNumberByName(styleName) {
19822 var number = STYLENAME[styleName];
19823
19824 if (number === undefined) {
19825 return -1;
19826 }
19827
19828 return number;
19829}
19830/**
19831 * Check if given number is a valid style number.
19832 *
19833 * @param {string | number} style
19834 * @return {boolean} true if valid, false otherwise
19835 */
19836
19837
19838function checkStyleNumber(style) {
19839 var valid = false;
19840
19841 for (var n in STYLE) {
19842 if (STYLE[n] === style) {
19843 valid = true;
19844 break;
19845 }
19846 }
19847
19848 return valid;
19849}
19850/**
19851 *
19852 * @param {string | number} style
19853 * @param {Object} dst
19854 */
19855
19856
19857function setStyle(style, dst) {
19858 if (style === undefined) {
19859 return; // Nothing to do
19860 }
19861
19862 var styleNumber;
19863
19864 if (typeof style === 'string') {
19865 styleNumber = getStyleNumberByName(style);
19866
19867 if (styleNumber === -1) {
19868 throw new Error('Style \'' + style + '\' is invalid');
19869 }
19870 } else {
19871 // Do a pedantic check on style number value
19872 if (!checkStyleNumber(style)) {
19873 throw new Error('Style \'' + style + '\' is invalid');
19874 }
19875
19876 styleNumber = style;
19877 }
19878
19879 dst.style = styleNumber;
19880}
19881/**
19882 * Set the background styling for the graph
19883 * @param {string | {fill: string, stroke: string, strokeWidth: string}} backgroundColor
19884 * @param {Object} dst
19885 */
19886
19887
19888function setBackgroundColor(backgroundColor, dst) {
19889 var fill = 'white';
19890 var stroke = 'gray';
19891 var strokeWidth = 1;
19892
19893 if (typeof backgroundColor === 'string') {
19894 fill = backgroundColor;
19895 stroke = 'none';
19896 strokeWidth = 0;
19897 } else if (_typeof$1(backgroundColor) === 'object') {
19898 if (backgroundColor.fill !== undefined) fill = backgroundColor.fill;
19899 if (backgroundColor.stroke !== undefined) stroke = backgroundColor.stroke;
19900 if (backgroundColor.strokeWidth !== undefined) strokeWidth = backgroundColor.strokeWidth;
19901 } else {
19902 throw new Error('Unsupported type of backgroundColor');
19903 }
19904
19905 dst.frame.style.backgroundColor = fill;
19906 dst.frame.style.borderColor = stroke;
19907 dst.frame.style.borderWidth = strokeWidth + 'px';
19908 dst.frame.style.borderStyle = 'solid';
19909}
19910/**
19911 *
19912 * @param {string | Object} dataColor
19913 * @param {Object} dst
19914 */
19915
19916
19917function setDataColor(dataColor, dst) {
19918 if (dataColor === undefined) {
19919 return; // Nothing to do
19920 }
19921
19922 if (dst.dataColor === undefined) {
19923 dst.dataColor = {};
19924 }
19925
19926 if (typeof dataColor === 'string') {
19927 dst.dataColor.fill = dataColor;
19928 dst.dataColor.stroke = dataColor;
19929 } else {
19930 if (dataColor.fill) {
19931 dst.dataColor.fill = dataColor.fill;
19932 }
19933
19934 if (dataColor.stroke) {
19935 dst.dataColor.stroke = dataColor.stroke;
19936 }
19937
19938 if (dataColor.strokeWidth !== undefined) {
19939 dst.dataColor.strokeWidth = dataColor.strokeWidth;
19940 }
19941 }
19942}
19943/**
19944 *
19945 * @param {Object} cameraPosition
19946 * @param {Object} dst
19947 */
19948
19949
19950function setCameraPosition(cameraPosition, dst) {
19951 var camPos = cameraPosition;
19952
19953 if (camPos === undefined) {
19954 return;
19955 }
19956
19957 if (dst.camera === undefined) {
19958 dst.camera = new Camera_1();
19959 }
19960
19961 dst.camera.setArmRotation(camPos.horizontal, camPos.vertical);
19962 dst.camera.setArmLength(camPos.distance);
19963}
19964
19965var STYLE_1 = STYLE;
19966var setDefaults_1 = setDefaults;
19967var setOptions_1 = setOptions;
19968var setCameraPosition_1 = setCameraPosition;
19969var Settings = {
19970 STYLE: STYLE_1,
19971 setDefaults: setDefaults_1,
19972 setOptions: setOptions_1,
19973 setCameraPosition: setCameraPosition_1
19974};
19975
19976var errorFound = false;
19977var allOptions;
19978var printStyle = 'background: #FFeeee; color: #dd0000';
19979/**
19980 * Used to validate options.
19981 */
19982
19983var Validator =
19984/*#__PURE__*/
19985function () {
19986 /**
19987 * @ignore
19988 */
19989 function Validator() {
19990 _classCallCheck$1(this, Validator);
19991 }
19992 /**
19993 * Main function to be called
19994 * @param {Object} options
19995 * @param {Object} referenceOptions
19996 * @param {Object} subObject
19997 * @returns {boolean}
19998 * @static
19999 */
20000
20001
20002 _createClass$1(Validator, null, [{
20003 key: "validate",
20004 value: function validate(options, referenceOptions, subObject) {
20005 errorFound = false;
20006 allOptions = referenceOptions;
20007 var usedOptions = referenceOptions;
20008
20009 if (subObject !== undefined) {
20010 usedOptions = referenceOptions[subObject];
20011 }
20012
20013 Validator.parse(options, usedOptions, []);
20014 return errorFound;
20015 }
20016 /**
20017 * Will traverse an object recursively and check every value
20018 * @param {Object} options
20019 * @param {Object} referenceOptions
20020 * @param {array} path | where to look for the actual option
20021 * @static
20022 */
20023
20024 }, {
20025 key: "parse",
20026 value: function parse(options, referenceOptions, path) {
20027 for (var option in options) {
20028 if (options.hasOwnProperty(option)) {
20029 Validator.check(option, options, referenceOptions, path);
20030 }
20031 }
20032 }
20033 /**
20034 * Check every value. If the value is an object, call the parse function on that object.
20035 * @param {string} option
20036 * @param {Object} options
20037 * @param {Object} referenceOptions
20038 * @param {array} path | where to look for the actual option
20039 * @static
20040 */
20041
20042 }, {
20043 key: "check",
20044 value: function check(option, options, referenceOptions, path) {
20045 if (referenceOptions[option] === undefined && referenceOptions.__any__ === undefined) {
20046 Validator.getSuggestion(option, referenceOptions, path);
20047 return;
20048 }
20049
20050 var referenceOption = option;
20051 var is_object = true;
20052
20053 if (referenceOptions[option] === undefined && referenceOptions.__any__ !== undefined) {
20054 // NOTE: This only triggers if the __any__ is in the top level of the options object.
20055 // THAT'S A REALLY BAD PLACE TO ALLOW IT!!!!
20056 // TODO: Examine if needed, remove if possible
20057 // __any__ is a wildcard. Any value is accepted and will be further analysed by reference.
20058 referenceOption = '__any__'; // if the any-subgroup is not a predefined object in the configurator,
20059 // we do not look deeper into the object.
20060
20061 is_object = Validator.getType(options[option]) === 'object';
20062 }
20063
20064 var refOptionObj = referenceOptions[referenceOption];
20065
20066 if (is_object && refOptionObj.__type__ !== undefined) {
20067 refOptionObj = refOptionObj.__type__;
20068 }
20069
20070 Validator.checkFields(option, options, referenceOptions, referenceOption, refOptionObj, path);
20071 }
20072 /**
20073 *
20074 * @param {string} option | the option property
20075 * @param {Object} options | The supplied options object
20076 * @param {Object} referenceOptions | The reference options containing all options and their allowed formats
20077 * @param {string} referenceOption | Usually this is the same as option, except when handling an __any__ tag.
20078 * @param {string} refOptionObj | This is the type object from the reference options
20079 * @param {Array} path | where in the object is the option
20080 * @static
20081 */
20082
20083 }, {
20084 key: "checkFields",
20085 value: function checkFields(option, options, referenceOptions, referenceOption, refOptionObj, path) {
20086 var log = function log(message) {
20087 console.log('%c' + message + Validator.printLocation(path, option), printStyle);
20088 };
20089
20090 var optionType = Validator.getType(options[option]);
20091 var refOptionType = refOptionObj[optionType];
20092
20093 if (refOptionType !== undefined) {
20094 // if the type is correct, we check if it is supposed to be one of a few select values
20095 if (Validator.getType(refOptionType) === 'array' && refOptionType.indexOf(options[option]) === -1) {
20096 log('Invalid option detected in "' + option + '".' + ' Allowed values are:' + Validator.print(refOptionType) + ' not "' + options[option] + '". ');
20097 errorFound = true;
20098 } else if (optionType === 'object' && referenceOption !== "__any__") {
20099 path = util.copyAndExtendArray(path, option);
20100 Validator.parse(options[option], referenceOptions[referenceOption], path);
20101 }
20102 } else if (refOptionObj['any'] === undefined) {
20103 // type of the field is incorrect and the field cannot be any
20104 log('Invalid type received for "' + option + '". Expected: ' + Validator.print(Object.keys(refOptionObj)) + '. Received [' + optionType + '] "' + options[option] + '"');
20105 errorFound = true;
20106 }
20107 }
20108 /**
20109 *
20110 * @param {Object|boolean|number|string|Array.<number>|Date|Node|Moment|undefined|null} object
20111 * @returns {string}
20112 * @static
20113 */
20114
20115 }, {
20116 key: "getType",
20117 value: function getType(object) {
20118 var type = _typeof$1(object);
20119
20120 if (type === 'object') {
20121 if (object === null) {
20122 return 'null';
20123 }
20124
20125 if (object instanceof Boolean) {
20126 return 'boolean';
20127 }
20128
20129 if (object instanceof Number) {
20130 return 'number';
20131 }
20132
20133 if (object instanceof String) {
20134 return 'string';
20135 }
20136
20137 if (Array.isArray(object)) {
20138 return 'array';
20139 }
20140
20141 if (object instanceof Date) {
20142 return 'date';
20143 }
20144
20145 if (object.nodeType !== undefined) {
20146 return 'dom';
20147 }
20148
20149 if (object._isAMomentObject === true) {
20150 return 'moment';
20151 }
20152
20153 return 'object';
20154 } else if (type === 'number') {
20155 return 'number';
20156 } else if (type === 'boolean') {
20157 return 'boolean';
20158 } else if (type === 'string') {
20159 return 'string';
20160 } else if (type === undefined) {
20161 return 'undefined';
20162 }
20163
20164 return type;
20165 }
20166 /**
20167 * @param {string} option
20168 * @param {Object} options
20169 * @param {Array.<string>} path
20170 * @static
20171 */
20172
20173 }, {
20174 key: "getSuggestion",
20175 value: function getSuggestion(option, options, path) {
20176 var localSearch = Validator.findInOptions(option, options, path, false);
20177 var globalSearch = Validator.findInOptions(option, allOptions, [], true);
20178 var localSearchThreshold = 8;
20179 var globalSearchThreshold = 4;
20180 var msg;
20181
20182 if (localSearch.indexMatch !== undefined) {
20183 msg = ' in ' + Validator.printLocation(localSearch.path, option, '') + 'Perhaps it was incomplete? Did you mean: "' + localSearch.indexMatch + '"?\n\n';
20184 } else if (globalSearch.distance <= globalSearchThreshold && localSearch.distance > globalSearch.distance) {
20185 msg = ' in ' + Validator.printLocation(localSearch.path, option, '') + 'Perhaps it was misplaced? Matching option found at: ' + Validator.printLocation(globalSearch.path, globalSearch.closestMatch, '');
20186 } else if (localSearch.distance <= localSearchThreshold) {
20187 msg = '. Did you mean "' + localSearch.closestMatch + '"?' + Validator.printLocation(localSearch.path, option);
20188 } else {
20189 msg = '. Did you mean one of these: ' + Validator.print(Object.keys(options)) + Validator.printLocation(path, option);
20190 }
20191
20192 console.log('%cUnknown option detected: "' + option + '"' + msg, printStyle);
20193 errorFound = true;
20194 }
20195 /**
20196 * traverse the options in search for a match.
20197 * @param {string} option
20198 * @param {Object} options
20199 * @param {Array} path | where to look for the actual option
20200 * @param {boolean} [recursive=false]
20201 * @returns {{closestMatch: string, path: Array, distance: number}}
20202 * @static
20203 */
20204
20205 }, {
20206 key: "findInOptions",
20207 value: function findInOptions(option, options, path) {
20208 var recursive = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
20209 var min = 1e9;
20210 var closestMatch = '';
20211 var closestMatchPath = [];
20212 var lowerCaseOption = option.toLowerCase();
20213 var indexMatch = undefined;
20214
20215 for (var op in options) {
20216 // eslint-disable-line guard-for-in
20217 var distance = void 0;
20218
20219 if (options[op].__type__ !== undefined && recursive === true) {
20220 var result = Validator.findInOptions(option, options[op], util.copyAndExtendArray(path, op));
20221
20222 if (min > result.distance) {
20223 closestMatch = result.closestMatch;
20224 closestMatchPath = result.path;
20225 min = result.distance;
20226 indexMatch = result.indexMatch;
20227 }
20228 } else {
20229 if (op.toLowerCase().indexOf(lowerCaseOption) !== -1) {
20230 indexMatch = op;
20231 }
20232
20233 distance = Validator.levenshteinDistance(option, op);
20234
20235 if (min > distance) {
20236 closestMatch = op;
20237 closestMatchPath = util.copyArray(path);
20238 min = distance;
20239 }
20240 }
20241 }
20242
20243 return {
20244 closestMatch: closestMatch,
20245 path: closestMatchPath,
20246 distance: min,
20247 indexMatch: indexMatch
20248 };
20249 }
20250 /**
20251 * @param {Array.<string>} path
20252 * @param {Object} option
20253 * @param {string} prefix
20254 * @returns {String}
20255 * @static
20256 */
20257
20258 }, {
20259 key: "printLocation",
20260 value: function printLocation(path, option) {
20261 var prefix = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'Problem value found at: \n';
20262 var str = '\n\n' + prefix + 'options = {\n';
20263
20264 for (var i = 0; i < path.length; i++) {
20265 for (var j = 0; j < i + 1; j++) {
20266 str += ' ';
20267 }
20268
20269 str += path[i] + ': {\n';
20270 }
20271
20272 for (var _j = 0; _j < path.length + 1; _j++) {
20273 str += ' ';
20274 }
20275
20276 str += option + '\n';
20277
20278 for (var _i = 0; _i < path.length + 1; _i++) {
20279 for (var _j2 = 0; _j2 < path.length - _i; _j2++) {
20280 str += ' ';
20281 }
20282
20283 str += '}\n';
20284 }
20285
20286 return str + '\n\n';
20287 }
20288 /**
20289 * @param {Object} options
20290 * @returns {String}
20291 * @static
20292 */
20293
20294 }, {
20295 key: "print",
20296 value: function print(options) {
20297 return JSON.stringify(options).replace(/(\")|(\[)|(\])|(,"__type__")/g, "").replace(/(\,)/g, ', ');
20298 }
20299 /**
20300 * Compute the edit distance between the two given strings
20301 * http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#JavaScript
20302 *
20303 * Copyright (c) 2011 Andrei Mackenzie
20304 *
20305 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
20306 *
20307 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
20308 *
20309 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
20310 *
20311 * @param {string} a
20312 * @param {string} b
20313 * @returns {Array.<Array.<number>>}}
20314 * @static
20315 */
20316
20317 }, {
20318 key: "levenshteinDistance",
20319 value: function levenshteinDistance(a, b) {
20320 if (a.length === 0) return b.length;
20321 if (b.length === 0) return a.length;
20322 var matrix = []; // increment along the first column of each row
20323
20324 var i;
20325
20326 for (i = 0; i <= b.length; i++) {
20327 matrix[i] = [i];
20328 } // increment each column in the first row
20329
20330
20331 var j;
20332
20333 for (j = 0; j <= a.length; j++) {
20334 matrix[0][j] = j;
20335 } // Fill in the rest of the matrix
20336
20337
20338 for (i = 1; i <= b.length; i++) {
20339 for (j = 1; j <= a.length; j++) {
20340 if (b.charAt(i - 1) == a.charAt(j - 1)) {
20341 matrix[i][j] = matrix[i - 1][j - 1];
20342 } else {
20343 matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, // substitution
20344 Math.min(matrix[i][j - 1] + 1, // insertion
20345 matrix[i - 1][j] + 1)); // deletion
20346 }
20347 }
20348 }
20349
20350 return matrix[b.length][a.length];
20351 }
20352 }]);
20353
20354 return Validator;
20355}();
20356
20357var Validator$1 = /*#__PURE__*/Object.freeze({
20358 Validator: Validator,
20359 printStyle: printStyle
20360});
20361
20362/**
20363 * This object contains all possible options. It will check if the types are correct, if required if the option is one
20364 * of the allowed values.
20365 *
20366 * __any__ means that the name of the property does not matter.
20367 * __type__ is a required field for all objects and contains the allowed types of all objects
20368 */
20369var string = 'string';
20370var bool = 'boolean';
20371var number = 'number';
20372var object = 'object'; // should only be in a __type__ property
20373// Following not used here, but useful for reference
20374//let array = 'array';
20375//let dom = 'dom';
20376//let any = 'any';
20377
20378var colorOptions = {
20379 fill: {
20380 string: string
20381 },
20382 stroke: {
20383 string: string
20384 },
20385 strokeWidth: {
20386 number: number
20387 },
20388 __type__: {
20389 string: string,
20390 object: object,
20391 'undefined': 'undefined'
20392 }
20393};
20394/**
20395 * Order attempted to be alphabetical.
20396 * - x/y/z-prefixes ignored in sorting
20397 * - __type__ always at end
20398 * - globals at end
20399 */
20400
20401var allOptions$1 = {
20402 animationAutoStart: {
20403 boolean: bool,
20404 'undefined': 'undefined'
20405 },
20406 animationInterval: {
20407 number: number
20408 },
20409 animationPreload: {
20410 boolean: bool
20411 },
20412 axisColor: {
20413 string: string
20414 },
20415 axisFontSize: {
20416 number: number
20417 },
20418 axisFontType: {
20419 string: string
20420 },
20421 backgroundColor: colorOptions,
20422 xBarWidth: {
20423 number: number,
20424 'undefined': 'undefined'
20425 },
20426 yBarWidth: {
20427 number: number,
20428 'undefined': 'undefined'
20429 },
20430 cameraPosition: {
20431 distance: {
20432 number: number
20433 },
20434 horizontal: {
20435 number: number
20436 },
20437 vertical: {
20438 number: number
20439 },
20440 __type__: {
20441 object: object
20442 }
20443 },
20444 zoomable: {
20445 boolean: bool
20446 },
20447 ctrlToZoom: {
20448 boolean: bool
20449 },
20450 xCenter: {
20451 string: string
20452 },
20453 yCenter: {
20454 string: string
20455 },
20456 dataColor: colorOptions,
20457 dotSizeMinFraction: {
20458 number: number
20459 },
20460 dotSizeMaxFraction: {
20461 number: number
20462 },
20463 dotSizeRatio: {
20464 number: number
20465 },
20466 filterLabel: {
20467 string: string
20468 },
20469 gridColor: {
20470 string: string
20471 },
20472 onclick: {
20473 'function': 'function'
20474 },
20475 keepAspectRatio: {
20476 boolean: bool
20477 },
20478 xLabel: {
20479 string: string
20480 },
20481 yLabel: {
20482 string: string
20483 },
20484 zLabel: {
20485 string: string
20486 },
20487 legendLabel: {
20488 string: string
20489 },
20490 xMin: {
20491 number: number,
20492 'undefined': 'undefined'
20493 },
20494 yMin: {
20495 number: number,
20496 'undefined': 'undefined'
20497 },
20498 zMin: {
20499 number: number,
20500 'undefined': 'undefined'
20501 },
20502 xMax: {
20503 number: number,
20504 'undefined': 'undefined'
20505 },
20506 yMax: {
20507 number: number,
20508 'undefined': 'undefined'
20509 },
20510 zMax: {
20511 number: number,
20512 'undefined': 'undefined'
20513 },
20514 showAnimationControls: {
20515 boolean: bool,
20516 'undefined': 'undefined'
20517 },
20518 showGrid: {
20519 boolean: bool
20520 },
20521 showLegend: {
20522 boolean: bool,
20523 'undefined': 'undefined'
20524 },
20525 showPerspective: {
20526 boolean: bool
20527 },
20528 showShadow: {
20529 boolean: bool
20530 },
20531 showXAxis: {
20532 boolean: bool
20533 },
20534 showYAxis: {
20535 boolean: bool
20536 },
20537 showZAxis: {
20538 boolean: bool
20539 },
20540 rotateAxisLabels: {
20541 boolean: bool
20542 },
20543 xStep: {
20544 number: number,
20545 'undefined': 'undefined'
20546 },
20547 yStep: {
20548 number: number,
20549 'undefined': 'undefined'
20550 },
20551 zStep: {
20552 number: number,
20553 'undefined': 'undefined'
20554 },
20555 style: {
20556 number: number,
20557 // TODO: either Graph3d.DEFAULT has string, or number allowed in documentation
20558 string: ['bar', 'bar-color', 'bar-size', 'dot', 'dot-line', 'dot-color', 'dot-size', 'line', 'grid', 'surface']
20559 },
20560 tooltip: {
20561 boolean: bool,
20562 'function': 'function'
20563 },
20564 tooltipDelay: {
20565 number: number
20566 },
20567 tooltipStyle: {
20568 content: {
20569 color: {
20570 string: string
20571 },
20572 background: {
20573 string: string
20574 },
20575 border: {
20576 string: string
20577 },
20578 borderRadius: {
20579 string: string
20580 },
20581 boxShadow: {
20582 string: string
20583 },
20584 padding: {
20585 string: string
20586 },
20587 __type__: {
20588 object: object
20589 }
20590 },
20591 line: {
20592 borderLeft: {
20593 string: string
20594 },
20595 height: {
20596 string: string
20597 },
20598 width: {
20599 string: string
20600 },
20601 pointerEvents: {
20602 string: string
20603 },
20604 __type__: {
20605 object: object
20606 }
20607 },
20608 dot: {
20609 border: {
20610 string: string
20611 },
20612 borderRadius: {
20613 string: string
20614 },
20615 height: {
20616 string: string
20617 },
20618 width: {
20619 string: string
20620 },
20621 pointerEvents: {
20622 string: string
20623 },
20624 __type__: {
20625 object: object
20626 }
20627 },
20628 __type__: {
20629 object: object
20630 }
20631 },
20632 xValueLabel: {
20633 'function': 'function'
20634 },
20635 yValueLabel: {
20636 'function': 'function'
20637 },
20638 zValueLabel: {
20639 'function': 'function'
20640 },
20641 valueMax: {
20642 number: number,
20643 'undefined': 'undefined'
20644 },
20645 valueMin: {
20646 number: number,
20647 'undefined': 'undefined'
20648 },
20649 verticalRatio: {
20650 number: number
20651 },
20652 //globals :
20653 height: {
20654 string: string
20655 },
20656 width: {
20657 string: string
20658 },
20659 __type__: {
20660 object: object
20661 }
20662};
20663
20664var options = /*#__PURE__*/Object.freeze({
20665 allOptions: allOptions$1
20666});
20667
20668/**
20669 * @prototype Range
20670 *
20671 * Helper class to make working with related min and max values easier.
20672 *
20673 * The range is inclusive; a given value is considered part of the range if:
20674 *
20675 * this.min <= value <= this.max
20676 */
20677function Range() {
20678 this.min = undefined;
20679 this.max = undefined;
20680}
20681/**
20682 * Adjust the range so that the passed value fits in it.
20683 *
20684 * If the value is outside of the current extremes, adjust
20685 * the min or max so that the value is within the range.
20686 *
20687 * @param {number} value Numeric value to fit in range
20688 */
20689
20690
20691Range.prototype.adjust = function (value) {
20692 if (value === undefined) return;
20693
20694 if (this.min === undefined || this.min > value) {
20695 this.min = value;
20696 }
20697
20698 if (this.max === undefined || this.max < value) {
20699 this.max = value;
20700 }
20701};
20702/**
20703 * Adjust the current range so that the passed range fits in it.
20704 *
20705 * @param {Range} range Range instance to fit in current instance
20706 */
20707
20708
20709Range.prototype.combine = function (range) {
20710 this.add(range.min);
20711 this.add(range.max);
20712};
20713/**
20714 * Expand the range by the given value
20715 *
20716 * min will be lowered by given value;
20717 * max will be raised by given value
20718 *
20719 * Shrinking by passing a negative value is allowed.
20720 *
20721 * @param {number} val Amount by which to expand or shrink current range with
20722 */
20723
20724
20725Range.prototype.expand = function (val) {
20726 if (val === undefined) {
20727 return;
20728 }
20729
20730 var newMin = this.min - val;
20731 var newMax = this.max + val; // Note that following allows newMin === newMax.
20732 // This should be OK, since method expand() allows this also.
20733
20734 if (newMin > newMax) {
20735 throw new Error('Passed expansion value makes range invalid');
20736 }
20737
20738 this.min = newMin;
20739 this.max = newMax;
20740};
20741/**
20742 * Determine the full range width of current instance.
20743 *
20744 * @returns {num} The calculated width of this range
20745 */
20746
20747
20748Range.prototype.range = function () {
20749 return this.max - this.min;
20750};
20751/**
20752 * Determine the central point of current instance.
20753 *
20754 * @returns {number} the value in the middle of min and max
20755 */
20756
20757
20758Range.prototype.center = function () {
20759 return (this.min + this.max) / 2;
20760};
20761
20762var Range_1 = Range;
20763
20764var DataView$1 = index.DataView;
20765/**
20766 * @class Filter
20767 *
20768 * @param {DataGroup} dataGroup the data group
20769 * @param {number} column The index of the column to be filtered
20770 * @param {Graph3d} graph The graph
20771 */
20772
20773function Filter(dataGroup, column, graph) {
20774 this.dataGroup = dataGroup;
20775 this.column = column;
20776 this.graph = graph; // the parent graph
20777
20778 this.index = undefined;
20779 this.value = undefined; // read all distinct values and select the first one
20780
20781 this.values = dataGroup.getDistinctValues(this.column);
20782
20783 if (this.values.length > 0) {
20784 this.selectValue(0);
20785 } // create an array with the filtered datapoints. this will be loaded afterwards
20786
20787
20788 this.dataPoints = [];
20789 this.loaded = false;
20790 this.onLoadCallback = undefined;
20791
20792 if (graph.animationPreload) {
20793 this.loaded = false;
20794 this.loadInBackground();
20795 } else {
20796 this.loaded = true;
20797 }
20798}
20799/**
20800 * Return the label
20801 * @return {string} label
20802 */
20803
20804
20805Filter.prototype.isLoaded = function () {
20806 return this.loaded;
20807};
20808/**
20809 * Return the loaded progress
20810 * @return {number} percentage between 0 and 100
20811 */
20812
20813
20814Filter.prototype.getLoadedProgress = function () {
20815 var len = this.values.length;
20816 var i = 0;
20817
20818 while (this.dataPoints[i]) {
20819 i++;
20820 }
20821
20822 return Math.round(i / len * 100);
20823};
20824/**
20825 * Return the label
20826 * @return {string} label
20827 */
20828
20829
20830Filter.prototype.getLabel = function () {
20831 return this.graph.filterLabel;
20832};
20833/**
20834 * Return the columnIndex of the filter
20835 * @return {number} columnIndex
20836 */
20837
20838
20839Filter.prototype.getColumn = function () {
20840 return this.column;
20841};
20842/**
20843 * Return the currently selected value. Returns undefined if there is no selection
20844 * @return {*} value
20845 */
20846
20847
20848Filter.prototype.getSelectedValue = function () {
20849 if (this.index === undefined) return undefined;
20850 return this.values[this.index];
20851};
20852/**
20853 * Retrieve all values of the filter
20854 * @return {Array} values
20855 */
20856
20857
20858Filter.prototype.getValues = function () {
20859 return this.values;
20860};
20861/**
20862 * Retrieve one value of the filter
20863 * @param {number} index
20864 * @return {*} value
20865 */
20866
20867
20868Filter.prototype.getValue = function (index) {
20869 if (index >= this.values.length) throw new Error('Index out of range');
20870 return this.values[index];
20871};
20872/**
20873 * Retrieve the (filtered) dataPoints for the currently selected filter index
20874 * @param {number} [index] (optional)
20875 * @return {Array} dataPoints
20876 */
20877
20878
20879Filter.prototype._getDataPoints = function (index) {
20880 if (index === undefined) index = this.index;
20881 if (index === undefined) return [];
20882 var dataPoints;
20883
20884 if (this.dataPoints[index]) {
20885 dataPoints = this.dataPoints[index];
20886 } else {
20887 var f = {};
20888 f.column = this.column;
20889 f.value = this.values[index];
20890 var dataView = new DataView$1(this.dataGroup.getDataSet(), {
20891 filter: function filter(item) {
20892 return item[f.column] == f.value;
20893 }
20894 }).get();
20895 dataPoints = this.dataGroup._getDataPoints(dataView);
20896 this.dataPoints[index] = dataPoints;
20897 }
20898
20899 return dataPoints;
20900};
20901/**
20902 * Set a callback function when the filter is fully loaded.
20903 *
20904 * @param {function} callback
20905 */
20906
20907
20908Filter.prototype.setOnLoadCallback = function (callback) {
20909 this.onLoadCallback = callback;
20910};
20911/**
20912 * Add a value to the list with available values for this filter
20913 * No double entries will be created.
20914 * @param {number} index
20915 */
20916
20917
20918Filter.prototype.selectValue = function (index) {
20919 if (index >= this.values.length) throw new Error('Index out of range');
20920 this.index = index;
20921 this.value = this.values[index];
20922};
20923/**
20924 * Load all filtered rows in the background one by one
20925 * Start this method without providing an index!
20926 *
20927 * @param {number} [index=0]
20928 */
20929
20930
20931Filter.prototype.loadInBackground = function (index) {
20932 if (index === undefined) index = 0;
20933 var frame = this.graph.frame;
20934
20935 if (index < this.values.length) {
20936 // create a progress box
20937 if (frame.progress === undefined) {
20938 frame.progress = document.createElement('DIV');
20939 frame.progress.style.position = 'absolute';
20940 frame.progress.style.color = 'gray';
20941 frame.appendChild(frame.progress);
20942 }
20943
20944 var progress = this.getLoadedProgress();
20945 frame.progress.innerHTML = 'Loading animation... ' + progress + '%'; // TODO: this is no nice solution...
20946
20947 frame.progress.style.bottom = 60 + 'px'; // TODO: use height of slider
20948
20949 frame.progress.style.left = 10 + 'px';
20950 var me = this;
20951 setTimeout(function () {
20952 me.loadInBackground(index + 1);
20953 }, 10);
20954 this.loaded = false;
20955 } else {
20956 this.loaded = true; // remove the progress box
20957
20958 if (frame.progress !== undefined) {
20959 frame.removeChild(frame.progress);
20960 frame.progress = undefined;
20961 }
20962
20963 if (this.onLoadCallback) this.onLoadCallback();
20964 }
20965};
20966
20967var Filter_1 = Filter;
20968
20969var DataSet$1 = index.DataSet;
20970var DataView$2 = index.DataView;
20971/**
20972 * Creates a container for all data of one specific 3D-graph.
20973 *
20974 * On construction, the container is totally empty; the data
20975 * needs to be initialized with method initializeData().
20976 * Failure to do so will result in the following exception begin thrown
20977 * on instantiation of Graph3D:
20978 *
20979 * Error: Array, DataSet, or DataView expected
20980 *
20981 * @constructor DataGroup
20982 */
20983
20984function DataGroup() {
20985 this.dataTable = null; // The original data table
20986}
20987/**
20988 * Initializes the instance from the passed data.
20989 *
20990 * Calculates minimum and maximum values and column index values.
20991 *
20992 * The graph3d instance is used internally to access the settings for
20993 * the given instance.
20994 * TODO: Pass settings only instead.
20995 *
20996 * @param {vis.Graph3d} graph3d Reference to the calling Graph3D instance.
20997 * @param {Array | DataSet | DataView} rawData The data containing the items for
20998 * the Graph.
20999 * @param {number} style Style Number
21000 * @returns {Array.<Object>}
21001 */
21002
21003
21004DataGroup.prototype.initializeData = function (graph3d, rawData, style) {
21005 if (rawData === undefined) return;
21006
21007 if (Array.isArray(rawData)) {
21008 rawData = new DataSet$1(rawData);
21009 }
21010
21011 var data;
21012
21013 if (rawData instanceof DataSet$1 || rawData instanceof DataView$2) {
21014 data = rawData.get();
21015 } else {
21016 throw new Error('Array, DataSet, or DataView expected');
21017 }
21018
21019 if (data.length == 0) return;
21020 this.style = style; // unsubscribe from the dataTable
21021
21022 if (this.dataSet) {
21023 this.dataSet.off('*', this._onChange);
21024 }
21025
21026 this.dataSet = rawData;
21027 this.dataTable = data; // subscribe to changes in the dataset
21028
21029 var me = this;
21030
21031 this._onChange = function () {
21032 graph3d.setData(me.dataSet);
21033 };
21034
21035 this.dataSet.on('*', this._onChange); // determine the location of x,y,z,value,filter columns
21036
21037 this.colX = 'x';
21038 this.colY = 'y';
21039 this.colZ = 'z';
21040 var withBars = graph3d.hasBars(style); // determine barWidth from data
21041
21042 if (withBars) {
21043 if (graph3d.defaultXBarWidth !== undefined) {
21044 this.xBarWidth = graph3d.defaultXBarWidth;
21045 } else {
21046 this.xBarWidth = this.getSmallestDifference(data, this.colX) || 1;
21047 }
21048
21049 if (graph3d.defaultYBarWidth !== undefined) {
21050 this.yBarWidth = graph3d.defaultYBarWidth;
21051 } else {
21052 this.yBarWidth = this.getSmallestDifference(data, this.colY) || 1;
21053 }
21054 } // calculate minima and maxima
21055
21056
21057 this._initializeRange(data, this.colX, graph3d, withBars);
21058
21059 this._initializeRange(data, this.colY, graph3d, withBars);
21060
21061 this._initializeRange(data, this.colZ, graph3d, false);
21062
21063 if (data[0].hasOwnProperty('style')) {
21064 this.colValue = 'style';
21065 var valueRange = this.getColumnRange(data, this.colValue);
21066
21067 this._setRangeDefaults(valueRange, graph3d.defaultValueMin, graph3d.defaultValueMax);
21068
21069 this.valueRange = valueRange;
21070 } // Initialize data filter if a filter column is provided
21071
21072
21073 var table = this.getDataTable();
21074
21075 if (table[0].hasOwnProperty('filter')) {
21076 if (this.dataFilter === undefined) {
21077 this.dataFilter = new Filter_1(this, 'filter', graph3d);
21078 this.dataFilter.setOnLoadCallback(function () {
21079 graph3d.redraw();
21080 });
21081 }
21082 }
21083
21084 var dataPoints;
21085
21086 if (this.dataFilter) {
21087 // apply filtering
21088 dataPoints = this.dataFilter._getDataPoints();
21089 } else {
21090 // no filtering. load all data
21091 dataPoints = this._getDataPoints(this.getDataTable());
21092 }
21093
21094 return dataPoints;
21095};
21096/**
21097 * Collect the range settings for the given data column.
21098 *
21099 * This internal method is intended to make the range
21100 * initalization more generic.
21101 *
21102 * TODO: if/when combined settings per axis defined, get rid of this.
21103 *
21104 * @private
21105 *
21106 * @param {'x'|'y'|'z'} column The data column to process
21107 * @param {vis.Graph3d} graph3d Reference to the calling Graph3D instance;
21108 * required for access to settings
21109 * @returns {Object}
21110 */
21111
21112
21113DataGroup.prototype._collectRangeSettings = function (column, graph3d) {
21114 var index = ['x', 'y', 'z'].indexOf(column);
21115
21116 if (index == -1) {
21117 throw new Error('Column \'' + column + '\' invalid');
21118 }
21119
21120 var upper = column.toUpperCase();
21121 return {
21122 barWidth: this[column + 'BarWidth'],
21123 min: graph3d['default' + upper + 'Min'],
21124 max: graph3d['default' + upper + 'Max'],
21125 step: graph3d['default' + upper + 'Step'],
21126 range_label: column + 'Range',
21127 // Name of instance field to write to
21128 step_label: column + 'Step' // Name of instance field to write to
21129
21130 };
21131};
21132/**
21133 * Initializes the settings per given column.
21134 *
21135 * TODO: if/when combined settings per axis defined, rewrite this.
21136 *
21137 * @private
21138 *
21139 * @param {DataSet | DataView} data The data containing the items for the Graph
21140 * @param {'x'|'y'|'z'} column The data column to process
21141 * @param {vis.Graph3d} graph3d Reference to the calling Graph3D instance;
21142 * required for access to settings
21143 * @param {boolean} withBars True if initializing for bar graph
21144 */
21145
21146
21147DataGroup.prototype._initializeRange = function (data, column, graph3d, withBars) {
21148 var NUMSTEPS = 5;
21149
21150 var settings = this._collectRangeSettings(column, graph3d);
21151
21152 var range = this.getColumnRange(data, column);
21153
21154 if (withBars && column != 'z') {
21155 // Safeguard for 'z'; it doesn't have a bar width
21156 range.expand(settings.barWidth / 2);
21157 }
21158
21159 this._setRangeDefaults(range, settings.min, settings.max);
21160
21161 this[settings.range_label] = range;
21162 this[settings.step_label] = settings.step !== undefined ? settings.step : range.range() / NUMSTEPS;
21163};
21164/**
21165 * Creates a list with all the different values in the data for the given column.
21166 *
21167 * If no data passed, use the internal data of this instance.
21168 *
21169 * @param {'x'|'y'|'z'} column The data column to process
21170 * @param {DataSet|DataView|undefined} data The data containing the items for the Graph
21171 *
21172 * @returns {Array} All distinct values in the given column data, sorted ascending.
21173 */
21174
21175
21176DataGroup.prototype.getDistinctValues = function (column, data) {
21177 if (data === undefined) {
21178 data = this.dataTable;
21179 }
21180
21181 var values = [];
21182
21183 for (var i = 0; i < data.length; i++) {
21184 var value = data[i][column] || 0;
21185
21186 if (values.indexOf(value) === -1) {
21187 values.push(value);
21188 }
21189 }
21190
21191 return values.sort(function (a, b) {
21192 return a - b;
21193 });
21194};
21195/**
21196 * Determine the smallest difference between the values for given
21197 * column in the passed data set.
21198 *
21199 * @param {DataSet|DataView|undefined} data The data containing the items for the Graph
21200 * @param {'x'|'y'|'z'} column The data column to process
21201 *
21202 * @returns {number|null} Smallest difference value or
21203 * null, if it can't be determined.
21204 */
21205
21206
21207DataGroup.prototype.getSmallestDifference = function (data, column) {
21208 var values = this.getDistinctValues(data, column); // Get all the distinct diffs
21209 // Array values is assumed to be sorted here
21210
21211 var smallest_diff = null;
21212
21213 for (var i = 1; i < values.length; i++) {
21214 var diff = values[i] - values[i - 1];
21215
21216 if (smallest_diff == null || smallest_diff > diff) {
21217 smallest_diff = diff;
21218 }
21219 }
21220
21221 return smallest_diff;
21222};
21223/**
21224 * Get the absolute min/max values for the passed data column.
21225 *
21226 * @param {DataSet|DataView|undefined} data The data containing the items for the Graph
21227 * @param {'x'|'y'|'z'} column The data column to process
21228 *
21229 * @returns {Range} A Range instance with min/max members properly set.
21230 */
21231
21232
21233DataGroup.prototype.getColumnRange = function (data, column) {
21234 var range = new Range_1(); // Adjust the range so that it covers all values in the passed data elements.
21235
21236 for (var i = 0; i < data.length; i++) {
21237 var item = data[i][column];
21238 range.adjust(item);
21239 }
21240
21241 return range;
21242};
21243/**
21244 * Determines the number of rows in the current data.
21245 *
21246 * @returns {number}
21247 */
21248
21249
21250DataGroup.prototype.getNumberOfRows = function () {
21251 return this.dataTable.length;
21252};
21253/**
21254 * Set default values for range
21255 *
21256 * The default values override the range values, if defined.
21257 *
21258 * Because it's possible that only defaultMin or defaultMax is set, it's better
21259 * to pass in a range already set with the min/max set from the data. Otherwise,
21260 * it's quite hard to process the min/max properly.
21261 *
21262 * @param {vis.Range} range
21263 * @param {number} [defaultMin=range.min]
21264 * @param {number} [defaultMax=range.max]
21265 * @private
21266 */
21267
21268
21269DataGroup.prototype._setRangeDefaults = function (range, defaultMin, defaultMax) {
21270 if (defaultMin !== undefined) {
21271 range.min = defaultMin;
21272 }
21273
21274 if (defaultMax !== undefined) {
21275 range.max = defaultMax;
21276 } // This is the original way that the default min/max values were adjusted.
21277 // TODO: Perhaps it's better if an error is thrown if the values do not agree.
21278 // But this will change the behaviour.
21279
21280
21281 if (range.max <= range.min) range.max = range.min + 1;
21282};
21283
21284DataGroup.prototype.getDataTable = function () {
21285 return this.dataTable;
21286};
21287
21288DataGroup.prototype.getDataSet = function () {
21289 return this.dataSet;
21290};
21291/**
21292 * Return all data values as a list of Point3d objects
21293 * @param {Array.<Object>} data
21294 * @returns {Array.<Object>}
21295 */
21296
21297
21298DataGroup.prototype.getDataPoints = function (data) {
21299 var dataPoints = [];
21300
21301 for (var i = 0; i < data.length; i++) {
21302 var point = new Point3d_1();
21303 point.x = data[i][this.colX] || 0;
21304 point.y = data[i][this.colY] || 0;
21305 point.z = data[i][this.colZ] || 0;
21306 point.data = data[i];
21307
21308 if (this.colValue !== undefined) {
21309 point.value = data[i][this.colValue] || 0;
21310 }
21311
21312 var obj = {};
21313 obj.point = point;
21314 obj.bottom = new Point3d_1(point.x, point.y, this.zRange.min);
21315 obj.trans = undefined;
21316 obj.screen = undefined;
21317 dataPoints.push(obj);
21318 }
21319
21320 return dataPoints;
21321};
21322/**
21323 * Copy all values from the data table to a matrix.
21324 *
21325 * The provided values are supposed to form a grid of (x,y) positions.
21326 * @param {Array.<Object>} data
21327 * @returns {Array.<Object>}
21328 * @private
21329 */
21330
21331
21332DataGroup.prototype.initDataAsMatrix = function (data) {
21333 // TODO: store the created matrix dataPoints in the filters instead of
21334 // reloading each time.
21335 var x, y, i, obj; // create two lists with all present x and y values
21336
21337 var dataX = this.getDistinctValues(this.colX, data);
21338 var dataY = this.getDistinctValues(this.colY, data);
21339 var dataPoints = this.getDataPoints(data); // create a grid, a 2d matrix, with all values.
21340
21341 var dataMatrix = []; // temporary data matrix
21342
21343 for (i = 0; i < dataPoints.length; i++) {
21344 obj = dataPoints[i]; // TODO: implement Array().indexOf() for Internet Explorer
21345
21346 var xIndex = dataX.indexOf(obj.point.x);
21347 var yIndex = dataY.indexOf(obj.point.y);
21348
21349 if (dataMatrix[xIndex] === undefined) {
21350 dataMatrix[xIndex] = [];
21351 }
21352
21353 dataMatrix[xIndex][yIndex] = obj;
21354 } // fill in the pointers to the neighbors.
21355
21356
21357 for (x = 0; x < dataMatrix.length; x++) {
21358 for (y = 0; y < dataMatrix[x].length; y++) {
21359 if (dataMatrix[x][y]) {
21360 dataMatrix[x][y].pointRight = x < dataMatrix.length - 1 ? dataMatrix[x + 1][y] : undefined;
21361 dataMatrix[x][y].pointTop = y < dataMatrix[x].length - 1 ? dataMatrix[x][y + 1] : undefined;
21362 dataMatrix[x][y].pointCross = x < dataMatrix.length - 1 && y < dataMatrix[x].length - 1 ? dataMatrix[x + 1][y + 1] : undefined;
21363 }
21364 }
21365 }
21366
21367 return dataPoints;
21368};
21369/**
21370 * Return common information, if present
21371 *
21372 * @returns {string}
21373 */
21374
21375
21376DataGroup.prototype.getInfo = function () {
21377 var dataFilter = this.dataFilter;
21378 if (!dataFilter) return undefined;
21379 return dataFilter.getLabel() + ': ' + dataFilter.getSelectedValue();
21380};
21381/**
21382 * Reload the data
21383 */
21384
21385
21386DataGroup.prototype.reload = function () {
21387 if (this.dataTable) {
21388 this.setData(this.dataTable);
21389 }
21390};
21391/**
21392 * Filter the data based on the current filter
21393 *
21394 * @param {Array} data
21395 * @returns {Array} dataPoints Array with point objects which can be drawn on
21396 * screen
21397 */
21398
21399
21400DataGroup.prototype._getDataPoints = function (data) {
21401 var dataPoints = [];
21402
21403 if (this.style === Settings.STYLE.GRID || this.style === Settings.STYLE.SURFACE) {
21404 dataPoints = this.initDataAsMatrix(data);
21405 } else {
21406 // 'dot', 'dot-line', etc.
21407 this._checkValueField(data);
21408
21409 dataPoints = this.getDataPoints(data);
21410
21411 if (this.style === Settings.STYLE.LINE) {
21412 // Add next member points for line drawing
21413 for (var i = 0; i < dataPoints.length; i++) {
21414 if (i > 0) {
21415 dataPoints[i - 1].pointNext = dataPoints[i];
21416 }
21417 }
21418 }
21419 }
21420
21421 return dataPoints;
21422};
21423/**
21424 * Check if the state is consistent for the use of the value field.
21425 *
21426 * Throws if a problem is detected.
21427 *
21428 * @param {Array.<Object>} data
21429 * @private
21430 */
21431
21432
21433DataGroup.prototype._checkValueField = function (data) {
21434 var hasValueField = this.style === Settings.STYLE.BARCOLOR || this.style === Settings.STYLE.BARSIZE || this.style === Settings.STYLE.DOTCOLOR || this.style === Settings.STYLE.DOTSIZE;
21435
21436 if (!hasValueField) {
21437 return; // No need to check further
21438 } // Following field must be present for the current graph style
21439
21440
21441 if (this.colValue === undefined) {
21442 throw new Error('Expected data to have ' + ' field \'style\' ' + ' for graph style \'' + this.style + '\'');
21443 } // The data must also contain this field.
21444 // Note that only first data element is checked.
21445
21446
21447 if (data[0][this.colValue] === undefined) {
21448 throw new Error('Expected data to have ' + ' field \'' + this.colValue + '\' ' + ' for graph style \'' + this.style + '\'');
21449 }
21450};
21451
21452var DataGroup_1 = DataGroup;
21453
21454var Validator$2 = Validator$1.Validator;
21455var printStyle$1 = Validator$1.printStyle;
21456var allOptions$2 = options.allOptions; /// enumerate the available styles
21457
21458Graph3d.STYLE = Settings.STYLE;
21459/**
21460 * Following label is used in the settings to describe values which should be
21461 * determined by the code while running, from the current data and graph style.
21462 *
21463 * Using 'undefined' directly achieves the same thing, but this is more
21464 * descriptive by describing the intent.
21465 */
21466
21467var autoByDefault = undefined;
21468/**
21469 * Default values for option settings.
21470 *
21471 * These are the values used when a Graph3d instance is initialized without
21472 * custom settings.
21473 *
21474 * If a field is not in this list, a default value of 'autoByDefault' is assumed,
21475 * which is just an alias for 'undefined'.
21476 */
21477
21478Graph3d.DEFAULTS = {
21479 width: '400px',
21480 height: '400px',
21481 filterLabel: 'time',
21482 legendLabel: 'value',
21483 xLabel: 'x',
21484 yLabel: 'y',
21485 zLabel: 'z',
21486 xValueLabel: function xValueLabel(v) {
21487 return v;
21488 },
21489 yValueLabel: function yValueLabel(v) {
21490 return v;
21491 },
21492 zValueLabel: function zValueLabel(v) {
21493 return v;
21494 },
21495 showXAxis: true,
21496 showYAxis: true,
21497 showZAxis: true,
21498 showGrid: true,
21499 showPerspective: true,
21500 showShadow: false,
21501 keepAspectRatio: true,
21502 rotateAxisLabels: true,
21503 verticalRatio: 0.5,
21504 // 0.1 to 1.0, where 1.0 results in a 'cube'
21505 dotSizeRatio: 0.02,
21506 // size of the dots as a fraction of the graph width
21507 dotSizeMinFraction: 0.5,
21508 // size of min-value dot as a fraction of dotSizeRatio
21509 dotSizeMaxFraction: 2.5,
21510 // size of max-value dot as a fraction of dotSizeRatio
21511 showAnimationControls: autoByDefault,
21512 animationInterval: 1000,
21513 // milliseconds
21514 animationPreload: false,
21515 animationAutoStart: autoByDefault,
21516 axisFontSize: 14,
21517 axisFontType: 'arial',
21518 axisColor: '#4D4D4D',
21519 gridColor: '#D3D3D3',
21520 xCenter: '55%',
21521 yCenter: '50%',
21522 style: Graph3d.STYLE.DOT,
21523 tooltip: false,
21524 tooltipDelay: 300,
21525 // milliseconds
21526 tooltipStyle: {
21527 content: {
21528 padding: '10px',
21529 border: '1px solid #4d4d4d',
21530 color: '#1a1a1a',
21531 background: 'rgba(255,255,255,0.7)',
21532 borderRadius: '2px',
21533 boxShadow: '5px 5px 10px rgba(128,128,128,0.5)'
21534 },
21535 line: {
21536 height: '40px',
21537 width: '0',
21538 borderLeft: '1px solid #4d4d4d',
21539 pointerEvents: 'none'
21540 },
21541 dot: {
21542 height: '0',
21543 width: '0',
21544 border: '5px solid #4d4d4d',
21545 borderRadius: '5px',
21546 pointerEvents: 'none'
21547 }
21548 },
21549 dataColor: {
21550 fill: '#7DC1FF',
21551 stroke: '#3267D2',
21552 strokeWidth: 1 // px
21553
21554 },
21555 cameraPosition: {
21556 horizontal: 1.0,
21557 vertical: 0.5,
21558 distance: 1.7
21559 },
21560 zoomable: true,
21561 ctrlToZoom: false,
21562
21563 /*
21564 The following fields are 'auto by default', see above.
21565 */
21566 showLegend: autoByDefault,
21567 // determined by graph style
21568 backgroundColor: autoByDefault,
21569 xBarWidth: autoByDefault,
21570 yBarWidth: autoByDefault,
21571 valueMin: autoByDefault,
21572 valueMax: autoByDefault,
21573 xMin: autoByDefault,
21574 xMax: autoByDefault,
21575 xStep: autoByDefault,
21576 yMin: autoByDefault,
21577 yMax: autoByDefault,
21578 yStep: autoByDefault,
21579 zMin: autoByDefault,
21580 zMax: autoByDefault,
21581 zStep: autoByDefault
21582}; // -----------------------------------------------------------------------------
21583// Class Graph3d
21584// -----------------------------------------------------------------------------
21585
21586/**
21587 * Graph3d displays data in 3d.
21588 *
21589 * Graph3d is developed in javascript as a Google Visualization Chart.
21590 *
21591 * @constructor Graph3d
21592 * @param {Element} container The DOM element in which the Graph3d will
21593 * be created. Normally a div element.
21594 * @param {DataSet | DataView | Array} [data]
21595 * @param {Object} [options]
21596 */
21597
21598function Graph3d(container, data, options) {
21599 if (!(this instanceof Graph3d)) {
21600 throw new SyntaxError('Constructor must be called with the new operator');
21601 } // create variables and set default values
21602
21603
21604 this.containerElement = container;
21605 this.dataGroup = new DataGroup_1();
21606 this.dataPoints = null; // The table with point objects
21607 // create a frame and canvas
21608
21609 this.create();
21610 Settings.setDefaults(Graph3d.DEFAULTS, this); // the column indexes
21611
21612 this.colX = undefined;
21613 this.colY = undefined;
21614 this.colZ = undefined;
21615 this.colValue = undefined; // TODO: customize axis range
21616 // apply options (also when undefined)
21617
21618 this.setOptions(options); // apply data
21619
21620 this.setData(data);
21621} // Extend Graph3d with an Emitter mixin
21622
21623
21624emitterComponent(Graph3d.prototype);
21625/**
21626 * Calculate the scaling values, dependent on the range in x, y, and z direction
21627 */
21628
21629Graph3d.prototype._setScale = function () {
21630 this.scale = new Point3d_1(1 / this.xRange.range(), 1 / this.yRange.range(), 1 / this.zRange.range()); // keep aspect ration between x and y scale if desired
21631
21632 if (this.keepAspectRatio) {
21633 if (this.scale.x < this.scale.y) {
21634 //noinspection JSSuspiciousNameCombination
21635 this.scale.y = this.scale.x;
21636 } else {
21637 //noinspection JSSuspiciousNameCombination
21638 this.scale.x = this.scale.y;
21639 }
21640 } // scale the vertical axis
21641
21642
21643 this.scale.z *= this.verticalRatio; // TODO: can this be automated? verticalRatio?
21644 // determine scale for (optional) value
21645
21646 if (this.valueRange !== undefined) {
21647 this.scale.value = 1 / this.valueRange.range();
21648 } // position the camera arm
21649
21650
21651 var xCenter = this.xRange.center() * this.scale.x;
21652 var yCenter = this.yRange.center() * this.scale.y;
21653 var zCenter = this.zRange.center() * this.scale.z;
21654 this.camera.setArmLocation(xCenter, yCenter, zCenter);
21655};
21656/**
21657 * Convert a 3D location to a 2D location on screen
21658 * Source: ttp://en.wikipedia.org/wiki/3D_projection
21659 *
21660 * @param {Point3d} point3d A 3D point with parameters x, y, z
21661 * @returns {Point2d} point2d A 2D point with parameters x, y
21662 */
21663
21664
21665Graph3d.prototype._convert3Dto2D = function (point3d) {
21666 var translation = this._convertPointToTranslation(point3d);
21667
21668 return this._convertTranslationToScreen(translation);
21669};
21670/**
21671 * Convert a 3D location its translation seen from the camera
21672 * Source: http://en.wikipedia.org/wiki/3D_projection
21673 *
21674 * @param {Point3d} point3d A 3D point with parameters x, y, z
21675 * @returns {Point3d} translation A 3D point with parameters x, y, z This is
21676 * the translation of the point, seen from the
21677 * camera.
21678 */
21679
21680
21681Graph3d.prototype._convertPointToTranslation = function (point3d) {
21682 var cameraLocation = this.camera.getCameraLocation(),
21683 cameraRotation = this.camera.getCameraRotation(),
21684 ax = point3d.x * this.scale.x,
21685 ay = point3d.y * this.scale.y,
21686 az = point3d.z * this.scale.z,
21687 cx = cameraLocation.x,
21688 cy = cameraLocation.y,
21689 cz = cameraLocation.z,
21690 // calculate angles
21691 sinTx = Math.sin(cameraRotation.x),
21692 cosTx = Math.cos(cameraRotation.x),
21693 sinTy = Math.sin(cameraRotation.y),
21694 cosTy = Math.cos(cameraRotation.y),
21695 sinTz = Math.sin(cameraRotation.z),
21696 cosTz = Math.cos(cameraRotation.z),
21697 // calculate translation
21698 dx = cosTy * (sinTz * (ay - cy) + cosTz * (ax - cx)) - sinTy * (az - cz),
21699 dy = sinTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) + cosTx * (cosTz * (ay - cy) - sinTz * (ax - cx)),
21700 dz = cosTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) - sinTx * (cosTz * (ay - cy) - sinTz * (ax - cx));
21701 return new Point3d_1(dx, dy, dz);
21702};
21703/**
21704 * Convert a translation point to a point on the screen
21705 *
21706 * @param {Point3d} translation A 3D point with parameters x, y, z This is
21707 * the translation of the point, seen from the
21708 * camera.
21709 * @returns {Point2d} point2d A 2D point with parameters x, y
21710 */
21711
21712
21713Graph3d.prototype._convertTranslationToScreen = function (translation) {
21714 var ex = this.eye.x,
21715 ey = this.eye.y,
21716 ez = this.eye.z,
21717 dx = translation.x,
21718 dy = translation.y,
21719 dz = translation.z; // calculate position on screen from translation
21720
21721 var bx;
21722 var by;
21723
21724 if (this.showPerspective) {
21725 bx = (dx - ex) * (ez / dz);
21726 by = (dy - ey) * (ez / dz);
21727 } else {
21728 bx = dx * -(ez / this.camera.getArmLength());
21729 by = dy * -(ez / this.camera.getArmLength());
21730 } // shift and scale the point to the center of the screen
21731 // use the width of the graph to scale both horizontally and vertically.
21732
21733
21734 return new Point2d_1(this.currentXCenter + bx * this.frame.canvas.clientWidth, this.currentYCenter - by * this.frame.canvas.clientWidth);
21735};
21736/**
21737 * Calculate the translations and screen positions of all points
21738 *
21739 * @param {Array.<Point3d>} points
21740 * @private
21741 */
21742
21743
21744Graph3d.prototype._calcTranslations = function (points) {
21745 for (var i = 0; i < points.length; i++) {
21746 var point = points[i];
21747 point.trans = this._convertPointToTranslation(point.point);
21748 point.screen = this._convertTranslationToScreen(point.trans); // calculate the translation of the point at the bottom (needed for sorting)
21749
21750 var transBottom = this._convertPointToTranslation(point.bottom);
21751
21752 point.dist = this.showPerspective ? transBottom.length() : -transBottom.z;
21753 } // sort the points on depth of their (x,y) position (not on z)
21754
21755
21756 var sortDepth = function sortDepth(a, b) {
21757 return b.dist - a.dist;
21758 };
21759
21760 points.sort(sortDepth);
21761};
21762/**
21763 * Transfer min/max values to the Graph3d instance.
21764 */
21765
21766
21767Graph3d.prototype._initializeRanges = function () {
21768 // TODO: later on, all min/maxes of all datagroups will be combined here
21769 var dg = this.dataGroup;
21770 this.xRange = dg.xRange;
21771 this.yRange = dg.yRange;
21772 this.zRange = dg.zRange;
21773 this.valueRange = dg.valueRange; // Values currently needed but which need to be sorted out for
21774 // the multiple graph case.
21775
21776 this.xStep = dg.xStep;
21777 this.yStep = dg.yStep;
21778 this.zStep = dg.zStep;
21779 this.xBarWidth = dg.xBarWidth;
21780 this.yBarWidth = dg.yBarWidth;
21781 this.colX = dg.colX;
21782 this.colY = dg.colY;
21783 this.colZ = dg.colZ;
21784 this.colValue = dg.colValue; // set the scale dependent on the ranges.
21785
21786 this._setScale();
21787};
21788/**
21789 * Return all data values as a list of Point3d objects
21790 *
21791 * @param {vis.DataSet} data
21792 * @returns {Array.<Object>}
21793 */
21794
21795
21796Graph3d.prototype.getDataPoints = function (data) {
21797 var dataPoints = [];
21798
21799 for (var i = 0; i < data.length; i++) {
21800 var point = new Point3d_1();
21801 point.x = data[i][this.colX] || 0;
21802 point.y = data[i][this.colY] || 0;
21803 point.z = data[i][this.colZ] || 0;
21804 point.data = data[i];
21805
21806 if (this.colValue !== undefined) {
21807 point.value = data[i][this.colValue] || 0;
21808 }
21809
21810 var obj = {};
21811 obj.point = point;
21812 obj.bottom = new Point3d_1(point.x, point.y, this.zRange.min);
21813 obj.trans = undefined;
21814 obj.screen = undefined;
21815 dataPoints.push(obj);
21816 }
21817
21818 return dataPoints;
21819};
21820/**
21821 * Filter the data based on the current filter
21822 *
21823 * @param {Array} data
21824 * @returns {Array} dataPoints Array with point objects which can be drawn on
21825 * screen
21826 */
21827
21828
21829Graph3d.prototype._getDataPoints = function (data) {
21830 // TODO: store the created matrix dataPoints in the filters instead of
21831 // reloading each time.
21832 var x, y, i, obj;
21833 var dataPoints = [];
21834
21835 if (this.style === Graph3d.STYLE.GRID || this.style === Graph3d.STYLE.SURFACE) {
21836 // copy all values from the data table to a matrix
21837 // the provided values are supposed to form a grid of (x,y) positions
21838 // create two lists with all present x and y values
21839 var dataX = this.dataGroup.getDistinctValues(this.colX, data);
21840 var dataY = this.dataGroup.getDistinctValues(this.colY, data);
21841 dataPoints = this.getDataPoints(data); // create a grid, a 2d matrix, with all values.
21842
21843 var dataMatrix = []; // temporary data matrix
21844
21845 for (i = 0; i < dataPoints.length; i++) {
21846 obj = dataPoints[i]; // TODO: implement Array().indexOf() for Internet Explorer
21847
21848 var xIndex = dataX.indexOf(obj.point.x);
21849 var yIndex = dataY.indexOf(obj.point.y);
21850
21851 if (dataMatrix[xIndex] === undefined) {
21852 dataMatrix[xIndex] = [];
21853 }
21854
21855 dataMatrix[xIndex][yIndex] = obj;
21856 } // fill in the pointers to the neighbors.
21857
21858
21859 for (x = 0; x < dataMatrix.length; x++) {
21860 for (y = 0; y < dataMatrix[x].length; y++) {
21861 if (dataMatrix[x][y]) {
21862 dataMatrix[x][y].pointRight = x < dataMatrix.length - 1 ? dataMatrix[x + 1][y] : undefined;
21863 dataMatrix[x][y].pointTop = y < dataMatrix[x].length - 1 ? dataMatrix[x][y + 1] : undefined;
21864 dataMatrix[x][y].pointCross = x < dataMatrix.length - 1 && y < dataMatrix[x].length - 1 ? dataMatrix[x + 1][y + 1] : undefined;
21865 }
21866 }
21867 }
21868 } else {
21869 // 'dot', 'dot-line', etc.
21870 this._checkValueField(data);
21871
21872 dataPoints = this.getDataPoints(data);
21873
21874 if (this.style === Graph3d.STYLE.LINE) {
21875 // Add next member points for line drawing
21876 for (i = 0; i < dataPoints.length; i++) {
21877 if (i > 0) {
21878 dataPoints[i - 1].pointNext = dataPoints[i];
21879 }
21880 }
21881 }
21882 }
21883
21884 return dataPoints;
21885};
21886/**
21887 * Create the main frame for the Graph3d.
21888 *
21889 * This function is executed once when a Graph3d object is created. The frame
21890 * contains a canvas, and this canvas contains all objects like the axis and
21891 * nodes.
21892 */
21893
21894
21895Graph3d.prototype.create = function () {
21896 // remove all elements from the container element.
21897 while (this.containerElement.hasChildNodes()) {
21898 this.containerElement.removeChild(this.containerElement.firstChild);
21899 }
21900
21901 this.frame = document.createElement('div');
21902 this.frame.style.position = 'relative';
21903 this.frame.style.overflow = 'hidden'; // create the graph canvas (HTML canvas element)
21904
21905 this.frame.canvas = document.createElement('canvas');
21906 this.frame.canvas.style.position = 'relative';
21907 this.frame.appendChild(this.frame.canvas); //if (!this.frame.canvas.getContext) {
21908
21909 {
21910 var noCanvas = document.createElement('DIV');
21911 noCanvas.style.color = 'red';
21912 noCanvas.style.fontWeight = 'bold';
21913 noCanvas.style.padding = '10px';
21914 noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
21915 this.frame.canvas.appendChild(noCanvas);
21916 }
21917 this.frame.filter = document.createElement('div');
21918 this.frame.filter.style.position = 'absolute';
21919 this.frame.filter.style.bottom = '0px';
21920 this.frame.filter.style.left = '0px';
21921 this.frame.filter.style.width = '100%';
21922 this.frame.appendChild(this.frame.filter); // add event listeners to handle moving and zooming the contents
21923
21924 var me = this;
21925
21926 var onmousedown = function onmousedown(event) {
21927 me._onMouseDown(event);
21928 };
21929
21930 var ontouchstart = function ontouchstart(event) {
21931 me._onTouchStart(event);
21932 };
21933
21934 var onmousewheel = function onmousewheel(event) {
21935 me._onWheel(event);
21936 };
21937
21938 var ontooltip = function ontooltip(event) {
21939 me._onTooltip(event);
21940 };
21941
21942 var onclick = function onclick(event) {
21943 me._onClick(event);
21944 }; // TODO: these events are never cleaned up... can give a 'memory leakage'
21945
21946
21947 util.addEventListener(this.frame.canvas, 'mousedown', onmousedown);
21948 util.addEventListener(this.frame.canvas, 'touchstart', ontouchstart);
21949 util.addEventListener(this.frame.canvas, 'mousewheel', onmousewheel);
21950 util.addEventListener(this.frame.canvas, 'mousemove', ontooltip);
21951 util.addEventListener(this.frame.canvas, 'click', onclick); // add the new graph to the container element
21952
21953 this.containerElement.appendChild(this.frame);
21954};
21955/**
21956 * Set a new size for the graph
21957 *
21958 * @param {number} width
21959 * @param {number} height
21960 * @private
21961 */
21962
21963
21964Graph3d.prototype._setSize = function (width, height) {
21965 this.frame.style.width = width;
21966 this.frame.style.height = height;
21967
21968 this._resizeCanvas();
21969};
21970/**
21971 * Resize the canvas to the current size of the frame
21972 */
21973
21974
21975Graph3d.prototype._resizeCanvas = function () {
21976 this.frame.canvas.style.width = '100%';
21977 this.frame.canvas.style.height = '100%';
21978 this.frame.canvas.width = this.frame.canvas.clientWidth;
21979 this.frame.canvas.height = this.frame.canvas.clientHeight; // adjust with for margin
21980
21981 this.frame.filter.style.width = this.frame.canvas.clientWidth - 2 * 10 + 'px';
21982};
21983/**
21984 * Start playing the animation, if requested and filter present. Only applicable
21985 * when animation data is available.
21986 */
21987
21988
21989Graph3d.prototype.animationStart = function () {
21990 // start animation when option is true
21991 if (!this.animationAutoStart || !this.dataGroup.dataFilter) return;
21992 if (!this.frame.filter || !this.frame.filter.slider) throw new Error('No animation available');
21993 this.frame.filter.slider.play();
21994};
21995/**
21996 * Stop animation
21997 */
21998
21999
22000Graph3d.prototype.animationStop = function () {
22001 if (!this.frame.filter || !this.frame.filter.slider) return;
22002 this.frame.filter.slider.stop();
22003};
22004/**
22005 * Resize the center position based on the current values in this.xCenter
22006 * and this.yCenter (which are strings with a percentage or a value
22007 * in pixels). The center positions are the variables this.currentXCenter
22008 * and this.currentYCenter
22009 */
22010
22011
22012Graph3d.prototype._resizeCenter = function () {
22013 // calculate the horizontal center position
22014 if (this.xCenter.charAt(this.xCenter.length - 1) === '%') {
22015 this.currentXCenter = parseFloat(this.xCenter) / 100 * this.frame.canvas.clientWidth;
22016 } else {
22017 this.currentXCenter = parseFloat(this.xCenter); // supposed to be in px
22018 } // calculate the vertical center position
22019
22020
22021 if (this.yCenter.charAt(this.yCenter.length - 1) === '%') {
22022 this.currentYCenter = parseFloat(this.yCenter) / 100 * (this.frame.canvas.clientHeight - this.frame.filter.clientHeight);
22023 } else {
22024 this.currentYCenter = parseFloat(this.yCenter); // supposed to be in px
22025 }
22026};
22027/**
22028 * Retrieve the current camera rotation
22029 *
22030 * @returns {object} An object with parameters horizontal, vertical, and
22031 * distance
22032 */
22033
22034
22035Graph3d.prototype.getCameraPosition = function () {
22036 var pos = this.camera.getArmRotation();
22037 pos.distance = this.camera.getArmLength();
22038 return pos;
22039};
22040/**
22041 * Load data into the 3D Graph
22042 *
22043 * @param {vis.DataSet} data
22044 * @private
22045 */
22046
22047
22048Graph3d.prototype._readData = function (data) {
22049 // read the data
22050 this.dataPoints = this.dataGroup.initializeData(this, data, this.style);
22051
22052 this._initializeRanges();
22053
22054 this._redrawFilter();
22055};
22056/**
22057 * Replace the dataset of the Graph3d
22058 *
22059 * @param {Array | DataSet | DataView} data
22060 */
22061
22062
22063Graph3d.prototype.setData = function (data) {
22064 if (data === undefined || data === null) return;
22065
22066 this._readData(data);
22067
22068 this.redraw();
22069 this.animationStart();
22070};
22071/**
22072 * Update the options. Options will be merged with current options
22073 *
22074 * @param {Object} options
22075 */
22076
22077
22078Graph3d.prototype.setOptions = function (options) {
22079 if (options === undefined) return;
22080 var errorFound = Validator$2.validate(options, allOptions$2);
22081
22082 if (errorFound === true) {
22083 console.log('%cErrors have been found in the supplied options object.', printStyle$1);
22084 }
22085
22086 this.animationStop();
22087 Settings.setOptions(options, this);
22088 this.setPointDrawingMethod();
22089
22090 this._setSize(this.width, this.height);
22091
22092 this.setAxisLabelMethod();
22093 this.setData(this.dataGroup.getDataTable());
22094 this.animationStart();
22095};
22096/**
22097 * Determine which point drawing method to use for the current graph style.
22098 */
22099
22100
22101Graph3d.prototype.setPointDrawingMethod = function () {
22102 var method = undefined;
22103
22104 switch (this.style) {
22105 case Graph3d.STYLE.BAR:
22106 method = Graph3d.prototype._redrawBarGraphPoint;
22107 break;
22108
22109 case Graph3d.STYLE.BARCOLOR:
22110 method = Graph3d.prototype._redrawBarColorGraphPoint;
22111 break;
22112
22113 case Graph3d.STYLE.BARSIZE:
22114 method = Graph3d.prototype._redrawBarSizeGraphPoint;
22115 break;
22116
22117 case Graph3d.STYLE.DOT:
22118 method = Graph3d.prototype._redrawDotGraphPoint;
22119 break;
22120
22121 case Graph3d.STYLE.DOTLINE:
22122 method = Graph3d.prototype._redrawDotLineGraphPoint;
22123 break;
22124
22125 case Graph3d.STYLE.DOTCOLOR:
22126 method = Graph3d.prototype._redrawDotColorGraphPoint;
22127 break;
22128
22129 case Graph3d.STYLE.DOTSIZE:
22130 method = Graph3d.prototype._redrawDotSizeGraphPoint;
22131 break;
22132
22133 case Graph3d.STYLE.SURFACE:
22134 method = Graph3d.prototype._redrawSurfaceGraphPoint;
22135 break;
22136
22137 case Graph3d.STYLE.GRID:
22138 method = Graph3d.prototype._redrawGridGraphPoint;
22139 break;
22140
22141 case Graph3d.STYLE.LINE:
22142 method = Graph3d.prototype._redrawLineGraphPoint;
22143 break;
22144
22145 default:
22146 throw new Error('Can not determine point drawing method ' + 'for graph style \'' + this.style + '\'');
22147 }
22148
22149 this._pointDrawingMethod = method;
22150};
22151/**
22152 * Determine which functions to use to draw axis labels.
22153 */
22154
22155
22156Graph3d.prototype.setAxisLabelMethod = function () {
22157 var method_x, method_y, method_z;
22158 method_x = method_y = method_z = undefined;
22159
22160 if (this.rotateAxisLabels == true) {
22161 method_x = Graph3d.prototype.drawAxisLabelXRotate;
22162 method_y = Graph3d.prototype.drawAxisLabelYRotate;
22163 method_z = Graph3d.prototype.drawAxisLabelZRotate;
22164 } else {
22165 method_x = Graph3d.prototype.drawAxisLabelX;
22166 method_y = Graph3d.prototype.drawAxisLabelY;
22167 method_z = Graph3d.prototype.drawAxisLabelZ;
22168 }
22169
22170 this._drawAxisLabelX = method_x;
22171 this._drawAxisLabelY = method_y;
22172 this._drawAxisLabelZ = method_z;
22173};
22174/**
22175 * Redraw the Graph.
22176 */
22177
22178
22179Graph3d.prototype.redraw = function () {
22180 if (this.dataPoints === undefined) {
22181 throw new Error('Graph data not initialized');
22182 }
22183
22184 this._resizeCanvas();
22185
22186 this._resizeCenter();
22187
22188 this._redrawSlider();
22189
22190 this._redrawClear();
22191
22192 this._redrawAxis();
22193
22194 this._redrawDataGraph();
22195
22196 this._redrawInfo();
22197
22198 this._redrawLegend();
22199};
22200/**
22201 * Get drawing context without exposing canvas
22202 *
22203 * @returns {CanvasRenderingContext2D}
22204 * @private
22205 */
22206
22207
22208Graph3d.prototype._getContext = function () {
22209 var canvas = this.frame.canvas;
22210 var ctx = canvas.getContext('2d');
22211 ctx.lineJoin = 'round';
22212 ctx.lineCap = 'round';
22213 return ctx;
22214};
22215/**
22216 * Clear the canvas before redrawing
22217 */
22218
22219
22220Graph3d.prototype._redrawClear = function () {
22221 var canvas = this.frame.canvas;
22222 var ctx = canvas.getContext('2d');
22223 ctx.clearRect(0, 0, canvas.width, canvas.height);
22224};
22225
22226Graph3d.prototype._dotSize = function () {
22227 return this.frame.clientWidth * this.dotSizeRatio;
22228};
22229/**
22230 * Get legend width
22231 *
22232 * @returns {*}
22233 * @private
22234 */
22235
22236
22237Graph3d.prototype._getLegendWidth = function () {
22238 var width;
22239
22240 if (this.style === Graph3d.STYLE.DOTSIZE) {
22241 var dotSize = this._dotSize(); //width = dotSize / 2 + dotSize * 2;
22242
22243
22244 width = dotSize * this.dotSizeMaxFraction;
22245 } else if (this.style === Graph3d.STYLE.BARSIZE) {
22246 width = this.xBarWidth;
22247 } else {
22248 width = 20;
22249 }
22250
22251 return width;
22252};
22253/**
22254 * Redraw the legend based on size, dot color, or surface height
22255 */
22256
22257
22258Graph3d.prototype._redrawLegend = function () {
22259 //Return without drawing anything, if no legend is specified
22260 if (this.showLegend !== true) {
22261 return;
22262 } // Do not draw legend when graph style does not support
22263
22264
22265 if (this.style === Graph3d.STYLE.LINE || this.style === Graph3d.STYLE.BARSIZE //TODO add legend support for BARSIZE
22266 ) {
22267 return;
22268 } // Legend types - size and color. Determine if size legend.
22269
22270
22271 var isSizeLegend = this.style === Graph3d.STYLE.BARSIZE || this.style === Graph3d.STYLE.DOTSIZE; // Legend is either tracking z values or style values. This flag if false means use z values.
22272
22273 var isValueLegend = this.style === Graph3d.STYLE.DOTSIZE || this.style === Graph3d.STYLE.DOTCOLOR || this.style === Graph3d.STYLE.BARCOLOR;
22274 var height = Math.max(this.frame.clientHeight * 0.25, 100);
22275 var top = this.margin;
22276
22277 var width = this._getLegendWidth(); // px - overwritten by size legend
22278
22279
22280 var right = this.frame.clientWidth - this.margin;
22281 var left = right - width;
22282 var bottom = top + height;
22283
22284 var ctx = this._getContext();
22285
22286 ctx.lineWidth = 1;
22287 ctx.font = '14px arial'; // TODO: put in options
22288
22289 if (isSizeLegend === false) {
22290 // draw the color bar
22291 var ymin = 0;
22292 var ymax = height; // Todo: make height customizable
22293
22294 var y;
22295
22296 for (y = ymin; y < ymax; y++) {
22297 var f = (y - ymin) / (ymax - ymin);
22298 var hue = f * 240;
22299
22300 var color = this._hsv2rgb(hue, 1, 1);
22301
22302 ctx.strokeStyle = color;
22303 ctx.beginPath();
22304 ctx.moveTo(left, top + y);
22305 ctx.lineTo(right, top + y);
22306 ctx.stroke();
22307 }
22308
22309 ctx.strokeStyle = this.axisColor;
22310 ctx.strokeRect(left, top, width, height);
22311 } else {
22312 // draw the size legend box
22313 var widthMin;
22314
22315 if (this.style === Graph3d.STYLE.DOTSIZE) {
22316 // Get the proportion to max and min right
22317 widthMin = width * (this.dotSizeMinFraction / this.dotSizeMaxFraction);
22318 } else if (this.style === Graph3d.STYLE.BARSIZE) ;
22319
22320 ctx.strokeStyle = this.axisColor;
22321 ctx.fillStyle = this.dataColor.fill;
22322 ctx.beginPath();
22323 ctx.moveTo(left, top);
22324 ctx.lineTo(right, top);
22325 ctx.lineTo(left + widthMin, bottom);
22326 ctx.lineTo(left, bottom);
22327 ctx.closePath();
22328 ctx.fill();
22329 ctx.stroke();
22330 } // print value text along the legend edge
22331
22332
22333 var gridLineLen = 5; // px
22334
22335 var legendMin = isValueLegend ? this.valueRange.min : this.zRange.min;
22336 var legendMax = isValueLegend ? this.valueRange.max : this.zRange.max;
22337 var step = new StepNumber_1(legendMin, legendMax, (legendMax - legendMin) / 5, true);
22338 step.start(true);
22339 var from;
22340 var to;
22341
22342 while (!step.end()) {
22343 y = bottom - (step.getCurrent() - legendMin) / (legendMax - legendMin) * height;
22344 from = new Point2d_1(left - gridLineLen, y);
22345 to = new Point2d_1(left, y);
22346
22347 this._line(ctx, from, to);
22348
22349 ctx.textAlign = 'right';
22350 ctx.textBaseline = 'middle';
22351 ctx.fillStyle = this.axisColor;
22352 ctx.fillText(step.getCurrent(), left - 2 * gridLineLen, y);
22353 step.next();
22354 }
22355
22356 ctx.textAlign = 'right';
22357 ctx.textBaseline = 'top';
22358 var label = this.legendLabel;
22359 ctx.fillText(label, right, bottom + this.margin);
22360};
22361/**
22362 * Redraw the filter
22363 */
22364
22365
22366Graph3d.prototype._redrawFilter = function () {
22367 var dataFilter = this.dataGroup.dataFilter;
22368 var filter = this.frame.filter;
22369 filter.innerHTML = '';
22370
22371 if (!dataFilter) {
22372 filter.slider = undefined;
22373 return;
22374 }
22375
22376 var options = {
22377 'visible': this.showAnimationControls
22378 };
22379 var slider = new Slider_1(filter, options);
22380 filter.slider = slider; // TODO: css here is not nice here...
22381
22382 filter.style.padding = '10px'; //this.frame.filter.style.backgroundColor = '#EFEFEF';
22383
22384 slider.setValues(dataFilter.values);
22385 slider.setPlayInterval(this.animationInterval); // create an event handler
22386
22387 var me = this;
22388
22389 var onchange = function onchange() {
22390 var dataFilter = me.dataGroup.dataFilter;
22391 var index = slider.getIndex();
22392 dataFilter.selectValue(index);
22393 me.dataPoints = dataFilter._getDataPoints();
22394 me.redraw();
22395 };
22396
22397 slider.setOnChangeCallback(onchange);
22398};
22399/**
22400 * Redraw the slider
22401 */
22402
22403
22404Graph3d.prototype._redrawSlider = function () {
22405 if (this.frame.filter.slider !== undefined) {
22406 this.frame.filter.slider.redraw();
22407 }
22408};
22409/**
22410 * Redraw common information
22411 */
22412
22413
22414Graph3d.prototype._redrawInfo = function () {
22415 var info = this.dataGroup.getInfo();
22416 if (info === undefined) return;
22417
22418 var ctx = this._getContext();
22419
22420 ctx.font = '14px arial'; // TODO: put in options
22421
22422 ctx.lineStyle = 'gray';
22423 ctx.fillStyle = 'gray';
22424 ctx.textAlign = 'left';
22425 ctx.textBaseline = 'top';
22426 var x = this.margin;
22427 var y = this.margin;
22428 ctx.fillText(info, x, y);
22429};
22430/**
22431 * Draw a line between 2d points 'from' and 'to'.
22432 *
22433 * If stroke style specified, set that as well.
22434 *
22435 * @param {CanvasRenderingContext2D} ctx
22436 * @param {vis.Point2d} from
22437 * @param {vis.Point2d} to
22438 * @param {string} [strokeStyle]
22439 * @private
22440 */
22441
22442
22443Graph3d.prototype._line = function (ctx, from, to, strokeStyle) {
22444 if (strokeStyle !== undefined) {
22445 ctx.strokeStyle = strokeStyle;
22446 }
22447
22448 ctx.beginPath();
22449 ctx.moveTo(from.x, from.y);
22450 ctx.lineTo(to.x, to.y);
22451 ctx.stroke();
22452};
22453/**
22454 *
22455 * @param {CanvasRenderingContext2D} ctx
22456 * @param {vis.Point3d} point3d
22457 * @param {string} text
22458 * @param {number} armAngle
22459 * @param {number} [yMargin=0]
22460 */
22461
22462
22463Graph3d.prototype.drawAxisLabelX = function (ctx, point3d, text, armAngle, yMargin) {
22464 if (yMargin === undefined) {
22465 yMargin = 0;
22466 }
22467
22468 var point2d = this._convert3Dto2D(point3d);
22469
22470 if (Math.cos(armAngle * 2) > 0) {
22471 ctx.textAlign = 'center';
22472 ctx.textBaseline = 'top';
22473 point2d.y += yMargin;
22474 } else if (Math.sin(armAngle * 2) < 0) {
22475 ctx.textAlign = 'right';
22476 ctx.textBaseline = 'middle';
22477 } else {
22478 ctx.textAlign = 'left';
22479 ctx.textBaseline = 'middle';
22480 }
22481
22482 ctx.fillStyle = this.axisColor;
22483 ctx.fillText(text, point2d.x, point2d.y);
22484};
22485/**
22486 *
22487 * @param {CanvasRenderingContext2D} ctx
22488 * @param {vis.Point3d} point3d
22489 * @param {string} text
22490 * @param {number} armAngle
22491 * @param {number} [yMargin=0]
22492 */
22493
22494
22495Graph3d.prototype.drawAxisLabelY = function (ctx, point3d, text, armAngle, yMargin) {
22496 if (yMargin === undefined) {
22497 yMargin = 0;
22498 }
22499
22500 var point2d = this._convert3Dto2D(point3d);
22501
22502 if (Math.cos(armAngle * 2) < 0) {
22503 ctx.textAlign = 'center';
22504 ctx.textBaseline = 'top';
22505 point2d.y += yMargin;
22506 } else if (Math.sin(armAngle * 2) > 0) {
22507 ctx.textAlign = 'right';
22508 ctx.textBaseline = 'middle';
22509 } else {
22510 ctx.textAlign = 'left';
22511 ctx.textBaseline = 'middle';
22512 }
22513
22514 ctx.fillStyle = this.axisColor;
22515 ctx.fillText(text, point2d.x, point2d.y);
22516};
22517/**
22518 *
22519 * @param {CanvasRenderingContext2D} ctx
22520 * @param {vis.Point3d} point3d
22521 * @param {string} text
22522 * @param {number} [offset=0]
22523 */
22524
22525
22526Graph3d.prototype.drawAxisLabelZ = function (ctx, point3d, text, offset) {
22527 if (offset === undefined) {
22528 offset = 0;
22529 }
22530
22531 var point2d = this._convert3Dto2D(point3d);
22532
22533 ctx.textAlign = 'right';
22534 ctx.textBaseline = 'middle';
22535 ctx.fillStyle = this.axisColor;
22536 ctx.fillText(text, point2d.x - offset, point2d.y);
22537};
22538/**
22539 *
22540 * @param {CanvasRenderingContext2D} ctx
22541 * @param {vis.Point3d} point3d
22542 * @param {string} text
22543 * @param {number} armAngle
22544 * @param {number} [yMargin=0]
22545 */
22546
22547
22548Graph3d.prototype.drawAxisLabelXRotate = function (ctx, point3d, text, armAngle, yMargin) {
22549 if (yMargin === undefined) {
22550 yMargin = 0;
22551 }
22552
22553 var point2d = this._convert3Dto2D(point3d);
22554
22555 if (Math.cos(armAngle * 2) > 0) {
22556 ctx.save();
22557 ctx.get;
22558 ctx.translate(point2d.x, point2d.y);
22559 ctx.rotate(Math.PI / 2);
22560 ctx.fillText(text, point2d.x / 100, point2d.y / 100);
22561 ctx.textAlign = 'center';
22562 ctx.textBaseline = 'top';
22563 point2d.y += yMargin;
22564 ctx.restore();
22565 } else if (Math.sin(armAngle * 2) < 0) {
22566 ctx.textAlign = 'right';
22567 ctx.textBaseline = 'middle';
22568 ctx.fillStyle = this.axisColor;
22569 ctx.fillText(text, point2d.x, point2d.y);
22570 } else {
22571 ctx.textAlign = 'left';
22572 ctx.textBaseline = 'middle';
22573 ctx.fillStyle = this.axisColor;
22574 ctx.fillText(text, point2d.x, point2d.y);
22575 }
22576};
22577/**
22578 *
22579 * @param {CanvasRenderingContext2D} ctx
22580 * @param {vis.Point3d} point3d
22581 * @param {string} text
22582 * @param {number} armAngle
22583 * @param {number} [yMargin=0]
22584 */
22585
22586
22587Graph3d.prototype.drawAxisLabelYRotate = function (ctx, point3d, text, armAngle, yMargin) {
22588 if (yMargin === undefined) {
22589 yMargin = 0;
22590 }
22591
22592 var point2d = this._convert3Dto2D(point3d);
22593
22594 if (Math.cos(armAngle * 2) < 0 && Math.sin(armAngle * 2) < 0) {
22595 ctx.save();
22596 ctx.get;
22597 ctx.translate(point2d.x, point2d.y);
22598 ctx.rotate(Math.PI / 2 * -1);
22599 ctx.fillText(text, point2d.x / 100, point2d.y / 100);
22600 ctx.textAlign = 'center';
22601 ctx.textBaseline = 'top';
22602 point2d.y += yMargin;
22603 ctx.restore();
22604 } else if (Math.cos(armAngle * 2) < 0) {
22605 ctx.save();
22606 ctx.get;
22607 ctx.translate(point2d.x, point2d.y);
22608 ctx.rotate(Math.PI / 2);
22609 ctx.fillText(text, point2d.x / 100, point2d.y / 100);
22610 ctx.textAlign = 'center';
22611 ctx.textBaseline = 'top';
22612 point2d.y += yMargin;
22613 ctx.restore();
22614 } else if (Math.sin(armAngle * 2) > 0) {
22615 ctx.textAlign = 'right';
22616 ctx.textBaseline = 'middle';
22617 ctx.fillStyle = this.axisColor;
22618 ctx.fillText(text, point2d.x, point2d.y);
22619 } else {
22620 ctx.textAlign = 'left';
22621 ctx.textBaseline = 'middle';
22622 ctx.fillStyle = this.axisColor;
22623 ctx.fillText(text, point2d.x, point2d.y);
22624 }
22625};
22626/**
22627 *
22628 * @param {CanvasRenderingContext2D} ctx
22629 * @param {vis.Point3d} point3d
22630 * @param {string} text
22631 * @param {number} [offset=0]
22632 */
22633
22634
22635Graph3d.prototype.drawAxisLabelZRotate = function (ctx, point3d, text, offset) {
22636 if (offset === undefined) {
22637 offset = 0;
22638 }
22639
22640 var point2d = this._convert3Dto2D(point3d);
22641
22642 ctx.textAlign = 'right';
22643 ctx.textBaseline = 'middle';
22644 ctx.fillStyle = this.axisColor;
22645 ctx.fillText(text, point2d.x - offset, point2d.y);
22646};
22647/**
22648
22649
22650/**
22651 * Draw a line between 2d points 'from' and 'to'.
22652 *
22653 * If stroke style specified, set that as well.
22654 *
22655 * @param {CanvasRenderingContext2D} ctx
22656 * @param {vis.Point2d} from
22657 * @param {vis.Point2d} to
22658 * @param {string} [strokeStyle]
22659 * @private
22660 */
22661
22662
22663Graph3d.prototype._line3d = function (ctx, from, to, strokeStyle) {
22664 var from2d = this._convert3Dto2D(from);
22665
22666 var to2d = this._convert3Dto2D(to);
22667
22668 this._line(ctx, from2d, to2d, strokeStyle);
22669};
22670/**
22671 * Redraw the axis
22672 */
22673
22674
22675Graph3d.prototype._redrawAxis = function () {
22676 var ctx = this._getContext(),
22677 from,
22678 to,
22679 step,
22680 prettyStep,
22681 text,
22682 xText,
22683 yText,
22684 zText,
22685 offset,
22686 xOffset,
22687 yOffset; // TODO: get the actual rendered style of the containerElement
22688 //ctx.font = this.containerElement.style.font;
22689 //ctx.font = 24 / this.camera.getArmLength() + 'px arial';
22690
22691
22692 ctx.font = this.axisFontSize / this.camera.getArmLength() + 'px ' + this.axisFontType; // calculate the length for the short grid lines
22693
22694 var gridLenX = 0.025 / this.scale.x;
22695 var gridLenY = 0.025 / this.scale.y;
22696 var textMargin = 5 / this.camera.getArmLength(); // px
22697
22698 var armAngle = this.camera.getArmRotation().horizontal;
22699 var armVector = new Point2d_1(Math.cos(armAngle), Math.sin(armAngle));
22700 var xRange = this.xRange;
22701 var yRange = this.yRange;
22702 var zRange = this.zRange;
22703 var point3d; // draw x-grid lines
22704
22705 ctx.lineWidth = 1;
22706 prettyStep = this.defaultXStep === undefined;
22707 step = new StepNumber_1(xRange.min, xRange.max, this.xStep, prettyStep);
22708 step.start(true);
22709
22710 while (!step.end()) {
22711 var x = step.getCurrent();
22712
22713 if (this.showGrid) {
22714 from = new Point3d_1(x, yRange.min, zRange.min);
22715 to = new Point3d_1(x, yRange.max, zRange.min);
22716
22717 this._line3d(ctx, from, to, this.gridColor);
22718 } else if (this.showXAxis) {
22719 from = new Point3d_1(x, yRange.min, zRange.min);
22720 to = new Point3d_1(x, yRange.min + gridLenX, zRange.min);
22721
22722 this._line3d(ctx, from, to, this.axisColor);
22723
22724 from = new Point3d_1(x, yRange.max, zRange.min);
22725 to = new Point3d_1(x, yRange.max - gridLenX, zRange.min);
22726
22727 this._line3d(ctx, from, to, this.axisColor);
22728 }
22729
22730 if (this.showXAxis) {
22731 yText = armVector.x > 0 ? yRange.min : yRange.max;
22732 point3d = new Point3d_1(x, yText, zRange.min);
22733 var msg = ' ' + this.xValueLabel(x) + ' ';
22734
22735 this._drawAxisLabelX.call(this, ctx, point3d, msg, armAngle, textMargin);
22736 }
22737
22738 step.next();
22739 } // draw y-grid lines
22740
22741
22742 ctx.lineWidth = 1;
22743 prettyStep = this.defaultYStep === undefined;
22744 step = new StepNumber_1(yRange.min, yRange.max, this.yStep, prettyStep);
22745 step.start(true);
22746
22747 while (!step.end()) {
22748 var y = step.getCurrent();
22749
22750 if (this.showGrid) {
22751 from = new Point3d_1(xRange.min, y, zRange.min);
22752 to = new Point3d_1(xRange.max, y, zRange.min);
22753
22754 this._line3d(ctx, from, to, this.gridColor);
22755 } else if (this.showYAxis) {
22756 from = new Point3d_1(xRange.min, y, zRange.min);
22757 to = new Point3d_1(xRange.min + gridLenY, y, zRange.min);
22758
22759 this._line3d(ctx, from, to, this.axisColor);
22760
22761 from = new Point3d_1(xRange.max, y, zRange.min);
22762 to = new Point3d_1(xRange.max - gridLenY, y, zRange.min);
22763
22764 this._line3d(ctx, from, to, this.axisColor);
22765 }
22766
22767 if (this.showYAxis) {
22768 xText = armVector.y > 0 ? xRange.min : xRange.max;
22769 point3d = new Point3d_1(xText, y, zRange.min);
22770
22771 var _msg = ' ' + this.yValueLabel(y) + ' ';
22772
22773 this._drawAxisLabelY.call(this, ctx, point3d, _msg, armAngle, textMargin);
22774 }
22775
22776 step.next();
22777 } // draw z-grid lines and axis
22778
22779
22780 if (this.showZAxis) {
22781 ctx.lineWidth = 1;
22782 prettyStep = this.defaultZStep === undefined;
22783 step = new StepNumber_1(zRange.min, zRange.max, this.zStep, prettyStep);
22784 step.start(true);
22785 xText = armVector.x > 0 ? xRange.min : xRange.max;
22786 yText = armVector.y < 0 ? yRange.min : yRange.max;
22787
22788 while (!step.end()) {
22789 var z = step.getCurrent(); // TODO: make z-grid lines really 3d?
22790
22791 var from3d = new Point3d_1(xText, yText, z);
22792
22793 var from2d = this._convert3Dto2D(from3d);
22794
22795 to = new Point2d_1(from2d.x - textMargin, from2d.y);
22796
22797 this._line(ctx, from2d, to, this.axisColor);
22798
22799 var _msg2 = this.zValueLabel(z) + ' ';
22800
22801 this._drawAxisLabelZ.call(this, ctx, from3d, _msg2, 5);
22802
22803 step.next();
22804 }
22805
22806 ctx.lineWidth = 1;
22807 from = new Point3d_1(xText, yText, zRange.min);
22808 to = new Point3d_1(xText, yText, zRange.max);
22809
22810 this._line3d(ctx, from, to, this.axisColor);
22811 } // draw x-axis
22812
22813
22814 if (this.showXAxis) {
22815 var xMin2d;
22816 var xMax2d;
22817 ctx.lineWidth = 1; // line at yMin
22818
22819 xMin2d = new Point3d_1(xRange.min, yRange.min, zRange.min);
22820 xMax2d = new Point3d_1(xRange.max, yRange.min, zRange.min);
22821
22822 this._line3d(ctx, xMin2d, xMax2d, this.axisColor); // line at ymax
22823
22824
22825 xMin2d = new Point3d_1(xRange.min, yRange.max, zRange.min);
22826 xMax2d = new Point3d_1(xRange.max, yRange.max, zRange.min);
22827
22828 this._line3d(ctx, xMin2d, xMax2d, this.axisColor);
22829 } // draw y-axis
22830
22831
22832 if (this.showYAxis) {
22833 ctx.lineWidth = 1; // line at xMin
22834
22835 from = new Point3d_1(xRange.min, yRange.min, zRange.min);
22836 to = new Point3d_1(xRange.min, yRange.max, zRange.min);
22837
22838 this._line3d(ctx, from, to, this.axisColor); // line at xMax
22839
22840
22841 from = new Point3d_1(xRange.max, yRange.min, zRange.min);
22842 to = new Point3d_1(xRange.max, yRange.max, zRange.min);
22843
22844 this._line3d(ctx, from, to, this.axisColor);
22845 } // draw x-label
22846
22847
22848 var xLabel = this.xLabel;
22849
22850 if (xLabel.length > 0 && this.showXAxis) {
22851 yOffset = 0.1 / this.scale.y;
22852 xText = (xRange.max + 3 * xRange.min) / 4;
22853 yText = armVector.x > 0 ? yRange.min - yOffset : yRange.max + yOffset;
22854 text = new Point3d_1(xText, yText, zRange.min);
22855 this.drawAxisLabelX(ctx, text, xLabel, armAngle);
22856 } // draw y-label
22857
22858
22859 var yLabel = this.yLabel;
22860
22861 if (yLabel.length > 0 && this.showYAxis) {
22862 xOffset = 0.1 / this.scale.x;
22863 xText = armVector.y > 0 ? xRange.min - xOffset : xRange.max + xOffset;
22864 yText = (yRange.max + 3 * yRange.min) / 4;
22865 text = new Point3d_1(xText, yText, zRange.min);
22866 this.drawAxisLabelY(ctx, text, yLabel, armAngle);
22867 } // draw z-label
22868
22869
22870 var zLabel = this.zLabel;
22871
22872 if (zLabel.length > 0 && this.showZAxis) {
22873 offset = 30; // pixels. // TODO: relate to the max width of the values on the z axis?
22874
22875 xText = armVector.x > 0 ? xRange.min : xRange.max;
22876 yText = armVector.y < 0 ? yRange.min : yRange.max;
22877 zText = (zRange.max + 3 * zRange.min) / 4;
22878 text = new Point3d_1(xText, yText, zText);
22879 this.drawAxisLabelZ(ctx, text, zLabel, offset);
22880 }
22881};
22882/**
22883 * Calculate the color based on the given value.
22884 * @param {number} H Hue, a value be between 0 and 360
22885 * @param {number} S Saturation, a value between 0 and 1
22886 * @param {number} V Value, a value between 0 and 1
22887 * @returns {string}
22888 * @private
22889 */
22890
22891
22892Graph3d.prototype._hsv2rgb = function (H, S, V) {
22893 var R, G, B, C, Hi, X;
22894 C = V * S;
22895 Hi = Math.floor(H / 60); // hi = 0,1,2,3,4,5
22896
22897 X = C * (1 - Math.abs(H / 60 % 2 - 1));
22898
22899 switch (Hi) {
22900 case 0:
22901 R = C;
22902 G = X;
22903 B = 0;
22904 break;
22905
22906 case 1:
22907 R = X;
22908 G = C;
22909 B = 0;
22910 break;
22911
22912 case 2:
22913 R = 0;
22914 G = C;
22915 B = X;
22916 break;
22917
22918 case 3:
22919 R = 0;
22920 G = X;
22921 B = C;
22922 break;
22923
22924 case 4:
22925 R = X;
22926 G = 0;
22927 B = C;
22928 break;
22929
22930 case 5:
22931 R = C;
22932 G = 0;
22933 B = X;
22934 break;
22935
22936 default:
22937 R = 0;
22938 G = 0;
22939 B = 0;
22940 break;
22941 }
22942
22943 return 'RGB(' + parseInt(R * 255) + ',' + parseInt(G * 255) + ',' + parseInt(B * 255) + ')';
22944};
22945/**
22946 *
22947 * @param {vis.Point3d} point
22948 * @returns {*}
22949 * @private
22950 */
22951
22952
22953Graph3d.prototype._getStrokeWidth = function (point) {
22954 if (point !== undefined) {
22955 if (this.showPerspective) {
22956 return 1 / -point.trans.z * this.dataColor.strokeWidth;
22957 } else {
22958 return -(this.eye.z / this.camera.getArmLength()) * this.dataColor.strokeWidth;
22959 }
22960 }
22961
22962 return this.dataColor.strokeWidth;
22963}; // -----------------------------------------------------------------------------
22964// Drawing primitives for the graphs
22965// -----------------------------------------------------------------------------
22966
22967/**
22968 * Draw a bar element in the view with the given properties.
22969 *
22970 * @param {CanvasRenderingContext2D} ctx
22971 * @param {Object} point
22972 * @param {number} xWidth
22973 * @param {number} yWidth
22974 * @param {string} color
22975 * @param {string} borderColor
22976 * @private
22977 */
22978
22979
22980Graph3d.prototype._redrawBar = function (ctx, point, xWidth, yWidth, color, borderColor) {
22981 var surface; // calculate all corner points
22982
22983 var me = this;
22984 var point3d = point.point;
22985 var zMin = this.zRange.min;
22986 var top = [{
22987 point: new Point3d_1(point3d.x - xWidth, point3d.y - yWidth, point3d.z)
22988 }, {
22989 point: new Point3d_1(point3d.x + xWidth, point3d.y - yWidth, point3d.z)
22990 }, {
22991 point: new Point3d_1(point3d.x + xWidth, point3d.y + yWidth, point3d.z)
22992 }, {
22993 point: new Point3d_1(point3d.x - xWidth, point3d.y + yWidth, point3d.z)
22994 }];
22995 var bottom = [{
22996 point: new Point3d_1(point3d.x - xWidth, point3d.y - yWidth, zMin)
22997 }, {
22998 point: new Point3d_1(point3d.x + xWidth, point3d.y - yWidth, zMin)
22999 }, {
23000 point: new Point3d_1(point3d.x + xWidth, point3d.y + yWidth, zMin)
23001 }, {
23002 point: new Point3d_1(point3d.x - xWidth, point3d.y + yWidth, zMin)
23003 }]; // calculate screen location of the points
23004
23005 top.forEach(function (obj) {
23006 obj.screen = me._convert3Dto2D(obj.point);
23007 });
23008 bottom.forEach(function (obj) {
23009 obj.screen = me._convert3Dto2D(obj.point);
23010 }); // create five sides, calculate both corner points and center points
23011
23012 var surfaces = [{
23013 corners: top,
23014 center: Point3d_1.avg(bottom[0].point, bottom[2].point)
23015 }, {
23016 corners: [top[0], top[1], bottom[1], bottom[0]],
23017 center: Point3d_1.avg(bottom[1].point, bottom[0].point)
23018 }, {
23019 corners: [top[1], top[2], bottom[2], bottom[1]],
23020 center: Point3d_1.avg(bottom[2].point, bottom[1].point)
23021 }, {
23022 corners: [top[2], top[3], bottom[3], bottom[2]],
23023 center: Point3d_1.avg(bottom[3].point, bottom[2].point)
23024 }, {
23025 corners: [top[3], top[0], bottom[0], bottom[3]],
23026 center: Point3d_1.avg(bottom[0].point, bottom[3].point)
23027 }];
23028 point.surfaces = surfaces; // calculate the distance of each of the surface centers to the camera
23029
23030 for (var j = 0; j < surfaces.length; j++) {
23031 surface = surfaces[j];
23032
23033 var transCenter = this._convertPointToTranslation(surface.center);
23034
23035 surface.dist = this.showPerspective ? transCenter.length() : -transCenter.z; // TODO: this dept calculation doesn't work 100% of the cases due to perspective,
23036 // but the current solution is fast/simple and works in 99.9% of all cases
23037 // the issue is visible in example 14, with graph.setCameraPosition({horizontal: 2.97, vertical: 0.5, distance: 0.9})
23038 } // order the surfaces by their (translated) depth
23039
23040
23041 surfaces.sort(function (a, b) {
23042 var diff = b.dist - a.dist;
23043 if (diff) return diff; // if equal depth, sort the top surface last
23044
23045 if (a.corners === top) return 1;
23046 if (b.corners === top) return -1; // both are equal
23047
23048 return 0;
23049 }); // draw the ordered surfaces
23050
23051 ctx.lineWidth = this._getStrokeWidth(point);
23052 ctx.strokeStyle = borderColor;
23053 ctx.fillStyle = color; // NOTE: we start at j=2 instead of j=0 as we don't need to draw the two surfaces at the backside
23054
23055 for (var _j = 2; _j < surfaces.length; _j++) {
23056 surface = surfaces[_j];
23057
23058 this._polygon(ctx, surface.corners);
23059 }
23060};
23061/**
23062 * Draw a polygon using the passed points and fill it with the passed style and stroke.
23063 *
23064 * @param {CanvasRenderingContext2D} ctx
23065 * @param {Array.<vis.Point3d>} points an array of points.
23066 * @param {string} [fillStyle] the fill style to set
23067 * @param {string} [strokeStyle] the stroke style to set
23068 */
23069
23070
23071Graph3d.prototype._polygon = function (ctx, points, fillStyle, strokeStyle) {
23072 if (points.length < 2) {
23073 return;
23074 }
23075
23076 if (fillStyle !== undefined) {
23077 ctx.fillStyle = fillStyle;
23078 }
23079
23080 if (strokeStyle !== undefined) {
23081 ctx.strokeStyle = strokeStyle;
23082 }
23083
23084 ctx.beginPath();
23085 ctx.moveTo(points[0].screen.x, points[0].screen.y);
23086
23087 for (var i = 1; i < points.length; ++i) {
23088 var point = points[i];
23089 ctx.lineTo(point.screen.x, point.screen.y);
23090 }
23091
23092 ctx.closePath();
23093 ctx.fill();
23094 ctx.stroke(); // TODO: only draw stroke when strokeWidth > 0
23095};
23096/**
23097 * @param {CanvasRenderingContext2D} ctx
23098 * @param {object} point
23099 * @param {string} color
23100 * @param {string} borderColor
23101 * @param {number} [size=this._dotSize()]
23102 * @private
23103 */
23104
23105
23106Graph3d.prototype._drawCircle = function (ctx, point, color, borderColor, size) {
23107 var radius = this._calcRadius(point, size);
23108
23109 ctx.lineWidth = this._getStrokeWidth(point);
23110 ctx.strokeStyle = borderColor;
23111 ctx.fillStyle = color;
23112 ctx.beginPath();
23113 ctx.arc(point.screen.x, point.screen.y, radius, 0, Math.PI * 2, true);
23114 ctx.fill();
23115 ctx.stroke();
23116};
23117/**
23118 * Determine the colors for the 'regular' graph styles.
23119 *
23120 * @param {object} point
23121 * @returns {{fill, border}}
23122 * @private
23123 */
23124
23125
23126Graph3d.prototype._getColorsRegular = function (point) {
23127 // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
23128 var hue = (1 - (point.point.z - this.zRange.min) * this.scale.z / this.verticalRatio) * 240;
23129
23130 var color = this._hsv2rgb(hue, 1, 1);
23131
23132 var borderColor = this._hsv2rgb(hue, 1, 0.8);
23133
23134 return {
23135 fill: color,
23136 border: borderColor
23137 };
23138};
23139/**
23140 * Get the colors for the 'color' graph styles.
23141 * These styles are currently: 'bar-color' and 'dot-color'
23142 * Color may be set as a string representation of HTML color, like #ff00ff,
23143 * or calculated from a number, for example, distance from this point
23144 * The first option is useful when we have some pre-given legend, to which we have to adjust ourselves
23145 * The second option is useful when we are interested in automatically setting the color, from some value,
23146 * using some color scale
23147 * @param {object} point
23148 * @returns {{fill: *, border: *}}
23149 * @private
23150 */
23151
23152
23153Graph3d.prototype._getColorsColor = function (point) {
23154 // calculate the color based on the value
23155 var color, borderColor, pointStyle;
23156
23157 if (point && point.point && point.point.data && point.point.data.style) {
23158 pointStyle = point.point.data.style;
23159 }
23160
23161 if (pointStyle && _typeof$1(pointStyle) === 'object' && pointStyle.fill && pointStyle.stroke) {
23162 return {
23163 fill: pointStyle.fill,
23164 border: pointStyle.stroke
23165 };
23166 }
23167
23168 if (typeof point.point.value === "string") {
23169 color = point.point.value;
23170 borderColor = point.point.value;
23171 } else {
23172 var hue = (1 - (point.point.value - this.valueRange.min) * this.scale.value) * 240;
23173 color = this._hsv2rgb(hue, 1, 1);
23174 borderColor = this._hsv2rgb(hue, 1, 0.8);
23175 }
23176
23177 return {
23178 fill: color,
23179 border: borderColor
23180 };
23181};
23182/**
23183 * Get the colors for the 'size' graph styles.
23184 * These styles are currently: 'bar-size' and 'dot-size'
23185 *
23186 * @returns {{fill: *, border: (string|colorOptions.stroke|{string, undefined}|string|colorOptions.stroke|{string}|*)}}
23187 * @private
23188 */
23189
23190
23191Graph3d.prototype._getColorsSize = function () {
23192 return {
23193 fill: this.dataColor.fill,
23194 border: this.dataColor.stroke
23195 };
23196};
23197/**
23198 * Determine the size of a point on-screen, as determined by the
23199 * distance to the camera.
23200 *
23201 * @param {Object} point
23202 * @param {number} [size=this._dotSize()] the size that needs to be translated to screen coordinates.
23203 * optional; if not passed, use the default point size.
23204 * @returns {number}
23205 * @private
23206 */
23207
23208
23209Graph3d.prototype._calcRadius = function (point, size) {
23210 if (size === undefined) {
23211 size = this._dotSize();
23212 }
23213
23214 var radius;
23215
23216 if (this.showPerspective) {
23217 radius = size / -point.trans.z;
23218 } else {
23219 radius = size * -(this.eye.z / this.camera.getArmLength());
23220 }
23221
23222 if (radius < 0) {
23223 radius = 0;
23224 }
23225
23226 return radius;
23227}; // -----------------------------------------------------------------------------
23228// Methods for drawing points per graph style.
23229// -----------------------------------------------------------------------------
23230
23231/**
23232 * Draw single datapoint for graph style 'bar'.
23233 *
23234 * @param {CanvasRenderingContext2D} ctx
23235 * @param {Object} point
23236 * @private
23237 */
23238
23239
23240Graph3d.prototype._redrawBarGraphPoint = function (ctx, point) {
23241 var xWidth = this.xBarWidth / 2;
23242 var yWidth = this.yBarWidth / 2;
23243
23244 var colors = this._getColorsRegular(point);
23245
23246 this._redrawBar(ctx, point, xWidth, yWidth, colors.fill, colors.border);
23247};
23248/**
23249 * Draw single datapoint for graph style 'bar-color'.
23250 *
23251 * @param {CanvasRenderingContext2D} ctx
23252 * @param {Object} point
23253 * @private
23254 */
23255
23256
23257Graph3d.prototype._redrawBarColorGraphPoint = function (ctx, point) {
23258 var xWidth = this.xBarWidth / 2;
23259 var yWidth = this.yBarWidth / 2;
23260
23261 var colors = this._getColorsColor(point);
23262
23263 this._redrawBar(ctx, point, xWidth, yWidth, colors.fill, colors.border);
23264};
23265/**
23266 * Draw single datapoint for graph style 'bar-size'.
23267 *
23268 * @param {CanvasRenderingContext2D} ctx
23269 * @param {Object} point
23270 * @private
23271 */
23272
23273
23274Graph3d.prototype._redrawBarSizeGraphPoint = function (ctx, point) {
23275 // calculate size for the bar
23276 var fraction = (point.point.value - this.valueRange.min) / this.valueRange.range();
23277 var xWidth = this.xBarWidth / 2 * (fraction * 0.8 + 0.2);
23278 var yWidth = this.yBarWidth / 2 * (fraction * 0.8 + 0.2);
23279
23280 var colors = this._getColorsSize();
23281
23282 this._redrawBar(ctx, point, xWidth, yWidth, colors.fill, colors.border);
23283};
23284/**
23285 * Draw single datapoint for graph style 'dot'.
23286 *
23287 * @param {CanvasRenderingContext2D} ctx
23288 * @param {Object} point
23289 * @private
23290 */
23291
23292
23293Graph3d.prototype._redrawDotGraphPoint = function (ctx, point) {
23294 var colors = this._getColorsRegular(point);
23295
23296 this._drawCircle(ctx, point, colors.fill, colors.border);
23297};
23298/**
23299 * Draw single datapoint for graph style 'dot-line'.
23300 *
23301 * @param {CanvasRenderingContext2D} ctx
23302 * @param {Object} point
23303 * @private
23304 */
23305
23306
23307Graph3d.prototype._redrawDotLineGraphPoint = function (ctx, point) {
23308 // draw a vertical line from the XY-plane to the graph value
23309 var from = this._convert3Dto2D(point.bottom);
23310
23311 ctx.lineWidth = 1;
23312
23313 this._line(ctx, from, point.screen, this.gridColor);
23314
23315 this._redrawDotGraphPoint(ctx, point);
23316};
23317/**
23318 * Draw single datapoint for graph style 'dot-color'.
23319 *
23320 * @param {CanvasRenderingContext2D} ctx
23321 * @param {Object} point
23322 * @private
23323 */
23324
23325
23326Graph3d.prototype._redrawDotColorGraphPoint = function (ctx, point) {
23327 var colors = this._getColorsColor(point);
23328
23329 this._drawCircle(ctx, point, colors.fill, colors.border);
23330};
23331/**
23332 * Draw single datapoint for graph style 'dot-size'.
23333 *
23334 * @param {CanvasRenderingContext2D} ctx
23335 * @param {Object} point
23336 * @private
23337 */
23338
23339
23340Graph3d.prototype._redrawDotSizeGraphPoint = function (ctx, point) {
23341 var dotSize = this._dotSize();
23342
23343 var fraction = (point.point.value - this.valueRange.min) / this.valueRange.range();
23344 var sizeMin = dotSize * this.dotSizeMinFraction;
23345 var sizeRange = dotSize * this.dotSizeMaxFraction - sizeMin;
23346 var size = sizeMin + sizeRange * fraction;
23347
23348 var colors = this._getColorsSize();
23349
23350 this._drawCircle(ctx, point, colors.fill, colors.border, size);
23351};
23352/**
23353 * Draw single datapoint for graph style 'surface'.
23354 *
23355 * @param {CanvasRenderingContext2D} ctx
23356 * @param {Object} point
23357 * @private
23358 */
23359
23360
23361Graph3d.prototype._redrawSurfaceGraphPoint = function (ctx, point) {
23362 var right = point.pointRight;
23363 var top = point.pointTop;
23364 var cross = point.pointCross;
23365
23366 if (point === undefined || right === undefined || top === undefined || cross === undefined) {
23367 return;
23368 }
23369
23370 var topSideVisible = true;
23371 var fillStyle;
23372 var strokeStyle;
23373
23374 if (this.showGrayBottom || this.showShadow) {
23375 // calculate the cross product of the two vectors from center
23376 // to left and right, in order to know whether we are looking at the
23377 // bottom or at the top side. We can also use the cross product
23378 // for calculating light intensity
23379 var aDiff = Point3d_1.subtract(cross.trans, point.trans);
23380 var bDiff = Point3d_1.subtract(top.trans, right.trans);
23381 var crossproduct = Point3d_1.crossProduct(aDiff, bDiff);
23382 var len = crossproduct.length(); // FIXME: there is a bug with determining the surface side (shadow or colored)
23383
23384 topSideVisible = crossproduct.z > 0;
23385 }
23386
23387 if (topSideVisible) {
23388 // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
23389 var zAvg = (point.point.z + right.point.z + top.point.z + cross.point.z) / 4;
23390 var h = (1 - (zAvg - this.zRange.min) * this.scale.z / this.verticalRatio) * 240;
23391 var s = 1; // saturation
23392
23393 var v;
23394
23395 if (this.showShadow) {
23396 v = Math.min(1 + crossproduct.x / len / 2, 1); // value. TODO: scale
23397
23398 fillStyle = this._hsv2rgb(h, s, v);
23399 strokeStyle = fillStyle;
23400 } else {
23401 v = 1;
23402 fillStyle = this._hsv2rgb(h, s, v);
23403 strokeStyle = this.axisColor; // TODO: should be customizable
23404 }
23405 } else {
23406 fillStyle = 'gray';
23407 strokeStyle = this.axisColor;
23408 }
23409
23410 ctx.lineWidth = this._getStrokeWidth(point); // TODO: only draw stroke when strokeWidth > 0
23411
23412 var points = [point, right, cross, top];
23413
23414 this._polygon(ctx, points, fillStyle, strokeStyle);
23415};
23416/**
23417 * Helper method for _redrawGridGraphPoint()
23418 *
23419 * @param {CanvasRenderingContext2D} ctx
23420 * @param {Object} from
23421 * @param {Object} to
23422 * @private
23423 */
23424
23425
23426Graph3d.prototype._drawGridLine = function (ctx, from, to) {
23427 if (from === undefined || to === undefined) {
23428 return;
23429 } // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
23430
23431
23432 var zAvg = (from.point.z + to.point.z) / 2;
23433 var h = (1 - (zAvg - this.zRange.min) * this.scale.z / this.verticalRatio) * 240;
23434 ctx.lineWidth = this._getStrokeWidth(from) * 2;
23435 ctx.strokeStyle = this._hsv2rgb(h, 1, 1);
23436
23437 this._line(ctx, from.screen, to.screen);
23438};
23439/**
23440 * Draw single datapoint for graph style 'Grid'.
23441 *
23442 * @param {CanvasRenderingContext2D} ctx
23443 * @param {Object} point
23444 * @private
23445 */
23446
23447
23448Graph3d.prototype._redrawGridGraphPoint = function (ctx, point) {
23449 this._drawGridLine(ctx, point, point.pointRight);
23450
23451 this._drawGridLine(ctx, point, point.pointTop);
23452};
23453/**
23454 * Draw single datapoint for graph style 'line'.
23455 *
23456 * @param {CanvasRenderingContext2D} ctx
23457 * @param {Object} point
23458 * @private
23459 */
23460
23461
23462Graph3d.prototype._redrawLineGraphPoint = function (ctx, point) {
23463 if (point.pointNext === undefined) {
23464 return;
23465 }
23466
23467 ctx.lineWidth = this._getStrokeWidth(point);
23468 ctx.strokeStyle = this.dataColor.stroke;
23469
23470 this._line(ctx, point.screen, point.pointNext.screen);
23471};
23472/**
23473 * Draw all datapoints for currently selected graph style.
23474 *
23475 */
23476
23477
23478Graph3d.prototype._redrawDataGraph = function () {
23479 var ctx = this._getContext();
23480
23481 var i;
23482 if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception?
23483
23484 this._calcTranslations(this.dataPoints);
23485
23486 for (i = 0; i < this.dataPoints.length; i++) {
23487 var point = this.dataPoints[i]; // Using call() ensures that the correct context is used
23488
23489 this._pointDrawingMethod.call(this, ctx, point);
23490 }
23491}; // -----------------------------------------------------------------------------
23492// End methods for drawing points per graph style.
23493// -----------------------------------------------------------------------------
23494
23495/**
23496 * Store startX, startY and startOffset for mouse operations
23497 *
23498 * @param {Event} event The event that occurred
23499 */
23500
23501
23502Graph3d.prototype._storeMousePosition = function (event) {
23503 // get mouse position (different code for IE and all other browsers)
23504 this.startMouseX = getMouseX(event);
23505 this.startMouseY = getMouseY(event);
23506 this._startCameraOffset = this.camera.getOffset();
23507};
23508/**
23509 * Start a moving operation inside the provided parent element
23510 * @param {Event} event The event that occurred (required for
23511 * retrieving the mouse position)
23512 */
23513
23514
23515Graph3d.prototype._onMouseDown = function (event) {
23516 event = event || window.event; // check if mouse is still down (may be up when focus is lost for example
23517 // in an iframe)
23518
23519 if (this.leftButtonDown) {
23520 this._onMouseUp(event);
23521 } // only react on left mouse button down
23522
23523
23524 this.leftButtonDown = event.which ? event.which === 1 : event.button === 1;
23525 if (!this.leftButtonDown && !this.touchDown) return;
23526
23527 this._storeMousePosition(event);
23528
23529 this.startStart = new Date(this.start);
23530 this.startEnd = new Date(this.end);
23531 this.startArmRotation = this.camera.getArmRotation();
23532 this.frame.style.cursor = 'move'; // add event listeners to handle moving the contents
23533 // we store the function onmousemove and onmouseup in the graph, so we can
23534 // remove the eventlisteners lateron in the function mouseUp()
23535
23536 var me = this;
23537
23538 this.onmousemove = function (event) {
23539 me._onMouseMove(event);
23540 };
23541
23542 this.onmouseup = function (event) {
23543 me._onMouseUp(event);
23544 };
23545
23546 util.addEventListener(document, 'mousemove', me.onmousemove);
23547 util.addEventListener(document, 'mouseup', me.onmouseup);
23548 util.preventDefault(event);
23549};
23550/**
23551 * Perform moving operating.
23552 * This function activated from within the funcion Graph.mouseDown().
23553 * @param {Event} event Well, eehh, the event
23554 */
23555
23556
23557Graph3d.prototype._onMouseMove = function (event) {
23558 this.moving = true;
23559 event = event || window.event; // calculate change in mouse position
23560
23561 var diffX = parseFloat(getMouseX(event)) - this.startMouseX;
23562 var diffY = parseFloat(getMouseY(event)) - this.startMouseY; // move with ctrl or rotate by other
23563
23564 if (event && event.ctrlKey === true) {
23565 // calculate change in mouse position
23566 var scaleX = this.frame.clientWidth * 0.5;
23567 var scaleY = this.frame.clientHeight * 0.5;
23568 var offXNew = (this._startCameraOffset.x || 0) - diffX / scaleX * this.camera.armLength * 0.8;
23569 var offYNew = (this._startCameraOffset.y || 0) + diffY / scaleY * this.camera.armLength * 0.8;
23570 this.camera.setOffset(offXNew, offYNew);
23571
23572 this._storeMousePosition(event);
23573 } else {
23574 var horizontalNew = this.startArmRotation.horizontal + diffX / 200;
23575 var verticalNew = this.startArmRotation.vertical + diffY / 200;
23576 var snapAngle = 4; // degrees
23577
23578 var snapValue = Math.sin(snapAngle / 360 * 2 * Math.PI); // snap horizontally to nice angles at 0pi, 0.5pi, 1pi, 1.5pi, etc...
23579 // the -0.001 is to take care that the vertical axis is always drawn at the left front corner
23580
23581 if (Math.abs(Math.sin(horizontalNew)) < snapValue) {
23582 horizontalNew = Math.round(horizontalNew / Math.PI) * Math.PI - 0.001;
23583 }
23584
23585 if (Math.abs(Math.cos(horizontalNew)) < snapValue) {
23586 horizontalNew = (Math.round(horizontalNew / Math.PI - 0.5) + 0.5) * Math.PI - 0.001;
23587 } // snap vertically to nice angles
23588
23589
23590 if (Math.abs(Math.sin(verticalNew)) < snapValue) {
23591 verticalNew = Math.round(verticalNew / Math.PI) * Math.PI;
23592 }
23593
23594 if (Math.abs(Math.cos(verticalNew)) < snapValue) {
23595 verticalNew = (Math.round(verticalNew / Math.PI - 0.5) + 0.5) * Math.PI;
23596 }
23597
23598 this.camera.setArmRotation(horizontalNew, verticalNew);
23599 }
23600
23601 this.redraw(); // fire a cameraPositionChange event
23602
23603 var parameters = this.getCameraPosition();
23604 this.emit('cameraPositionChange', parameters);
23605 util.preventDefault(event);
23606};
23607/**
23608 * Stop moving operating.
23609 * This function activated from within the funcion Graph.mouseDown().
23610 * @param {Event} event The event
23611 */
23612
23613
23614Graph3d.prototype._onMouseUp = function (event) {
23615 this.frame.style.cursor = 'auto';
23616 this.leftButtonDown = false; // remove event listeners here
23617
23618 util.removeEventListener(document, 'mousemove', this.onmousemove);
23619 util.removeEventListener(document, 'mouseup', this.onmouseup);
23620 util.preventDefault(event);
23621};
23622/**
23623 * @param {Event} event The event
23624 */
23625
23626
23627Graph3d.prototype._onClick = function (event) {
23628 if (!this.onclick_callback) return;
23629
23630 if (!this.moving) {
23631 var boundingRect = this.frame.getBoundingClientRect();
23632 var mouseX = getMouseX(event) - boundingRect.left;
23633 var mouseY = getMouseY(event) - boundingRect.top;
23634
23635 var dataPoint = this._dataPointFromXY(mouseX, mouseY);
23636
23637 if (dataPoint) this.onclick_callback(dataPoint.point.data);
23638 } else {
23639 // disable onclick callback, if it came immediately after rotate/pan
23640 this.moving = false;
23641 }
23642
23643 util.preventDefault(event);
23644};
23645/**
23646 * After having moved the mouse, a tooltip should pop up when the mouse is resting on a data point
23647 * @param {Event} event A mouse move event
23648 */
23649
23650
23651Graph3d.prototype._onTooltip = function (event) {
23652 var delay = this.tooltipDelay; // ms
23653
23654 var boundingRect = this.frame.getBoundingClientRect();
23655 var mouseX = getMouseX(event) - boundingRect.left;
23656 var mouseY = getMouseY(event) - boundingRect.top;
23657
23658 if (!this.showTooltip) {
23659 return;
23660 }
23661
23662 if (this.tooltipTimeout) {
23663 clearTimeout(this.tooltipTimeout);
23664 } // (delayed) display of a tooltip only if no mouse button is down
23665
23666
23667 if (this.leftButtonDown) {
23668 this._hideTooltip();
23669
23670 return;
23671 }
23672
23673 if (this.tooltip && this.tooltip.dataPoint) {
23674 // tooltip is currently visible
23675 var dataPoint = this._dataPointFromXY(mouseX, mouseY);
23676
23677 if (dataPoint !== this.tooltip.dataPoint) {
23678 // datapoint changed
23679 if (dataPoint) {
23680 this._showTooltip(dataPoint);
23681 } else {
23682 this._hideTooltip();
23683 }
23684 }
23685 } else {
23686 // tooltip is currently not visible
23687 var me = this;
23688 this.tooltipTimeout = setTimeout(function () {
23689 me.tooltipTimeout = null; // show a tooltip if we have a data point
23690
23691 var dataPoint = me._dataPointFromXY(mouseX, mouseY);
23692
23693 if (dataPoint) {
23694 me._showTooltip(dataPoint);
23695 }
23696 }, delay);
23697 }
23698};
23699/**
23700 * Event handler for touchstart event on mobile devices
23701 * @param {Event} event The event
23702 */
23703
23704
23705Graph3d.prototype._onTouchStart = function (event) {
23706 this.touchDown = true;
23707 var me = this;
23708
23709 this.ontouchmove = function (event) {
23710 me._onTouchMove(event);
23711 };
23712
23713 this.ontouchend = function (event) {
23714 me._onTouchEnd(event);
23715 };
23716
23717 util.addEventListener(document, 'touchmove', me.ontouchmove);
23718 util.addEventListener(document, 'touchend', me.ontouchend);
23719
23720 this._onMouseDown(event);
23721};
23722/**
23723 * Event handler for touchmove event on mobile devices
23724 * @param {Event} event The event
23725 */
23726
23727
23728Graph3d.prototype._onTouchMove = function (event) {
23729 this._onMouseMove(event);
23730};
23731/**
23732 * Event handler for touchend event on mobile devices
23733 * @param {Event} event The event
23734 */
23735
23736
23737Graph3d.prototype._onTouchEnd = function (event) {
23738 this.touchDown = false;
23739 util.removeEventListener(document, 'touchmove', this.ontouchmove);
23740 util.removeEventListener(document, 'touchend', this.ontouchend);
23741
23742 this._onMouseUp(event);
23743};
23744/**
23745 * Event handler for mouse wheel event, used to zoom the graph
23746 * Code from http://adomas.org/javascript-mouse-wheel/
23747 * @param {Event} event The event
23748 */
23749
23750
23751Graph3d.prototype._onWheel = function (event) {
23752 if (!event)
23753 /* For IE. */
23754 event = window.event;
23755
23756 if (this.zoomable && (!this.ctrlToZoom || event.ctrlKey)) {
23757 // retrieve delta
23758 var delta = 0;
23759
23760 if (event.wheelDelta) {
23761 /* IE/Opera. */
23762 delta = event.wheelDelta / 120;
23763 } else if (event.detail) {
23764 /* Mozilla case. */
23765 // In Mozilla, sign of delta is different than in IE.
23766 // Also, delta is multiple of 3.
23767 delta = -event.detail / 3;
23768 } // If delta is nonzero, handle it.
23769 // Basically, delta is now positive if wheel was scrolled up,
23770 // and negative, if wheel was scrolled down.
23771
23772
23773 if (delta) {
23774 var oldLength = this.camera.getArmLength();
23775 var newLength = oldLength * (1 - delta / 10);
23776 this.camera.setArmLength(newLength);
23777 this.redraw();
23778
23779 this._hideTooltip();
23780 } // fire a cameraPositionChange event
23781
23782
23783 var parameters = this.getCameraPosition();
23784 this.emit('cameraPositionChange', parameters); // Prevent default actions caused by mouse wheel.
23785 // That might be ugly, but we handle scrolls somehow
23786 // anyway, so don't bother here..
23787
23788 util.preventDefault(event);
23789 }
23790};
23791/**
23792 * Test whether a point lies inside given 2D triangle
23793 *
23794 * @param {vis.Point2d} point
23795 * @param {vis.Point2d[]} triangle
23796 * @returns {boolean} true if given point lies inside or on the edge of the
23797 * triangle, false otherwise
23798 * @private
23799 */
23800
23801
23802Graph3d.prototype._insideTriangle = function (point, triangle) {
23803 var a = triangle[0],
23804 b = triangle[1],
23805 c = triangle[2];
23806 /**
23807 *
23808 * @param {number} x
23809 * @returns {number}
23810 */
23811
23812 function sign(x) {
23813 return x > 0 ? 1 : x < 0 ? -1 : 0;
23814 }
23815
23816 var as = sign((b.x - a.x) * (point.y - a.y) - (b.y - a.y) * (point.x - a.x));
23817 var bs = sign((c.x - b.x) * (point.y - b.y) - (c.y - b.y) * (point.x - b.x));
23818 var cs = sign((a.x - c.x) * (point.y - c.y) - (a.y - c.y) * (point.x - c.x)); // each of the three signs must be either equal to each other or zero
23819
23820 return (as == 0 || bs == 0 || as == bs) && (bs == 0 || cs == 0 || bs == cs) && (as == 0 || cs == 0 || as == cs);
23821};
23822/**
23823 * Find a data point close to given screen position (x, y)
23824 *
23825 * @param {number} x
23826 * @param {number} y
23827 * @returns {Object | null} The closest data point or null if not close to any
23828 * data point
23829 * @private
23830 */
23831
23832
23833Graph3d.prototype._dataPointFromXY = function (x, y) {
23834 var i,
23835 distMax = 100,
23836 // px
23837 dataPoint = null,
23838 closestDataPoint = null,
23839 closestDist = null,
23840 center = new Point2d_1(x, y);
23841
23842 if (this.style === Graph3d.STYLE.BAR || this.style === Graph3d.STYLE.BARCOLOR || this.style === Graph3d.STYLE.BARSIZE) {
23843 // the data points are ordered from far away to closest
23844 for (i = this.dataPoints.length - 1; i >= 0; i--) {
23845 dataPoint = this.dataPoints[i];
23846 var surfaces = dataPoint.surfaces;
23847
23848 if (surfaces) {
23849 for (var s = surfaces.length - 1; s >= 0; s--) {
23850 // split each surface in two triangles, and see if the center point is inside one of these
23851 var surface = surfaces[s];
23852 var corners = surface.corners;
23853 var triangle1 = [corners[0].screen, corners[1].screen, corners[2].screen];
23854 var triangle2 = [corners[2].screen, corners[3].screen, corners[0].screen];
23855
23856 if (this._insideTriangle(center, triangle1) || this._insideTriangle(center, triangle2)) {
23857 // return immediately at the first hit
23858 return dataPoint;
23859 }
23860 }
23861 }
23862 }
23863 } else {
23864 // find the closest data point, using distance to the center of the point on 2d screen
23865 for (i = 0; i < this.dataPoints.length; i++) {
23866 dataPoint = this.dataPoints[i];
23867 var point = dataPoint.screen;
23868
23869 if (point) {
23870 var distX = Math.abs(x - point.x);
23871 var distY = Math.abs(y - point.y);
23872 var dist = Math.sqrt(distX * distX + distY * distY);
23873
23874 if ((closestDist === null || dist < closestDist) && dist < distMax) {
23875 closestDist = dist;
23876 closestDataPoint = dataPoint;
23877 }
23878 }
23879 }
23880 }
23881
23882 return closestDataPoint;
23883};
23884/**
23885 * Determine if the given style has bars
23886 *
23887 * @param {number} style the style to check
23888 * @returns {boolean} true if bar style, false otherwise
23889 */
23890
23891
23892Graph3d.prototype.hasBars = function (style) {
23893 return style == Graph3d.STYLE.BAR || style == Graph3d.STYLE.BARCOLOR || style == Graph3d.STYLE.BARSIZE;
23894};
23895/**
23896 * Display a tooltip for given data point
23897 * @param {Object} dataPoint
23898 * @private
23899 */
23900
23901
23902Graph3d.prototype._showTooltip = function (dataPoint) {
23903 var content, line, dot;
23904
23905 if (!this.tooltip) {
23906 content = document.createElement('div');
23907 Object.assign(content.style, {}, this.tooltipStyle.content);
23908 content.style.position = 'absolute';
23909 line = document.createElement('div');
23910 Object.assign(line.style, {}, this.tooltipStyle.line);
23911 line.style.position = 'absolute';
23912 dot = document.createElement('div');
23913 Object.assign(dot.style, {}, this.tooltipStyle.dot);
23914 dot.style.position = 'absolute';
23915 this.tooltip = {
23916 dataPoint: null,
23917 dom: {
23918 content: content,
23919 line: line,
23920 dot: dot
23921 }
23922 };
23923 } else {
23924 content = this.tooltip.dom.content;
23925 line = this.tooltip.dom.line;
23926 dot = this.tooltip.dom.dot;
23927 }
23928
23929 this._hideTooltip();
23930
23931 this.tooltip.dataPoint = dataPoint;
23932
23933 if (typeof this.showTooltip === 'function') {
23934 content.innerHTML = this.showTooltip(dataPoint.point);
23935 } else {
23936 content.innerHTML = '<table>' + '<tr><td>' + this.xLabel + ':</td><td>' + dataPoint.point.x + '</td></tr>' + '<tr><td>' + this.yLabel + ':</td><td>' + dataPoint.point.y + '</td></tr>' + '<tr><td>' + this.zLabel + ':</td><td>' + dataPoint.point.z + '</td></tr>' + '</table>';
23937 }
23938
23939 content.style.left = '0';
23940 content.style.top = '0';
23941 this.frame.appendChild(content);
23942 this.frame.appendChild(line);
23943 this.frame.appendChild(dot); // calculate sizes
23944
23945 var contentWidth = content.offsetWidth;
23946 var contentHeight = content.offsetHeight;
23947 var lineHeight = line.offsetHeight;
23948 var dotWidth = dot.offsetWidth;
23949 var dotHeight = dot.offsetHeight;
23950 var left = dataPoint.screen.x - contentWidth / 2;
23951 left = Math.min(Math.max(left, 10), this.frame.clientWidth - 10 - contentWidth);
23952 line.style.left = dataPoint.screen.x + 'px';
23953 line.style.top = dataPoint.screen.y - lineHeight + 'px';
23954 content.style.left = left + 'px';
23955 content.style.top = dataPoint.screen.y - lineHeight - contentHeight + 'px';
23956 dot.style.left = dataPoint.screen.x - dotWidth / 2 + 'px';
23957 dot.style.top = dataPoint.screen.y - dotHeight / 2 + 'px';
23958};
23959/**
23960 * Hide the tooltip when displayed
23961 * @private
23962 */
23963
23964
23965Graph3d.prototype._hideTooltip = function () {
23966 if (this.tooltip) {
23967 this.tooltip.dataPoint = null;
23968
23969 for (var prop in this.tooltip.dom) {
23970 if (this.tooltip.dom.hasOwnProperty(prop)) {
23971 var elem = this.tooltip.dom[prop];
23972
23973 if (elem && elem.parentNode) {
23974 elem.parentNode.removeChild(elem);
23975 }
23976 }
23977 }
23978 }
23979};
23980/**--------------------------------------------------------------------------**/
23981
23982/**
23983 * Get the horizontal mouse position from a mouse event
23984 *
23985 * @param {Event} event
23986 * @returns {number} mouse x
23987 */
23988
23989
23990function getMouseX(event) {
23991 if ('clientX' in event) return event.clientX;
23992 return event.targetTouches[0] && event.targetTouches[0].clientX || 0;
23993}
23994/**
23995 * Get the vertical mouse position from a mouse event
23996 *
23997 * @param {Event} event
23998 * @returns {number} mouse y
23999 */
24000
24001
24002function getMouseY(event) {
24003 if ('clientY' in event) return event.clientY;
24004 return event.targetTouches[0] && event.targetTouches[0].clientY || 0;
24005} // -----------------------------------------------------------------------------
24006// Public methods for specific settings
24007// -----------------------------------------------------------------------------
24008
24009/**
24010 * Set the rotation and distance of the camera
24011 *
24012 * @param {Object} pos An object with the camera position
24013 * @param {number} [pos.horizontal] The horizontal rotation, between 0 and 2*PI.
24014 * Optional, can be left undefined.
24015 * @param {number} [pos.vertical] The vertical rotation, between 0 and 0.5*PI.
24016 * if vertical=0.5*PI, the graph is shown from
24017 * the top. Optional, can be left undefined.
24018 * @param {number} [pos.distance] The (normalized) distance of the camera to the
24019 * center of the graph, a value between 0.71 and
24020 * 5.0. Optional, can be left undefined.
24021 */
24022
24023
24024Graph3d.prototype.setCameraPosition = function (pos) {
24025 Settings.setCameraPosition(pos, this);
24026 this.redraw();
24027};
24028/**
24029 * Set a new size for the graph
24030 *
24031 * @param {string} width Width in pixels or percentage (for example '800px'
24032 * or '50%')
24033 * @param {string} height Height in pixels or percentage (for example '400px'
24034 * or '30%')
24035 */
24036
24037
24038Graph3d.prototype.setSize = function (width, height) {
24039 this._setSize(width, height);
24040
24041 this.redraw();
24042}; // -----------------------------------------------------------------------------
24043// End public methods for specific settings
24044// -----------------------------------------------------------------------------
24045
24046
24047var Graph3d_1 = Graph3d;
24048
24049var moment$2 = createCommonjsModule$1(function (module, exports) {
24050
24051 (function (global, factory) {
24052 module.exports = factory() ;
24053 })(commonjsGlobal$1, function () {
24054
24055 var hookCallback;
24056
24057 function hooks() {
24058 return hookCallback.apply(null, arguments);
24059 } // This is done to register the method called with moment()
24060 // without creating circular dependencies.
24061
24062
24063 function setHookCallback(callback) {
24064 hookCallback = callback;
24065 }
24066
24067 function isArray(input) {
24068 return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]';
24069 }
24070
24071 function isObject(input) {
24072 // IE8 will treat undefined and null as object if it wasn't for
24073 // input != null
24074 return input != null && Object.prototype.toString.call(input) === '[object Object]';
24075 }
24076
24077 function isObjectEmpty(obj) {
24078 if (Object.getOwnPropertyNames) {
24079 return Object.getOwnPropertyNames(obj).length === 0;
24080 } else {
24081 var k;
24082
24083 for (k in obj) {
24084 if (obj.hasOwnProperty(k)) {
24085 return false;
24086 }
24087 }
24088
24089 return true;
24090 }
24091 }
24092
24093 function isUndefined(input) {
24094 return input === void 0;
24095 }
24096
24097 function isNumber(input) {
24098 return typeof input === 'number' || Object.prototype.toString.call(input) === '[object Number]';
24099 }
24100
24101 function isDate(input) {
24102 return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
24103 }
24104
24105 function map(arr, fn) {
24106 var res = [],
24107 i;
24108
24109 for (i = 0; i < arr.length; ++i) {
24110 res.push(fn(arr[i], i));
24111 }
24112
24113 return res;
24114 }
24115
24116 function hasOwnProp(a, b) {
24117 return Object.prototype.hasOwnProperty.call(a, b);
24118 }
24119
24120 function extend(a, b) {
24121 for (var i in b) {
24122 if (hasOwnProp(b, i)) {
24123 a[i] = b[i];
24124 }
24125 }
24126
24127 if (hasOwnProp(b, 'toString')) {
24128 a.toString = b.toString;
24129 }
24130
24131 if (hasOwnProp(b, 'valueOf')) {
24132 a.valueOf = b.valueOf;
24133 }
24134
24135 return a;
24136 }
24137
24138 function createUTC(input, format, locale, strict) {
24139 return createLocalOrUTC(input, format, locale, strict, true).utc();
24140 }
24141
24142 function defaultParsingFlags() {
24143 // We need to deep clone this object.
24144 return {
24145 empty: false,
24146 unusedTokens: [],
24147 unusedInput: [],
24148 overflow: -2,
24149 charsLeftOver: 0,
24150 nullInput: false,
24151 invalidMonth: null,
24152 invalidFormat: false,
24153 userInvalidated: false,
24154 iso: false,
24155 parsedDateParts: [],
24156 meridiem: null,
24157 rfc2822: false,
24158 weekdayMismatch: false
24159 };
24160 }
24161
24162 function getParsingFlags(m) {
24163 if (m._pf == null) {
24164 m._pf = defaultParsingFlags();
24165 }
24166
24167 return m._pf;
24168 }
24169
24170 var some;
24171
24172 if (Array.prototype.some) {
24173 some = Array.prototype.some;
24174 } else {
24175 some = function (fun) {
24176 var t = Object(this);
24177 var len = t.length >>> 0;
24178
24179 for (var i = 0; i < len; i++) {
24180 if (i in t && fun.call(this, t[i], i, t)) {
24181 return true;
24182 }
24183 }
24184
24185 return false;
24186 };
24187 }
24188
24189 function isValid(m) {
24190 if (m._isValid == null) {
24191 var flags = getParsingFlags(m);
24192 var parsedParts = some.call(flags.parsedDateParts, function (i) {
24193 return i != null;
24194 });
24195 var isNowValid = !isNaN(m._d.getTime()) && flags.overflow < 0 && !flags.empty && !flags.invalidMonth && !flags.invalidWeekday && !flags.weekdayMismatch && !flags.nullInput && !flags.invalidFormat && !flags.userInvalidated && (!flags.meridiem || flags.meridiem && parsedParts);
24196
24197 if (m._strict) {
24198 isNowValid = isNowValid && flags.charsLeftOver === 0 && flags.unusedTokens.length === 0 && flags.bigHour === undefined;
24199 }
24200
24201 if (Object.isFrozen == null || !Object.isFrozen(m)) {
24202 m._isValid = isNowValid;
24203 } else {
24204 return isNowValid;
24205 }
24206 }
24207
24208 return m._isValid;
24209 }
24210
24211 function createInvalid(flags) {
24212 var m = createUTC(NaN);
24213
24214 if (flags != null) {
24215 extend(getParsingFlags(m), flags);
24216 } else {
24217 getParsingFlags(m).userInvalidated = true;
24218 }
24219
24220 return m;
24221 } // Plugins that add properties should also add the key here (null value),
24222 // so we can properly clone ourselves.
24223
24224
24225 var momentProperties = hooks.momentProperties = [];
24226
24227 function copyConfig(to, from) {
24228 var i, prop, val;
24229
24230 if (!isUndefined(from._isAMomentObject)) {
24231 to._isAMomentObject = from._isAMomentObject;
24232 }
24233
24234 if (!isUndefined(from._i)) {
24235 to._i = from._i;
24236 }
24237
24238 if (!isUndefined(from._f)) {
24239 to._f = from._f;
24240 }
24241
24242 if (!isUndefined(from._l)) {
24243 to._l = from._l;
24244 }
24245
24246 if (!isUndefined(from._strict)) {
24247 to._strict = from._strict;
24248 }
24249
24250 if (!isUndefined(from._tzm)) {
24251 to._tzm = from._tzm;
24252 }
24253
24254 if (!isUndefined(from._isUTC)) {
24255 to._isUTC = from._isUTC;
24256 }
24257
24258 if (!isUndefined(from._offset)) {
24259 to._offset = from._offset;
24260 }
24261
24262 if (!isUndefined(from._pf)) {
24263 to._pf = getParsingFlags(from);
24264 }
24265
24266 if (!isUndefined(from._locale)) {
24267 to._locale = from._locale;
24268 }
24269
24270 if (momentProperties.length > 0) {
24271 for (i = 0; i < momentProperties.length; i++) {
24272 prop = momentProperties[i];
24273 val = from[prop];
24274
24275 if (!isUndefined(val)) {
24276 to[prop] = val;
24277 }
24278 }
24279 }
24280
24281 return to;
24282 }
24283
24284 var updateInProgress = false; // Moment prototype object
24285
24286 function Moment(config) {
24287 copyConfig(this, config);
24288 this._d = new Date(config._d != null ? config._d.getTime() : NaN);
24289
24290 if (!this.isValid()) {
24291 this._d = new Date(NaN);
24292 } // Prevent infinite loop in case updateOffset creates new moment
24293 // objects.
24294
24295
24296 if (updateInProgress === false) {
24297 updateInProgress = true;
24298 hooks.updateOffset(this);
24299 updateInProgress = false;
24300 }
24301 }
24302
24303 function isMoment(obj) {
24304 return obj instanceof Moment || obj != null && obj._isAMomentObject != null;
24305 }
24306
24307 function absFloor(number) {
24308 if (number < 0) {
24309 // -0 -> 0
24310 return Math.ceil(number) || 0;
24311 } else {
24312 return Math.floor(number);
24313 }
24314 }
24315
24316 function toInt(argumentForCoercion) {
24317 var coercedNumber = +argumentForCoercion,
24318 value = 0;
24319
24320 if (coercedNumber !== 0 && isFinite(coercedNumber)) {
24321 value = absFloor(coercedNumber);
24322 }
24323
24324 return value;
24325 } // compare two arrays, return the number of differences
24326
24327
24328 function compareArrays(array1, array2, dontConvert) {
24329 var len = Math.min(array1.length, array2.length),
24330 lengthDiff = Math.abs(array1.length - array2.length),
24331 diffs = 0,
24332 i;
24333
24334 for (i = 0; i < len; i++) {
24335 if (dontConvert && array1[i] !== array2[i] || !dontConvert && toInt(array1[i]) !== toInt(array2[i])) {
24336 diffs++;
24337 }
24338 }
24339
24340 return diffs + lengthDiff;
24341 }
24342
24343 function warn(msg) {
24344 if (hooks.suppressDeprecationWarnings === false && typeof console !== 'undefined' && console.warn) {
24345 console.warn('Deprecation warning: ' + msg);
24346 }
24347 }
24348
24349 function deprecate(msg, fn) {
24350 var firstTime = true;
24351 return extend(function () {
24352 if (hooks.deprecationHandler != null) {
24353 hooks.deprecationHandler(null, msg);
24354 }
24355
24356 if (firstTime) {
24357 var args = [];
24358 var arg;
24359
24360 for (var i = 0; i < arguments.length; i++) {
24361 arg = '';
24362
24363 if (typeof arguments[i] === 'object') {
24364 arg += '\n[' + i + '] ';
24365
24366 for (var key in arguments[0]) {
24367 arg += key + ': ' + arguments[0][key] + ', ';
24368 }
24369
24370 arg = arg.slice(0, -2); // Remove trailing comma and space
24371 } else {
24372 arg = arguments[i];
24373 }
24374
24375 args.push(arg);
24376 }
24377
24378 warn(msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + new Error().stack);
24379 firstTime = false;
24380 }
24381
24382 return fn.apply(this, arguments);
24383 }, fn);
24384 }
24385
24386 var deprecations = {};
24387
24388 function deprecateSimple(name, msg) {
24389 if (hooks.deprecationHandler != null) {
24390 hooks.deprecationHandler(name, msg);
24391 }
24392
24393 if (!deprecations[name]) {
24394 warn(msg);
24395 deprecations[name] = true;
24396 }
24397 }
24398
24399 hooks.suppressDeprecationWarnings = false;
24400 hooks.deprecationHandler = null;
24401
24402 function isFunction(input) {
24403 return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
24404 }
24405
24406 function set(config) {
24407 var prop, i;
24408
24409 for (i in config) {
24410 prop = config[i];
24411
24412 if (isFunction(prop)) {
24413 this[i] = prop;
24414 } else {
24415 this['_' + i] = prop;
24416 }
24417 }
24418
24419 this._config = config; // Lenient ordinal parsing accepts just a number in addition to
24420 // number + (possibly) stuff coming from _dayOfMonthOrdinalParse.
24421 // TODO: Remove "ordinalParse" fallback in next major release.
24422
24423 this._dayOfMonthOrdinalParseLenient = new RegExp((this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + '|' + /\d{1,2}/.source);
24424 }
24425
24426 function mergeConfigs(parentConfig, childConfig) {
24427 var res = extend({}, parentConfig),
24428 prop;
24429
24430 for (prop in childConfig) {
24431 if (hasOwnProp(childConfig, prop)) {
24432 if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
24433 res[prop] = {};
24434 extend(res[prop], parentConfig[prop]);
24435 extend(res[prop], childConfig[prop]);
24436 } else if (childConfig[prop] != null) {
24437 res[prop] = childConfig[prop];
24438 } else {
24439 delete res[prop];
24440 }
24441 }
24442 }
24443
24444 for (prop in parentConfig) {
24445 if (hasOwnProp(parentConfig, prop) && !hasOwnProp(childConfig, prop) && isObject(parentConfig[prop])) {
24446 // make sure changes to properties don't modify parent config
24447 res[prop] = extend({}, res[prop]);
24448 }
24449 }
24450
24451 return res;
24452 }
24453
24454 function Locale(config) {
24455 if (config != null) {
24456 this.set(config);
24457 }
24458 }
24459
24460 var keys;
24461
24462 if (Object.keys) {
24463 keys = Object.keys;
24464 } else {
24465 keys = function (obj) {
24466 var i,
24467 res = [];
24468
24469 for (i in obj) {
24470 if (hasOwnProp(obj, i)) {
24471 res.push(i);
24472 }
24473 }
24474
24475 return res;
24476 };
24477 }
24478
24479 var defaultCalendar = {
24480 sameDay: '[Today at] LT',
24481 nextDay: '[Tomorrow at] LT',
24482 nextWeek: 'dddd [at] LT',
24483 lastDay: '[Yesterday at] LT',
24484 lastWeek: '[Last] dddd [at] LT',
24485 sameElse: 'L'
24486 };
24487
24488 function calendar(key, mom, now) {
24489 var output = this._calendar[key] || this._calendar['sameElse'];
24490 return isFunction(output) ? output.call(mom, now) : output;
24491 }
24492
24493 var defaultLongDateFormat = {
24494 LTS: 'h:mm:ss A',
24495 LT: 'h:mm A',
24496 L: 'MM/DD/YYYY',
24497 LL: 'MMMM D, YYYY',
24498 LLL: 'MMMM D, YYYY h:mm A',
24499 LLLL: 'dddd, MMMM D, YYYY h:mm A'
24500 };
24501
24502 function longDateFormat(key) {
24503 var format = this._longDateFormat[key],
24504 formatUpper = this._longDateFormat[key.toUpperCase()];
24505
24506 if (format || !formatUpper) {
24507 return format;
24508 }
24509
24510 this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) {
24511 return val.slice(1);
24512 });
24513 return this._longDateFormat[key];
24514 }
24515
24516 var defaultInvalidDate = 'Invalid date';
24517
24518 function invalidDate() {
24519 return this._invalidDate;
24520 }
24521
24522 var defaultOrdinal = '%d';
24523 var defaultDayOfMonthOrdinalParse = /\d{1,2}/;
24524
24525 function ordinal(number) {
24526 return this._ordinal.replace('%d', number);
24527 }
24528
24529 var defaultRelativeTime = {
24530 future: 'in %s',
24531 past: '%s ago',
24532 s: 'a few seconds',
24533 ss: '%d seconds',
24534 m: 'a minute',
24535 mm: '%d minutes',
24536 h: 'an hour',
24537 hh: '%d hours',
24538 d: 'a day',
24539 dd: '%d days',
24540 M: 'a month',
24541 MM: '%d months',
24542 y: 'a year',
24543 yy: '%d years'
24544 };
24545
24546 function relativeTime(number, withoutSuffix, string, isFuture) {
24547 var output = this._relativeTime[string];
24548 return isFunction(output) ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number);
24549 }
24550
24551 function pastFuture(diff, output) {
24552 var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
24553 return isFunction(format) ? format(output) : format.replace(/%s/i, output);
24554 }
24555
24556 var aliases = {};
24557
24558 function addUnitAlias(unit, shorthand) {
24559 var lowerCase = unit.toLowerCase();
24560 aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
24561 }
24562
24563 function normalizeUnits(units) {
24564 return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined;
24565 }
24566
24567 function normalizeObjectUnits(inputObject) {
24568 var normalizedInput = {},
24569 normalizedProp,
24570 prop;
24571
24572 for (prop in inputObject) {
24573 if (hasOwnProp(inputObject, prop)) {
24574 normalizedProp = normalizeUnits(prop);
24575
24576 if (normalizedProp) {
24577 normalizedInput[normalizedProp] = inputObject[prop];
24578 }
24579 }
24580 }
24581
24582 return normalizedInput;
24583 }
24584
24585 var priorities = {};
24586
24587 function addUnitPriority(unit, priority) {
24588 priorities[unit] = priority;
24589 }
24590
24591 function getPrioritizedUnits(unitsObj) {
24592 var units = [];
24593
24594 for (var u in unitsObj) {
24595 units.push({
24596 unit: u,
24597 priority: priorities[u]
24598 });
24599 }
24600
24601 units.sort(function (a, b) {
24602 return a.priority - b.priority;
24603 });
24604 return units;
24605 }
24606
24607 function zeroFill(number, targetLength, forceSign) {
24608 var absNumber = '' + Math.abs(number),
24609 zerosToFill = targetLength - absNumber.length,
24610 sign = number >= 0;
24611 return (sign ? forceSign ? '+' : '' : '-') + Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber;
24612 }
24613
24614 var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g;
24615 var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;
24616 var formatFunctions = {};
24617 var formatTokenFunctions = {}; // token: 'M'
24618 // padded: ['MM', 2]
24619 // ordinal: 'Mo'
24620 // callback: function () { this.month() + 1 }
24621
24622 function addFormatToken(token, padded, ordinal, callback) {
24623 var func = callback;
24624
24625 if (typeof callback === 'string') {
24626 func = function () {
24627 return this[callback]();
24628 };
24629 }
24630
24631 if (token) {
24632 formatTokenFunctions[token] = func;
24633 }
24634
24635 if (padded) {
24636 formatTokenFunctions[padded[0]] = function () {
24637 return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
24638 };
24639 }
24640
24641 if (ordinal) {
24642 formatTokenFunctions[ordinal] = function () {
24643 return this.localeData().ordinal(func.apply(this, arguments), token);
24644 };
24645 }
24646 }
24647
24648 function removeFormattingTokens(input) {
24649 if (input.match(/\[[\s\S]/)) {
24650 return input.replace(/^\[|\]$/g, '');
24651 }
24652
24653 return input.replace(/\\/g, '');
24654 }
24655
24656 function makeFormatFunction(format) {
24657 var array = format.match(formattingTokens),
24658 i,
24659 length;
24660
24661 for (i = 0, length = array.length; i < length; i++) {
24662 if (formatTokenFunctions[array[i]]) {
24663 array[i] = formatTokenFunctions[array[i]];
24664 } else {
24665 array[i] = removeFormattingTokens(array[i]);
24666 }
24667 }
24668
24669 return function (mom) {
24670 var output = '',
24671 i;
24672
24673 for (i = 0; i < length; i++) {
24674 output += isFunction(array[i]) ? array[i].call(mom, format) : array[i];
24675 }
24676
24677 return output;
24678 };
24679 } // format date using native date object
24680
24681
24682 function formatMoment(m, format) {
24683 if (!m.isValid()) {
24684 return m.localeData().invalidDate();
24685 }
24686
24687 format = expandFormat(format, m.localeData());
24688 formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format);
24689 return formatFunctions[format](m);
24690 }
24691
24692 function expandFormat(format, locale) {
24693 var i = 5;
24694
24695 function replaceLongDateFormatTokens(input) {
24696 return locale.longDateFormat(input) || input;
24697 }
24698
24699 localFormattingTokens.lastIndex = 0;
24700
24701 while (i >= 0 && localFormattingTokens.test(format)) {
24702 format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
24703 localFormattingTokens.lastIndex = 0;
24704 i -= 1;
24705 }
24706
24707 return format;
24708 }
24709
24710 var match1 = /\d/; // 0 - 9
24711
24712 var match2 = /\d\d/; // 00 - 99
24713
24714 var match3 = /\d{3}/; // 000 - 999
24715
24716 var match4 = /\d{4}/; // 0000 - 9999
24717
24718 var match6 = /[+-]?\d{6}/; // -999999 - 999999
24719
24720 var match1to2 = /\d\d?/; // 0 - 99
24721
24722 var match3to4 = /\d\d\d\d?/; // 999 - 9999
24723
24724 var match5to6 = /\d\d\d\d\d\d?/; // 99999 - 999999
24725
24726 var match1to3 = /\d{1,3}/; // 0 - 999
24727
24728 var match1to4 = /\d{1,4}/; // 0 - 9999
24729
24730 var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999
24731
24732 var matchUnsigned = /\d+/; // 0 - inf
24733
24734 var matchSigned = /[+-]?\d+/; // -inf - inf
24735
24736 var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z
24737
24738 var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z
24739
24740 var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123
24741 // any word (or two) characters or numbers including two/three word month in arabic.
24742 // includes scottish gaelic two word and hyphenated months
24743
24744 var matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i;
24745 var regexes = {};
24746
24747 function addRegexToken(token, regex, strictRegex) {
24748 regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) {
24749 return isStrict && strictRegex ? strictRegex : regex;
24750 };
24751 }
24752
24753 function getParseRegexForToken(token, config) {
24754 if (!hasOwnProp(regexes, token)) {
24755 return new RegExp(unescapeFormat(token));
24756 }
24757
24758 return regexes[token](config._strict, config._locale);
24759 } // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
24760
24761
24762 function unescapeFormat(s) {
24763 return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
24764 return p1 || p2 || p3 || p4;
24765 }));
24766 }
24767
24768 function regexEscape(s) {
24769 return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
24770 }
24771
24772 var tokens = {};
24773
24774 function addParseToken(token, callback) {
24775 var i,
24776 func = callback;
24777
24778 if (typeof token === 'string') {
24779 token = [token];
24780 }
24781
24782 if (isNumber(callback)) {
24783 func = function (input, array) {
24784 array[callback] = toInt(input);
24785 };
24786 }
24787
24788 for (i = 0; i < token.length; i++) {
24789 tokens[token[i]] = func;
24790 }
24791 }
24792
24793 function addWeekParseToken(token, callback) {
24794 addParseToken(token, function (input, array, config, token) {
24795 config._w = config._w || {};
24796 callback(input, config._w, config, token);
24797 });
24798 }
24799
24800 function addTimeToArrayFromToken(token, input, config) {
24801 if (input != null && hasOwnProp(tokens, token)) {
24802 tokens[token](input, config._a, config, token);
24803 }
24804 }
24805
24806 var YEAR = 0;
24807 var MONTH = 1;
24808 var DATE = 2;
24809 var HOUR = 3;
24810 var MINUTE = 4;
24811 var SECOND = 5;
24812 var MILLISECOND = 6;
24813 var WEEK = 7;
24814 var WEEKDAY = 8; // FORMATTING
24815
24816 addFormatToken('Y', 0, 0, function () {
24817 var y = this.year();
24818 return y <= 9999 ? '' + y : '+' + y;
24819 });
24820 addFormatToken(0, ['YY', 2], 0, function () {
24821 return this.year() % 100;
24822 });
24823 addFormatToken(0, ['YYYY', 4], 0, 'year');
24824 addFormatToken(0, ['YYYYY', 5], 0, 'year');
24825 addFormatToken(0, ['YYYYYY', 6, true], 0, 'year'); // ALIASES
24826
24827 addUnitAlias('year', 'y'); // PRIORITIES
24828
24829 addUnitPriority('year', 1); // PARSING
24830
24831 addRegexToken('Y', matchSigned);
24832 addRegexToken('YY', match1to2, match2);
24833 addRegexToken('YYYY', match1to4, match4);
24834 addRegexToken('YYYYY', match1to6, match6);
24835 addRegexToken('YYYYYY', match1to6, match6);
24836 addParseToken(['YYYYY', 'YYYYYY'], YEAR);
24837 addParseToken('YYYY', function (input, array) {
24838 array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
24839 });
24840 addParseToken('YY', function (input, array) {
24841 array[YEAR] = hooks.parseTwoDigitYear(input);
24842 });
24843 addParseToken('Y', function (input, array) {
24844 array[YEAR] = parseInt(input, 10);
24845 }); // HELPERS
24846
24847 function daysInYear(year) {
24848 return isLeapYear(year) ? 366 : 365;
24849 }
24850
24851 function isLeapYear(year) {
24852 return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
24853 } // HOOKS
24854
24855
24856 hooks.parseTwoDigitYear = function (input) {
24857 return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
24858 }; // MOMENTS
24859
24860
24861 var getSetYear = makeGetSet('FullYear', true);
24862
24863 function getIsLeapYear() {
24864 return isLeapYear(this.year());
24865 }
24866
24867 function makeGetSet(unit, keepTime) {
24868 return function (value) {
24869 if (value != null) {
24870 set$1(this, unit, value);
24871 hooks.updateOffset(this, keepTime);
24872 return this;
24873 } else {
24874 return get(this, unit);
24875 }
24876 };
24877 }
24878
24879 function get(mom, unit) {
24880 return mom.isValid() ? mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN;
24881 }
24882
24883 function set$1(mom, unit, value) {
24884 if (mom.isValid() && !isNaN(value)) {
24885 if (unit === 'FullYear' && isLeapYear(mom.year()) && mom.month() === 1 && mom.date() === 29) {
24886 mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value, mom.month(), daysInMonth(value, mom.month()));
24887 } else {
24888 mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
24889 }
24890 }
24891 } // MOMENTS
24892
24893
24894 function stringGet(units) {
24895 units = normalizeUnits(units);
24896
24897 if (isFunction(this[units])) {
24898 return this[units]();
24899 }
24900
24901 return this;
24902 }
24903
24904 function stringSet(units, value) {
24905 if (typeof units === 'object') {
24906 units = normalizeObjectUnits(units);
24907 var prioritized = getPrioritizedUnits(units);
24908
24909 for (var i = 0; i < prioritized.length; i++) {
24910 this[prioritized[i].unit](units[prioritized[i].unit]);
24911 }
24912 } else {
24913 units = normalizeUnits(units);
24914
24915 if (isFunction(this[units])) {
24916 return this[units](value);
24917 }
24918 }
24919
24920 return this;
24921 }
24922
24923 function mod(n, x) {
24924 return (n % x + x) % x;
24925 }
24926
24927 var indexOf;
24928
24929 if (Array.prototype.indexOf) {
24930 indexOf = Array.prototype.indexOf;
24931 } else {
24932 indexOf = function (o) {
24933 // I know
24934 var i;
24935
24936 for (i = 0; i < this.length; ++i) {
24937 if (this[i] === o) {
24938 return i;
24939 }
24940 }
24941
24942 return -1;
24943 };
24944 }
24945
24946 function daysInMonth(year, month) {
24947 if (isNaN(year) || isNaN(month)) {
24948 return NaN;
24949 }
24950
24951 var modMonth = mod(month, 12);
24952 year += (month - modMonth) / 12;
24953 return modMonth === 1 ? isLeapYear(year) ? 29 : 28 : 31 - modMonth % 7 % 2;
24954 } // FORMATTING
24955
24956
24957 addFormatToken('M', ['MM', 2], 'Mo', function () {
24958 return this.month() + 1;
24959 });
24960 addFormatToken('MMM', 0, 0, function (format) {
24961 return this.localeData().monthsShort(this, format);
24962 });
24963 addFormatToken('MMMM', 0, 0, function (format) {
24964 return this.localeData().months(this, format);
24965 }); // ALIASES
24966
24967 addUnitAlias('month', 'M'); // PRIORITY
24968
24969 addUnitPriority('month', 8); // PARSING
24970
24971 addRegexToken('M', match1to2);
24972 addRegexToken('MM', match1to2, match2);
24973 addRegexToken('MMM', function (isStrict, locale) {
24974 return locale.monthsShortRegex(isStrict);
24975 });
24976 addRegexToken('MMMM', function (isStrict, locale) {
24977 return locale.monthsRegex(isStrict);
24978 });
24979 addParseToken(['M', 'MM'], function (input, array) {
24980 array[MONTH] = toInt(input) - 1;
24981 });
24982 addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
24983 var month = config._locale.monthsParse(input, token, config._strict); // if we didn't find a month name, mark the date as invalid.
24984
24985
24986 if (month != null) {
24987 array[MONTH] = month;
24988 } else {
24989 getParsingFlags(config).invalidMonth = input;
24990 }
24991 }); // LOCALES
24992
24993 var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/;
24994 var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_');
24995
24996 function localeMonths(m, format) {
24997 if (!m) {
24998 return isArray(this._months) ? this._months : this._months['standalone'];
24999 }
25000
25001 return isArray(this._months) ? this._months[m.month()] : this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()];
25002 }
25003
25004 var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_');
25005
25006 function localeMonthsShort(m, format) {
25007 if (!m) {
25008 return isArray(this._monthsShort) ? this._monthsShort : this._monthsShort['standalone'];
25009 }
25010
25011 return isArray(this._monthsShort) ? this._monthsShort[m.month()] : this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()];
25012 }
25013
25014 function handleStrictParse(monthName, format, strict) {
25015 var i,
25016 ii,
25017 mom,
25018 llc = monthName.toLocaleLowerCase();
25019
25020 if (!this._monthsParse) {
25021 // this is not used
25022 this._monthsParse = [];
25023 this._longMonthsParse = [];
25024 this._shortMonthsParse = [];
25025
25026 for (i = 0; i < 12; ++i) {
25027 mom = createUTC([2000, i]);
25028 this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase();
25029 this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
25030 }
25031 }
25032
25033 if (strict) {
25034 if (format === 'MMM') {
25035 ii = indexOf.call(this._shortMonthsParse, llc);
25036 return ii !== -1 ? ii : null;
25037 } else {
25038 ii = indexOf.call(this._longMonthsParse, llc);
25039 return ii !== -1 ? ii : null;
25040 }
25041 } else {
25042 if (format === 'MMM') {
25043 ii = indexOf.call(this._shortMonthsParse, llc);
25044
25045 if (ii !== -1) {
25046 return ii;
25047 }
25048
25049 ii = indexOf.call(this._longMonthsParse, llc);
25050 return ii !== -1 ? ii : null;
25051 } else {
25052 ii = indexOf.call(this._longMonthsParse, llc);
25053
25054 if (ii !== -1) {
25055 return ii;
25056 }
25057
25058 ii = indexOf.call(this._shortMonthsParse, llc);
25059 return ii !== -1 ? ii : null;
25060 }
25061 }
25062 }
25063
25064 function localeMonthsParse(monthName, format, strict) {
25065 var i, mom, regex;
25066
25067 if (this._monthsParseExact) {
25068 return handleStrictParse.call(this, monthName, format, strict);
25069 }
25070
25071 if (!this._monthsParse) {
25072 this._monthsParse = [];
25073 this._longMonthsParse = [];
25074 this._shortMonthsParse = [];
25075 } // TODO: add sorting
25076 // Sorting makes sure if one month (or abbr) is a prefix of another
25077 // see sorting in computeMonthsParse
25078
25079
25080 for (i = 0; i < 12; i++) {
25081 // make the regex if we don't have it already
25082 mom = createUTC([2000, i]);
25083
25084 if (strict && !this._longMonthsParse[i]) {
25085 this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
25086 this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
25087 }
25088
25089 if (!strict && !this._monthsParse[i]) {
25090 regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
25091 this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
25092 } // test the regex
25093
25094
25095 if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
25096 return i;
25097 } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
25098 return i;
25099 } else if (!strict && this._monthsParse[i].test(monthName)) {
25100 return i;
25101 }
25102 }
25103 } // MOMENTS
25104
25105
25106 function setMonth(mom, value) {
25107 var dayOfMonth;
25108
25109 if (!mom.isValid()) {
25110 // No op
25111 return mom;
25112 }
25113
25114 if (typeof value === 'string') {
25115 if (/^\d+$/.test(value)) {
25116 value = toInt(value);
25117 } else {
25118 value = mom.localeData().monthsParse(value); // TODO: Another silent failure?
25119
25120 if (!isNumber(value)) {
25121 return mom;
25122 }
25123 }
25124 }
25125
25126 dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
25127
25128 mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
25129
25130 return mom;
25131 }
25132
25133 function getSetMonth(value) {
25134 if (value != null) {
25135 setMonth(this, value);
25136 hooks.updateOffset(this, true);
25137 return this;
25138 } else {
25139 return get(this, 'Month');
25140 }
25141 }
25142
25143 function getDaysInMonth() {
25144 return daysInMonth(this.year(), this.month());
25145 }
25146
25147 var defaultMonthsShortRegex = matchWord;
25148
25149 function monthsShortRegex(isStrict) {
25150 if (this._monthsParseExact) {
25151 if (!hasOwnProp(this, '_monthsRegex')) {
25152 computeMonthsParse.call(this);
25153 }
25154
25155 if (isStrict) {
25156 return this._monthsShortStrictRegex;
25157 } else {
25158 return this._monthsShortRegex;
25159 }
25160 } else {
25161 if (!hasOwnProp(this, '_monthsShortRegex')) {
25162 this._monthsShortRegex = defaultMonthsShortRegex;
25163 }
25164
25165 return this._monthsShortStrictRegex && isStrict ? this._monthsShortStrictRegex : this._monthsShortRegex;
25166 }
25167 }
25168
25169 var defaultMonthsRegex = matchWord;
25170
25171 function monthsRegex(isStrict) {
25172 if (this._monthsParseExact) {
25173 if (!hasOwnProp(this, '_monthsRegex')) {
25174 computeMonthsParse.call(this);
25175 }
25176
25177 if (isStrict) {
25178 return this._monthsStrictRegex;
25179 } else {
25180 return this._monthsRegex;
25181 }
25182 } else {
25183 if (!hasOwnProp(this, '_monthsRegex')) {
25184 this._monthsRegex = defaultMonthsRegex;
25185 }
25186
25187 return this._monthsStrictRegex && isStrict ? this._monthsStrictRegex : this._monthsRegex;
25188 }
25189 }
25190
25191 function computeMonthsParse() {
25192 function cmpLenRev(a, b) {
25193 return b.length - a.length;
25194 }
25195
25196 var shortPieces = [],
25197 longPieces = [],
25198 mixedPieces = [],
25199 i,
25200 mom;
25201
25202 for (i = 0; i < 12; i++) {
25203 // make the regex if we don't have it already
25204 mom = createUTC([2000, i]);
25205 shortPieces.push(this.monthsShort(mom, ''));
25206 longPieces.push(this.months(mom, ''));
25207 mixedPieces.push(this.months(mom, ''));
25208 mixedPieces.push(this.monthsShort(mom, ''));
25209 } // Sorting makes sure if one month (or abbr) is a prefix of another it
25210 // will match the longer piece.
25211
25212
25213 shortPieces.sort(cmpLenRev);
25214 longPieces.sort(cmpLenRev);
25215 mixedPieces.sort(cmpLenRev);
25216
25217 for (i = 0; i < 12; i++) {
25218 shortPieces[i] = regexEscape(shortPieces[i]);
25219 longPieces[i] = regexEscape(longPieces[i]);
25220 }
25221
25222 for (i = 0; i < 24; i++) {
25223 mixedPieces[i] = regexEscape(mixedPieces[i]);
25224 }
25225
25226 this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
25227 this._monthsShortRegex = this._monthsRegex;
25228 this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
25229 this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
25230 }
25231
25232 function createDate(y, m, d, h, M, s, ms) {
25233 // can't just apply() to create a date:
25234 // https://stackoverflow.com/q/181348
25235 var date; // the date constructor remaps years 0-99 to 1900-1999
25236
25237 if (y < 100 && y >= 0) {
25238 // preserve leap years using a full 400 year cycle, then reset
25239 date = new Date(y + 400, m, d, h, M, s, ms);
25240
25241 if (isFinite(date.getFullYear())) {
25242 date.setFullYear(y);
25243 }
25244 } else {
25245 date = new Date(y, m, d, h, M, s, ms);
25246 }
25247
25248 return date;
25249 }
25250
25251 function createUTCDate(y) {
25252 var date; // the Date.UTC function remaps years 0-99 to 1900-1999
25253
25254 if (y < 100 && y >= 0) {
25255 var args = Array.prototype.slice.call(arguments); // preserve leap years using a full 400 year cycle, then reset
25256
25257 args[0] = y + 400;
25258 date = new Date(Date.UTC.apply(null, args));
25259
25260 if (isFinite(date.getUTCFullYear())) {
25261 date.setUTCFullYear(y);
25262 }
25263 } else {
25264 date = new Date(Date.UTC.apply(null, arguments));
25265 }
25266
25267 return date;
25268 } // start-of-first-week - start-of-year
25269
25270
25271 function firstWeekOffset(year, dow, doy) {
25272 var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
25273 fwd = 7 + dow - doy,
25274 // first-week day local weekday -- which local weekday is fwd
25275 fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
25276 return -fwdlw + fwd - 1;
25277 } // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
25278
25279
25280 function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
25281 var localWeekday = (7 + weekday - dow) % 7,
25282 weekOffset = firstWeekOffset(year, dow, doy),
25283 dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
25284 resYear,
25285 resDayOfYear;
25286
25287 if (dayOfYear <= 0) {
25288 resYear = year - 1;
25289 resDayOfYear = daysInYear(resYear) + dayOfYear;
25290 } else if (dayOfYear > daysInYear(year)) {
25291 resYear = year + 1;
25292 resDayOfYear = dayOfYear - daysInYear(year);
25293 } else {
25294 resYear = year;
25295 resDayOfYear = dayOfYear;
25296 }
25297
25298 return {
25299 year: resYear,
25300 dayOfYear: resDayOfYear
25301 };
25302 }
25303
25304 function weekOfYear(mom, dow, doy) {
25305 var weekOffset = firstWeekOffset(mom.year(), dow, doy),
25306 week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
25307 resWeek,
25308 resYear;
25309
25310 if (week < 1) {
25311 resYear = mom.year() - 1;
25312 resWeek = week + weeksInYear(resYear, dow, doy);
25313 } else if (week > weeksInYear(mom.year(), dow, doy)) {
25314 resWeek = week - weeksInYear(mom.year(), dow, doy);
25315 resYear = mom.year() + 1;
25316 } else {
25317 resYear = mom.year();
25318 resWeek = week;
25319 }
25320
25321 return {
25322 week: resWeek,
25323 year: resYear
25324 };
25325 }
25326
25327 function weeksInYear(year, dow, doy) {
25328 var weekOffset = firstWeekOffset(year, dow, doy),
25329 weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
25330 return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
25331 } // FORMATTING
25332
25333
25334 addFormatToken('w', ['ww', 2], 'wo', 'week');
25335 addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek'); // ALIASES
25336
25337 addUnitAlias('week', 'w');
25338 addUnitAlias('isoWeek', 'W'); // PRIORITIES
25339
25340 addUnitPriority('week', 5);
25341 addUnitPriority('isoWeek', 5); // PARSING
25342
25343 addRegexToken('w', match1to2);
25344 addRegexToken('ww', match1to2, match2);
25345 addRegexToken('W', match1to2);
25346 addRegexToken('WW', match1to2, match2);
25347 addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) {
25348 week[token.substr(0, 1)] = toInt(input);
25349 }); // HELPERS
25350 // LOCALES
25351
25352 function localeWeek(mom) {
25353 return weekOfYear(mom, this._week.dow, this._week.doy).week;
25354 }
25355
25356 var defaultLocaleWeek = {
25357 dow: 0,
25358 // Sunday is the first day of the week.
25359 doy: 6 // The week that contains Jan 6th is the first week of the year.
25360
25361 };
25362
25363 function localeFirstDayOfWeek() {
25364 return this._week.dow;
25365 }
25366
25367 function localeFirstDayOfYear() {
25368 return this._week.doy;
25369 } // MOMENTS
25370
25371
25372 function getSetWeek(input) {
25373 var week = this.localeData().week(this);
25374 return input == null ? week : this.add((input - week) * 7, 'd');
25375 }
25376
25377 function getSetISOWeek(input) {
25378 var week = weekOfYear(this, 1, 4).week;
25379 return input == null ? week : this.add((input - week) * 7, 'd');
25380 } // FORMATTING
25381
25382
25383 addFormatToken('d', 0, 'do', 'day');
25384 addFormatToken('dd', 0, 0, function (format) {
25385 return this.localeData().weekdaysMin(this, format);
25386 });
25387 addFormatToken('ddd', 0, 0, function (format) {
25388 return this.localeData().weekdaysShort(this, format);
25389 });
25390 addFormatToken('dddd', 0, 0, function (format) {
25391 return this.localeData().weekdays(this, format);
25392 });
25393 addFormatToken('e', 0, 0, 'weekday');
25394 addFormatToken('E', 0, 0, 'isoWeekday'); // ALIASES
25395
25396 addUnitAlias('day', 'd');
25397 addUnitAlias('weekday', 'e');
25398 addUnitAlias('isoWeekday', 'E'); // PRIORITY
25399
25400 addUnitPriority('day', 11);
25401 addUnitPriority('weekday', 11);
25402 addUnitPriority('isoWeekday', 11); // PARSING
25403
25404 addRegexToken('d', match1to2);
25405 addRegexToken('e', match1to2);
25406 addRegexToken('E', match1to2);
25407 addRegexToken('dd', function (isStrict, locale) {
25408 return locale.weekdaysMinRegex(isStrict);
25409 });
25410 addRegexToken('ddd', function (isStrict, locale) {
25411 return locale.weekdaysShortRegex(isStrict);
25412 });
25413 addRegexToken('dddd', function (isStrict, locale) {
25414 return locale.weekdaysRegex(isStrict);
25415 });
25416 addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
25417 var weekday = config._locale.weekdaysParse(input, token, config._strict); // if we didn't get a weekday name, mark the date as invalid
25418
25419
25420 if (weekday != null) {
25421 week.d = weekday;
25422 } else {
25423 getParsingFlags(config).invalidWeekday = input;
25424 }
25425 });
25426 addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
25427 week[token] = toInt(input);
25428 }); // HELPERS
25429
25430 function parseWeekday(input, locale) {
25431 if (typeof input !== 'string') {
25432 return input;
25433 }
25434
25435 if (!isNaN(input)) {
25436 return parseInt(input, 10);
25437 }
25438
25439 input = locale.weekdaysParse(input);
25440
25441 if (typeof input === 'number') {
25442 return input;
25443 }
25444
25445 return null;
25446 }
25447
25448 function parseIsoWeekday(input, locale) {
25449 if (typeof input === 'string') {
25450 return locale.weekdaysParse(input) % 7 || 7;
25451 }
25452
25453 return isNaN(input) ? null : input;
25454 } // LOCALES
25455
25456
25457 function shiftWeekdays(ws, n) {
25458 return ws.slice(n, 7).concat(ws.slice(0, n));
25459 }
25460
25461 var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_');
25462
25463 function localeWeekdays(m, format) {
25464 var weekdays = isArray(this._weekdays) ? this._weekdays : this._weekdays[m && m !== true && this._weekdays.isFormat.test(format) ? 'format' : 'standalone'];
25465 return m === true ? shiftWeekdays(weekdays, this._week.dow) : m ? weekdays[m.day()] : weekdays;
25466 }
25467
25468 var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');
25469
25470 function localeWeekdaysShort(m) {
25471 return m === true ? shiftWeekdays(this._weekdaysShort, this._week.dow) : m ? this._weekdaysShort[m.day()] : this._weekdaysShort;
25472 }
25473
25474 var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_');
25475
25476 function localeWeekdaysMin(m) {
25477 return m === true ? shiftWeekdays(this._weekdaysMin, this._week.dow) : m ? this._weekdaysMin[m.day()] : this._weekdaysMin;
25478 }
25479
25480 function handleStrictParse$1(weekdayName, format, strict) {
25481 var i,
25482 ii,
25483 mom,
25484 llc = weekdayName.toLocaleLowerCase();
25485
25486 if (!this._weekdaysParse) {
25487 this._weekdaysParse = [];
25488 this._shortWeekdaysParse = [];
25489 this._minWeekdaysParse = [];
25490
25491 for (i = 0; i < 7; ++i) {
25492 mom = createUTC([2000, 1]).day(i);
25493 this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase();
25494 this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase();
25495 this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
25496 }
25497 }
25498
25499 if (strict) {
25500 if (format === 'dddd') {
25501 ii = indexOf.call(this._weekdaysParse, llc);
25502 return ii !== -1 ? ii : null;
25503 } else if (format === 'ddd') {
25504 ii = indexOf.call(this._shortWeekdaysParse, llc);
25505 return ii !== -1 ? ii : null;
25506 } else {
25507 ii = indexOf.call(this._minWeekdaysParse, llc);
25508 return ii !== -1 ? ii : null;
25509 }
25510 } else {
25511 if (format === 'dddd') {
25512 ii = indexOf.call(this._weekdaysParse, llc);
25513
25514 if (ii !== -1) {
25515 return ii;
25516 }
25517
25518 ii = indexOf.call(this._shortWeekdaysParse, llc);
25519
25520 if (ii !== -1) {
25521 return ii;
25522 }
25523
25524 ii = indexOf.call(this._minWeekdaysParse, llc);
25525 return ii !== -1 ? ii : null;
25526 } else if (format === 'ddd') {
25527 ii = indexOf.call(this._shortWeekdaysParse, llc);
25528
25529 if (ii !== -1) {
25530 return ii;
25531 }
25532
25533 ii = indexOf.call(this._weekdaysParse, llc);
25534
25535 if (ii !== -1) {
25536 return ii;
25537 }
25538
25539 ii = indexOf.call(this._minWeekdaysParse, llc);
25540 return ii !== -1 ? ii : null;
25541 } else {
25542 ii = indexOf.call(this._minWeekdaysParse, llc);
25543
25544 if (ii !== -1) {
25545 return ii;
25546 }
25547
25548 ii = indexOf.call(this._weekdaysParse, llc);
25549
25550 if (ii !== -1) {
25551 return ii;
25552 }
25553
25554 ii = indexOf.call(this._shortWeekdaysParse, llc);
25555 return ii !== -1 ? ii : null;
25556 }
25557 }
25558 }
25559
25560 function localeWeekdaysParse(weekdayName, format, strict) {
25561 var i, mom, regex;
25562
25563 if (this._weekdaysParseExact) {
25564 return handleStrictParse$1.call(this, weekdayName, format, strict);
25565 }
25566
25567 if (!this._weekdaysParse) {
25568 this._weekdaysParse = [];
25569 this._minWeekdaysParse = [];
25570 this._shortWeekdaysParse = [];
25571 this._fullWeekdaysParse = [];
25572 }
25573
25574 for (i = 0; i < 7; i++) {
25575 // make the regex if we don't have it already
25576 mom = createUTC([2000, 1]).day(i);
25577
25578 if (strict && !this._fullWeekdaysParse[i]) {
25579 this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\\.?') + '$', 'i');
25580 this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$', 'i');
25581 this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$', 'i');
25582 }
25583
25584 if (!this._weekdaysParse[i]) {
25585 regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
25586 this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
25587 } // test the regex
25588
25589
25590 if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) {
25591 return i;
25592 } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) {
25593 return i;
25594 } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) {
25595 return i;
25596 } else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
25597 return i;
25598 }
25599 }
25600 } // MOMENTS
25601
25602
25603 function getSetDayOfWeek(input) {
25604 if (!this.isValid()) {
25605 return input != null ? this : NaN;
25606 }
25607
25608 var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
25609
25610 if (input != null) {
25611 input = parseWeekday(input, this.localeData());
25612 return this.add(input - day, 'd');
25613 } else {
25614 return day;
25615 }
25616 }
25617
25618 function getSetLocaleDayOfWeek(input) {
25619 if (!this.isValid()) {
25620 return input != null ? this : NaN;
25621 }
25622
25623 var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
25624 return input == null ? weekday : this.add(input - weekday, 'd');
25625 }
25626
25627 function getSetISODayOfWeek(input) {
25628 if (!this.isValid()) {
25629 return input != null ? this : NaN;
25630 } // behaves the same as moment#day except
25631 // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
25632 // as a setter, sunday should belong to the previous week.
25633
25634
25635 if (input != null) {
25636 var weekday = parseIsoWeekday(input, this.localeData());
25637 return this.day(this.day() % 7 ? weekday : weekday - 7);
25638 } else {
25639 return this.day() || 7;
25640 }
25641 }
25642
25643 var defaultWeekdaysRegex = matchWord;
25644
25645 function weekdaysRegex(isStrict) {
25646 if (this._weekdaysParseExact) {
25647 if (!hasOwnProp(this, '_weekdaysRegex')) {
25648 computeWeekdaysParse.call(this);
25649 }
25650
25651 if (isStrict) {
25652 return this._weekdaysStrictRegex;
25653 } else {
25654 return this._weekdaysRegex;
25655 }
25656 } else {
25657 if (!hasOwnProp(this, '_weekdaysRegex')) {
25658 this._weekdaysRegex = defaultWeekdaysRegex;
25659 }
25660
25661 return this._weekdaysStrictRegex && isStrict ? this._weekdaysStrictRegex : this._weekdaysRegex;
25662 }
25663 }
25664
25665 var defaultWeekdaysShortRegex = matchWord;
25666
25667 function weekdaysShortRegex(isStrict) {
25668 if (this._weekdaysParseExact) {
25669 if (!hasOwnProp(this, '_weekdaysRegex')) {
25670 computeWeekdaysParse.call(this);
25671 }
25672
25673 if (isStrict) {
25674 return this._weekdaysShortStrictRegex;
25675 } else {
25676 return this._weekdaysShortRegex;
25677 }
25678 } else {
25679 if (!hasOwnProp(this, '_weekdaysShortRegex')) {
25680 this._weekdaysShortRegex = defaultWeekdaysShortRegex;
25681 }
25682
25683 return this._weekdaysShortStrictRegex && isStrict ? this._weekdaysShortStrictRegex : this._weekdaysShortRegex;
25684 }
25685 }
25686
25687 var defaultWeekdaysMinRegex = matchWord;
25688
25689 function weekdaysMinRegex(isStrict) {
25690 if (this._weekdaysParseExact) {
25691 if (!hasOwnProp(this, '_weekdaysRegex')) {
25692 computeWeekdaysParse.call(this);
25693 }
25694
25695 if (isStrict) {
25696 return this._weekdaysMinStrictRegex;
25697 } else {
25698 return this._weekdaysMinRegex;
25699 }
25700 } else {
25701 if (!hasOwnProp(this, '_weekdaysMinRegex')) {
25702 this._weekdaysMinRegex = defaultWeekdaysMinRegex;
25703 }
25704
25705 return this._weekdaysMinStrictRegex && isStrict ? this._weekdaysMinStrictRegex : this._weekdaysMinRegex;
25706 }
25707 }
25708
25709 function computeWeekdaysParse() {
25710 function cmpLenRev(a, b) {
25711 return b.length - a.length;
25712 }
25713
25714 var minPieces = [],
25715 shortPieces = [],
25716 longPieces = [],
25717 mixedPieces = [],
25718 i,
25719 mom,
25720 minp,
25721 shortp,
25722 longp;
25723
25724 for (i = 0; i < 7; i++) {
25725 // make the regex if we don't have it already
25726 mom = createUTC([2000, 1]).day(i);
25727 minp = this.weekdaysMin(mom, '');
25728 shortp = this.weekdaysShort(mom, '');
25729 longp = this.weekdays(mom, '');
25730 minPieces.push(minp);
25731 shortPieces.push(shortp);
25732 longPieces.push(longp);
25733 mixedPieces.push(minp);
25734 mixedPieces.push(shortp);
25735 mixedPieces.push(longp);
25736 } // Sorting makes sure if one weekday (or abbr) is a prefix of another it
25737 // will match the longer piece.
25738
25739
25740 minPieces.sort(cmpLenRev);
25741 shortPieces.sort(cmpLenRev);
25742 longPieces.sort(cmpLenRev);
25743 mixedPieces.sort(cmpLenRev);
25744
25745 for (i = 0; i < 7; i++) {
25746 shortPieces[i] = regexEscape(shortPieces[i]);
25747 longPieces[i] = regexEscape(longPieces[i]);
25748 mixedPieces[i] = regexEscape(mixedPieces[i]);
25749 }
25750
25751 this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
25752 this._weekdaysShortRegex = this._weekdaysRegex;
25753 this._weekdaysMinRegex = this._weekdaysRegex;
25754 this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
25755 this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
25756 this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i');
25757 } // FORMATTING
25758
25759
25760 function hFormat() {
25761 return this.hours() % 12 || 12;
25762 }
25763
25764 function kFormat() {
25765 return this.hours() || 24;
25766 }
25767
25768 addFormatToken('H', ['HH', 2], 0, 'hour');
25769 addFormatToken('h', ['hh', 2], 0, hFormat);
25770 addFormatToken('k', ['kk', 2], 0, kFormat);
25771 addFormatToken('hmm', 0, 0, function () {
25772 return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
25773 });
25774 addFormatToken('hmmss', 0, 0, function () {
25775 return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2);
25776 });
25777 addFormatToken('Hmm', 0, 0, function () {
25778 return '' + this.hours() + zeroFill(this.minutes(), 2);
25779 });
25780 addFormatToken('Hmmss', 0, 0, function () {
25781 return '' + this.hours() + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2);
25782 });
25783
25784 function meridiem(token, lowercase) {
25785 addFormatToken(token, 0, 0, function () {
25786 return this.localeData().meridiem(this.hours(), this.minutes(), lowercase);
25787 });
25788 }
25789
25790 meridiem('a', true);
25791 meridiem('A', false); // ALIASES
25792
25793 addUnitAlias('hour', 'h'); // PRIORITY
25794
25795 addUnitPriority('hour', 13); // PARSING
25796
25797 function matchMeridiem(isStrict, locale) {
25798 return locale._meridiemParse;
25799 }
25800
25801 addRegexToken('a', matchMeridiem);
25802 addRegexToken('A', matchMeridiem);
25803 addRegexToken('H', match1to2);
25804 addRegexToken('h', match1to2);
25805 addRegexToken('k', match1to2);
25806 addRegexToken('HH', match1to2, match2);
25807 addRegexToken('hh', match1to2, match2);
25808 addRegexToken('kk', match1to2, match2);
25809 addRegexToken('hmm', match3to4);
25810 addRegexToken('hmmss', match5to6);
25811 addRegexToken('Hmm', match3to4);
25812 addRegexToken('Hmmss', match5to6);
25813 addParseToken(['H', 'HH'], HOUR);
25814 addParseToken(['k', 'kk'], function (input, array, config) {
25815 var kInput = toInt(input);
25816 array[HOUR] = kInput === 24 ? 0 : kInput;
25817 });
25818 addParseToken(['a', 'A'], function (input, array, config) {
25819 config._isPm = config._locale.isPM(input);
25820 config._meridiem = input;
25821 });
25822 addParseToken(['h', 'hh'], function (input, array, config) {
25823 array[HOUR] = toInt(input);
25824 getParsingFlags(config).bigHour = true;
25825 });
25826 addParseToken('hmm', function (input, array, config) {
25827 var pos = input.length - 2;
25828 array[HOUR] = toInt(input.substr(0, pos));
25829 array[MINUTE] = toInt(input.substr(pos));
25830 getParsingFlags(config).bigHour = true;
25831 });
25832 addParseToken('hmmss', function (input, array, config) {
25833 var pos1 = input.length - 4;
25834 var pos2 = input.length - 2;
25835 array[HOUR] = toInt(input.substr(0, pos1));
25836 array[MINUTE] = toInt(input.substr(pos1, 2));
25837 array[SECOND] = toInt(input.substr(pos2));
25838 getParsingFlags(config).bigHour = true;
25839 });
25840 addParseToken('Hmm', function (input, array, config) {
25841 var pos = input.length - 2;
25842 array[HOUR] = toInt(input.substr(0, pos));
25843 array[MINUTE] = toInt(input.substr(pos));
25844 });
25845 addParseToken('Hmmss', function (input, array, config) {
25846 var pos1 = input.length - 4;
25847 var pos2 = input.length - 2;
25848 array[HOUR] = toInt(input.substr(0, pos1));
25849 array[MINUTE] = toInt(input.substr(pos1, 2));
25850 array[SECOND] = toInt(input.substr(pos2));
25851 }); // LOCALES
25852
25853 function localeIsPM(input) {
25854 // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
25855 // Using charAt should be more compatible.
25856 return (input + '').toLowerCase().charAt(0) === 'p';
25857 }
25858
25859 var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i;
25860
25861 function localeMeridiem(hours, minutes, isLower) {
25862 if (hours > 11) {
25863 return isLower ? 'pm' : 'PM';
25864 } else {
25865 return isLower ? 'am' : 'AM';
25866 }
25867 } // MOMENTS
25868 // Setting the hour should keep the time, because the user explicitly
25869 // specified which hour they want. So trying to maintain the same hour (in
25870 // a new timezone) makes sense. Adding/subtracting hours does not follow
25871 // this rule.
25872
25873
25874 var getSetHour = makeGetSet('Hours', true);
25875 var baseConfig = {
25876 calendar: defaultCalendar,
25877 longDateFormat: defaultLongDateFormat,
25878 invalidDate: defaultInvalidDate,
25879 ordinal: defaultOrdinal,
25880 dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,
25881 relativeTime: defaultRelativeTime,
25882 months: defaultLocaleMonths,
25883 monthsShort: defaultLocaleMonthsShort,
25884 week: defaultLocaleWeek,
25885 weekdays: defaultLocaleWeekdays,
25886 weekdaysMin: defaultLocaleWeekdaysMin,
25887 weekdaysShort: defaultLocaleWeekdaysShort,
25888 meridiemParse: defaultLocaleMeridiemParse
25889 }; // internal storage for locale config files
25890
25891 var locales = {};
25892 var localeFamilies = {};
25893 var globalLocale;
25894
25895 function normalizeLocale(key) {
25896 return key ? key.toLowerCase().replace('_', '-') : key;
25897 } // pick the locale from the array
25898 // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
25899 // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
25900
25901
25902 function chooseLocale(names) {
25903 var i = 0,
25904 j,
25905 next,
25906 locale,
25907 split;
25908
25909 while (i < names.length) {
25910 split = normalizeLocale(names[i]).split('-');
25911 j = split.length;
25912 next = normalizeLocale(names[i + 1]);
25913 next = next ? next.split('-') : null;
25914
25915 while (j > 0) {
25916 locale = loadLocale(split.slice(0, j).join('-'));
25917
25918 if (locale) {
25919 return locale;
25920 }
25921
25922 if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
25923 //the next array item is better than a shallower substring of this one
25924 break;
25925 }
25926
25927 j--;
25928 }
25929
25930 i++;
25931 }
25932
25933 return globalLocale;
25934 }
25935
25936 function loadLocale(name) {
25937 var oldLocale = null; // TODO: Find a better way to register and load all the locales in Node
25938
25939 if (!locales[name] && 'object' !== 'undefined' && module && module.exports) {
25940 try {
25941 oldLocale = globalLocale._abbr;
25942 var aliasedRequire = commonjsRequire$1;
25943 aliasedRequire('./locale/' + name);
25944 getSetGlobalLocale(oldLocale);
25945 } catch (e) {}
25946 }
25947
25948 return locales[name];
25949 } // This function will load locale and then set the global locale. If
25950 // no arguments are passed in, it will simply return the current global
25951 // locale key.
25952
25953
25954 function getSetGlobalLocale(key, values) {
25955 var data;
25956
25957 if (key) {
25958 if (isUndefined(values)) {
25959 data = getLocale(key);
25960 } else {
25961 data = defineLocale(key, values);
25962 }
25963
25964 if (data) {
25965 // moment.duration._locale = moment._locale = data;
25966 globalLocale = data;
25967 } else {
25968 if (typeof console !== 'undefined' && console.warn) {
25969 //warn user if arguments are passed but the locale could not be set
25970 console.warn('Locale ' + key + ' not found. Did you forget to load it?');
25971 }
25972 }
25973 }
25974
25975 return globalLocale._abbr;
25976 }
25977
25978 function defineLocale(name, config) {
25979 if (config !== null) {
25980 var locale,
25981 parentConfig = baseConfig;
25982 config.abbr = name;
25983
25984 if (locales[name] != null) {
25985 deprecateSimple('defineLocaleOverride', 'use moment.updateLocale(localeName, config) to change ' + 'an existing locale. moment.defineLocale(localeName, ' + 'config) should only be used for creating a new locale ' + 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.');
25986 parentConfig = locales[name]._config;
25987 } else if (config.parentLocale != null) {
25988 if (locales[config.parentLocale] != null) {
25989 parentConfig = locales[config.parentLocale]._config;
25990 } else {
25991 locale = loadLocale(config.parentLocale);
25992
25993 if (locale != null) {
25994 parentConfig = locale._config;
25995 } else {
25996 if (!localeFamilies[config.parentLocale]) {
25997 localeFamilies[config.parentLocale] = [];
25998 }
25999
26000 localeFamilies[config.parentLocale].push({
26001 name: name,
26002 config: config
26003 });
26004 return null;
26005 }
26006 }
26007 }
26008
26009 locales[name] = new Locale(mergeConfigs(parentConfig, config));
26010
26011 if (localeFamilies[name]) {
26012 localeFamilies[name].forEach(function (x) {
26013 defineLocale(x.name, x.config);
26014 });
26015 } // backwards compat for now: also set the locale
26016 // make sure we set the locale AFTER all child locales have been
26017 // created, so we won't end up with the child locale set.
26018
26019
26020 getSetGlobalLocale(name);
26021 return locales[name];
26022 } else {
26023 // useful for testing
26024 delete locales[name];
26025 return null;
26026 }
26027 }
26028
26029 function updateLocale(name, config) {
26030 if (config != null) {
26031 var locale,
26032 tmpLocale,
26033 parentConfig = baseConfig; // MERGE
26034
26035 tmpLocale = loadLocale(name);
26036
26037 if (tmpLocale != null) {
26038 parentConfig = tmpLocale._config;
26039 }
26040
26041 config = mergeConfigs(parentConfig, config);
26042 locale = new Locale(config);
26043 locale.parentLocale = locales[name];
26044 locales[name] = locale; // backwards compat for now: also set the locale
26045
26046 getSetGlobalLocale(name);
26047 } else {
26048 // pass null for config to unupdate, useful for tests
26049 if (locales[name] != null) {
26050 if (locales[name].parentLocale != null) {
26051 locales[name] = locales[name].parentLocale;
26052 } else if (locales[name] != null) {
26053 delete locales[name];
26054 }
26055 }
26056 }
26057
26058 return locales[name];
26059 } // returns locale data
26060
26061
26062 function getLocale(key) {
26063 var locale;
26064
26065 if (key && key._locale && key._locale._abbr) {
26066 key = key._locale._abbr;
26067 }
26068
26069 if (!key) {
26070 return globalLocale;
26071 }
26072
26073 if (!isArray(key)) {
26074 //short-circuit everything else
26075 locale = loadLocale(key);
26076
26077 if (locale) {
26078 return locale;
26079 }
26080
26081 key = [key];
26082 }
26083
26084 return chooseLocale(key);
26085 }
26086
26087 function listLocales() {
26088 return keys(locales);
26089 }
26090
26091 function checkOverflow(m) {
26092 var overflow;
26093 var a = m._a;
26094
26095 if (a && getParsingFlags(m).overflow === -2) {
26096 overflow = a[MONTH] < 0 || a[MONTH] > 11 ? MONTH : a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE : a[HOUR] < 0 || a[HOUR] > 24 || a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0) ? HOUR : a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE : a[SECOND] < 0 || a[SECOND] > 59 ? SECOND : a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND : -1;
26097
26098 if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
26099 overflow = DATE;
26100 }
26101
26102 if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
26103 overflow = WEEK;
26104 }
26105
26106 if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
26107 overflow = WEEKDAY;
26108 }
26109
26110 getParsingFlags(m).overflow = overflow;
26111 }
26112
26113 return m;
26114 } // Pick the first defined of two or three arguments.
26115
26116
26117 function defaults(a, b, c) {
26118 if (a != null) {
26119 return a;
26120 }
26121
26122 if (b != null) {
26123 return b;
26124 }
26125
26126 return c;
26127 }
26128
26129 function currentDateArray(config) {
26130 // hooks is actually the exported moment object
26131 var nowValue = new Date(hooks.now());
26132
26133 if (config._useUTC) {
26134 return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()];
26135 }
26136
26137 return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
26138 } // convert an array to a date.
26139 // the array should mirror the parameters below
26140 // note: all values past the year are optional and will default to the lowest possible value.
26141 // [year, month, day , hour, minute, second, millisecond]
26142
26143
26144 function configFromArray(config) {
26145 var i,
26146 date,
26147 input = [],
26148 currentDate,
26149 expectedWeekday,
26150 yearToUse;
26151
26152 if (config._d) {
26153 return;
26154 }
26155
26156 currentDate = currentDateArray(config); //compute day of the year from weeks and weekdays
26157
26158 if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
26159 dayOfYearFromWeekInfo(config);
26160 } //if the day of the year is set, figure out what it is
26161
26162
26163 if (config._dayOfYear != null) {
26164 yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
26165
26166 if (config._dayOfYear > daysInYear(yearToUse) || config._dayOfYear === 0) {
26167 getParsingFlags(config)._overflowDayOfYear = true;
26168 }
26169
26170 date = createUTCDate(yearToUse, 0, config._dayOfYear);
26171 config._a[MONTH] = date.getUTCMonth();
26172 config._a[DATE] = date.getUTCDate();
26173 } // Default to current date.
26174 // * if no year, month, day of month are given, default to today
26175 // * if day of month is given, default month and year
26176 // * if month is given, default only year
26177 // * if year is given, don't default anything
26178
26179
26180 for (i = 0; i < 3 && config._a[i] == null; ++i) {
26181 config._a[i] = input[i] = currentDate[i];
26182 } // Zero out whatever was not defaulted, including time
26183
26184
26185 for (; i < 7; i++) {
26186 config._a[i] = input[i] = config._a[i] == null ? i === 2 ? 1 : 0 : config._a[i];
26187 } // Check for 24:00:00.000
26188
26189
26190 if (config._a[HOUR] === 24 && config._a[MINUTE] === 0 && config._a[SECOND] === 0 && config._a[MILLISECOND] === 0) {
26191 config._nextDay = true;
26192 config._a[HOUR] = 0;
26193 }
26194
26195 config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input);
26196 expectedWeekday = config._useUTC ? config._d.getUTCDay() : config._d.getDay(); // Apply timezone offset from input. The actual utcOffset can be changed
26197 // with parseZone.
26198
26199 if (config._tzm != null) {
26200 config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
26201 }
26202
26203 if (config._nextDay) {
26204 config._a[HOUR] = 24;
26205 } // check for mismatching day of week
26206
26207
26208 if (config._w && typeof config._w.d !== 'undefined' && config._w.d !== expectedWeekday) {
26209 getParsingFlags(config).weekdayMismatch = true;
26210 }
26211 }
26212
26213 function dayOfYearFromWeekInfo(config) {
26214 var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow;
26215 w = config._w;
26216
26217 if (w.GG != null || w.W != null || w.E != null) {
26218 dow = 1;
26219 doy = 4; // TODO: We need to take the current isoWeekYear, but that depends on
26220 // how we interpret now (local, utc, fixed offset). So create
26221 // a now version of current config (take local/utc/offset flags, and
26222 // create now).
26223
26224 weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year);
26225 week = defaults(w.W, 1);
26226 weekday = defaults(w.E, 1);
26227
26228 if (weekday < 1 || weekday > 7) {
26229 weekdayOverflow = true;
26230 }
26231 } else {
26232 dow = config._locale._week.dow;
26233 doy = config._locale._week.doy;
26234 var curWeek = weekOfYear(createLocal(), dow, doy);
26235 weekYear = defaults(w.gg, config._a[YEAR], curWeek.year); // Default to current week.
26236
26237 week = defaults(w.w, curWeek.week);
26238
26239 if (w.d != null) {
26240 // weekday -- low day numbers are considered next week
26241 weekday = w.d;
26242
26243 if (weekday < 0 || weekday > 6) {
26244 weekdayOverflow = true;
26245 }
26246 } else if (w.e != null) {
26247 // local weekday -- counting starts from beginning of week
26248 weekday = w.e + dow;
26249
26250 if (w.e < 0 || w.e > 6) {
26251 weekdayOverflow = true;
26252 }
26253 } else {
26254 // default to beginning of week
26255 weekday = dow;
26256 }
26257 }
26258
26259 if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
26260 getParsingFlags(config)._overflowWeeks = true;
26261 } else if (weekdayOverflow != null) {
26262 getParsingFlags(config)._overflowWeekday = true;
26263 } else {
26264 temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
26265 config._a[YEAR] = temp.year;
26266 config._dayOfYear = temp.dayOfYear;
26267 }
26268 } // iso 8601 regex
26269 // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
26270
26271
26272 var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;
26273 var basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;
26274 var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/;
26275 var isoDates = [['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/], ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/], ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/], ['GGGG-[W]WW', /\d{4}-W\d\d/, false], ['YYYY-DDD', /\d{4}-\d{3}/], ['YYYY-MM', /\d{4}-\d\d/, false], ['YYYYYYMMDD', /[+-]\d{10}/], ['YYYYMMDD', /\d{8}/], // YYYYMM is NOT allowed by the standard
26276 ['GGGG[W]WWE', /\d{4}W\d{3}/], ['GGGG[W]WW', /\d{4}W\d{2}/, false], ['YYYYDDD', /\d{7}/]]; // iso time formats and regexes
26277
26278 var isoTimes = [['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/], ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/], ['HH:mm:ss', /\d\d:\d\d:\d\d/], ['HH:mm', /\d\d:\d\d/], ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/], ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/], ['HHmmss', /\d\d\d\d\d\d/], ['HHmm', /\d\d\d\d/], ['HH', /\d\d/]];
26279 var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i; // date from iso format
26280
26281 function configFromISO(config) {
26282 var i,
26283 l,
26284 string = config._i,
26285 match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
26286 allowTime,
26287 dateFormat,
26288 timeFormat,
26289 tzFormat;
26290
26291 if (match) {
26292 getParsingFlags(config).iso = true;
26293
26294 for (i = 0, l = isoDates.length; i < l; i++) {
26295 if (isoDates[i][1].exec(match[1])) {
26296 dateFormat = isoDates[i][0];
26297 allowTime = isoDates[i][2] !== false;
26298 break;
26299 }
26300 }
26301
26302 if (dateFormat == null) {
26303 config._isValid = false;
26304 return;
26305 }
26306
26307 if (match[3]) {
26308 for (i = 0, l = isoTimes.length; i < l; i++) {
26309 if (isoTimes[i][1].exec(match[3])) {
26310 // match[2] should be 'T' or space
26311 timeFormat = (match[2] || ' ') + isoTimes[i][0];
26312 break;
26313 }
26314 }
26315
26316 if (timeFormat == null) {
26317 config._isValid = false;
26318 return;
26319 }
26320 }
26321
26322 if (!allowTime && timeFormat != null) {
26323 config._isValid = false;
26324 return;
26325 }
26326
26327 if (match[4]) {
26328 if (tzRegex.exec(match[4])) {
26329 tzFormat = 'Z';
26330 } else {
26331 config._isValid = false;
26332 return;
26333 }
26334 }
26335
26336 config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
26337 configFromStringAndFormat(config);
26338 } else {
26339 config._isValid = false;
26340 }
26341 } // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
26342
26343
26344 var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/;
26345
26346 function extractFromRFC2822Strings(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {
26347 var result = [untruncateYear(yearStr), defaultLocaleMonthsShort.indexOf(monthStr), parseInt(dayStr, 10), parseInt(hourStr, 10), parseInt(minuteStr, 10)];
26348
26349 if (secondStr) {
26350 result.push(parseInt(secondStr, 10));
26351 }
26352
26353 return result;
26354 }
26355
26356 function untruncateYear(yearStr) {
26357 var year = parseInt(yearStr, 10);
26358
26359 if (year <= 49) {
26360 return 2000 + year;
26361 } else if (year <= 999) {
26362 return 1900 + year;
26363 }
26364
26365 return year;
26366 }
26367
26368 function preprocessRFC2822(s) {
26369 // Remove comments and folding whitespace and replace multiple-spaces with a single space
26370 return s.replace(/\([^)]*\)|[\n\t]/g, ' ').replace(/(\s\s+)/g, ' ').replace(/^\s\s*/, '').replace(/\s\s*$/, '');
26371 }
26372
26373 function checkWeekday(weekdayStr, parsedInput, config) {
26374 if (weekdayStr) {
26375 // TODO: Replace the vanilla JS Date object with an indepentent day-of-week check.
26376 var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr),
26377 weekdayActual = new Date(parsedInput[0], parsedInput[1], parsedInput[2]).getDay();
26378
26379 if (weekdayProvided !== weekdayActual) {
26380 getParsingFlags(config).weekdayMismatch = true;
26381 config._isValid = false;
26382 return false;
26383 }
26384 }
26385
26386 return true;
26387 }
26388
26389 var obsOffsets = {
26390 UT: 0,
26391 GMT: 0,
26392 EDT: -4 * 60,
26393 EST: -5 * 60,
26394 CDT: -5 * 60,
26395 CST: -6 * 60,
26396 MDT: -6 * 60,
26397 MST: -7 * 60,
26398 PDT: -7 * 60,
26399 PST: -8 * 60
26400 };
26401
26402 function calculateOffset(obsOffset, militaryOffset, numOffset) {
26403 if (obsOffset) {
26404 return obsOffsets[obsOffset];
26405 } else if (militaryOffset) {
26406 // the only allowed military tz is Z
26407 return 0;
26408 } else {
26409 var hm = parseInt(numOffset, 10);
26410 var m = hm % 100,
26411 h = (hm - m) / 100;
26412 return h * 60 + m;
26413 }
26414 } // date and time from ref 2822 format
26415
26416
26417 function configFromRFC2822(config) {
26418 var match = rfc2822.exec(preprocessRFC2822(config._i));
26419
26420 if (match) {
26421 var parsedArray = extractFromRFC2822Strings(match[4], match[3], match[2], match[5], match[6], match[7]);
26422
26423 if (!checkWeekday(match[1], parsedArray, config)) {
26424 return;
26425 }
26426
26427 config._a = parsedArray;
26428 config._tzm = calculateOffset(match[8], match[9], match[10]);
26429 config._d = createUTCDate.apply(null, config._a);
26430
26431 config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
26432
26433 getParsingFlags(config).rfc2822 = true;
26434 } else {
26435 config._isValid = false;
26436 }
26437 } // date from iso format or fallback
26438
26439
26440 function configFromString(config) {
26441 var matched = aspNetJsonRegex.exec(config._i);
26442
26443 if (matched !== null) {
26444 config._d = new Date(+matched[1]);
26445 return;
26446 }
26447
26448 configFromISO(config);
26449
26450 if (config._isValid === false) {
26451 delete config._isValid;
26452 } else {
26453 return;
26454 }
26455
26456 configFromRFC2822(config);
26457
26458 if (config._isValid === false) {
26459 delete config._isValid;
26460 } else {
26461 return;
26462 } // Final attempt, use Input Fallback
26463
26464
26465 hooks.createFromInputFallback(config);
26466 }
26467
26468 hooks.createFromInputFallback = deprecate('value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' + 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' + 'discouraged and will be removed in an upcoming major release. Please refer to ' + 'http://momentjs.com/guides/#/warnings/js-date/ for more info.', function (config) {
26469 config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
26470 }); // constant that refers to the ISO standard
26471
26472 hooks.ISO_8601 = function () {}; // constant that refers to the RFC 2822 form
26473
26474
26475 hooks.RFC_2822 = function () {}; // date from string and format string
26476
26477
26478 function configFromStringAndFormat(config) {
26479 // TODO: Move this to another part of the creation flow to prevent circular deps
26480 if (config._f === hooks.ISO_8601) {
26481 configFromISO(config);
26482 return;
26483 }
26484
26485 if (config._f === hooks.RFC_2822) {
26486 configFromRFC2822(config);
26487 return;
26488 }
26489
26490 config._a = [];
26491 getParsingFlags(config).empty = true; // This array is used to make a Date, either with `new Date` or `Date.UTC`
26492
26493 var string = '' + config._i,
26494 i,
26495 parsedInput,
26496 tokens,
26497 token,
26498 skipped,
26499 stringLength = string.length,
26500 totalParsedInputLength = 0;
26501 tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];
26502
26503 for (i = 0; i < tokens.length; i++) {
26504 token = tokens[i];
26505 parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; // console.log('token', token, 'parsedInput', parsedInput,
26506 // 'regex', getParseRegexForToken(token, config));
26507
26508 if (parsedInput) {
26509 skipped = string.substr(0, string.indexOf(parsedInput));
26510
26511 if (skipped.length > 0) {
26512 getParsingFlags(config).unusedInput.push(skipped);
26513 }
26514
26515 string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
26516 totalParsedInputLength += parsedInput.length;
26517 } // don't parse if it's not a known token
26518
26519
26520 if (formatTokenFunctions[token]) {
26521 if (parsedInput) {
26522 getParsingFlags(config).empty = false;
26523 } else {
26524 getParsingFlags(config).unusedTokens.push(token);
26525 }
26526
26527 addTimeToArrayFromToken(token, parsedInput, config);
26528 } else if (config._strict && !parsedInput) {
26529 getParsingFlags(config).unusedTokens.push(token);
26530 }
26531 } // add remaining unparsed input length to the string
26532
26533
26534 getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength;
26535
26536 if (string.length > 0) {
26537 getParsingFlags(config).unusedInput.push(string);
26538 } // clear _12h flag if hour is <= 12
26539
26540
26541 if (config._a[HOUR] <= 12 && getParsingFlags(config).bigHour === true && config._a[HOUR] > 0) {
26542 getParsingFlags(config).bigHour = undefined;
26543 }
26544
26545 getParsingFlags(config).parsedDateParts = config._a.slice(0);
26546 getParsingFlags(config).meridiem = config._meridiem; // handle meridiem
26547
26548 config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem);
26549 configFromArray(config);
26550 checkOverflow(config);
26551 }
26552
26553 function meridiemFixWrap(locale, hour, meridiem) {
26554 var isPm;
26555
26556 if (meridiem == null) {
26557 // nothing to do
26558 return hour;
26559 }
26560
26561 if (locale.meridiemHour != null) {
26562 return locale.meridiemHour(hour, meridiem);
26563 } else if (locale.isPM != null) {
26564 // Fallback
26565 isPm = locale.isPM(meridiem);
26566
26567 if (isPm && hour < 12) {
26568 hour += 12;
26569 }
26570
26571 if (!isPm && hour === 12) {
26572 hour = 0;
26573 }
26574
26575 return hour;
26576 } else {
26577 // this is not supposed to happen
26578 return hour;
26579 }
26580 } // date from string and array of format strings
26581
26582
26583 function configFromStringAndArray(config) {
26584 var tempConfig, bestMoment, scoreToBeat, i, currentScore;
26585
26586 if (config._f.length === 0) {
26587 getParsingFlags(config).invalidFormat = true;
26588 config._d = new Date(NaN);
26589 return;
26590 }
26591
26592 for (i = 0; i < config._f.length; i++) {
26593 currentScore = 0;
26594 tempConfig = copyConfig({}, config);
26595
26596 if (config._useUTC != null) {
26597 tempConfig._useUTC = config._useUTC;
26598 }
26599
26600 tempConfig._f = config._f[i];
26601 configFromStringAndFormat(tempConfig);
26602
26603 if (!isValid(tempConfig)) {
26604 continue;
26605 } // if there is any input that was not parsed add a penalty for that format
26606
26607
26608 currentScore += getParsingFlags(tempConfig).charsLeftOver; //or tokens
26609
26610 currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
26611 getParsingFlags(tempConfig).score = currentScore;
26612
26613 if (scoreToBeat == null || currentScore < scoreToBeat) {
26614 scoreToBeat = currentScore;
26615 bestMoment = tempConfig;
26616 }
26617 }
26618
26619 extend(config, bestMoment || tempConfig);
26620 }
26621
26622 function configFromObject(config) {
26623 if (config._d) {
26624 return;
26625 }
26626
26627 var i = normalizeObjectUnits(config._i);
26628 config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) {
26629 return obj && parseInt(obj, 10);
26630 });
26631 configFromArray(config);
26632 }
26633
26634 function createFromConfig(config) {
26635 var res = new Moment(checkOverflow(prepareConfig(config)));
26636
26637 if (res._nextDay) {
26638 // Adding is smart enough around DST
26639 res.add(1, 'd');
26640 res._nextDay = undefined;
26641 }
26642
26643 return res;
26644 }
26645
26646 function prepareConfig(config) {
26647 var input = config._i,
26648 format = config._f;
26649 config._locale = config._locale || getLocale(config._l);
26650
26651 if (input === null || format === undefined && input === '') {
26652 return createInvalid({
26653 nullInput: true
26654 });
26655 }
26656
26657 if (typeof input === 'string') {
26658 config._i = input = config._locale.preparse(input);
26659 }
26660
26661 if (isMoment(input)) {
26662 return new Moment(checkOverflow(input));
26663 } else if (isDate(input)) {
26664 config._d = input;
26665 } else if (isArray(format)) {
26666 configFromStringAndArray(config);
26667 } else if (format) {
26668 configFromStringAndFormat(config);
26669 } else {
26670 configFromInput(config);
26671 }
26672
26673 if (!isValid(config)) {
26674 config._d = null;
26675 }
26676
26677 return config;
26678 }
26679
26680 function configFromInput(config) {
26681 var input = config._i;
26682
26683 if (isUndefined(input)) {
26684 config._d = new Date(hooks.now());
26685 } else if (isDate(input)) {
26686 config._d = new Date(input.valueOf());
26687 } else if (typeof input === 'string') {
26688 configFromString(config);
26689 } else if (isArray(input)) {
26690 config._a = map(input.slice(0), function (obj) {
26691 return parseInt(obj, 10);
26692 });
26693 configFromArray(config);
26694 } else if (isObject(input)) {
26695 configFromObject(config);
26696 } else if (isNumber(input)) {
26697 // from milliseconds
26698 config._d = new Date(input);
26699 } else {
26700 hooks.createFromInputFallback(config);
26701 }
26702 }
26703
26704 function createLocalOrUTC(input, format, locale, strict, isUTC) {
26705 var c = {};
26706
26707 if (locale === true || locale === false) {
26708 strict = locale;
26709 locale = undefined;
26710 }
26711
26712 if (isObject(input) && isObjectEmpty(input) || isArray(input) && input.length === 0) {
26713 input = undefined;
26714 } // object construction must be done this way.
26715 // https://github.com/moment/moment/issues/1423
26716
26717
26718 c._isAMomentObject = true;
26719 c._useUTC = c._isUTC = isUTC;
26720 c._l = locale;
26721 c._i = input;
26722 c._f = format;
26723 c._strict = strict;
26724 return createFromConfig(c);
26725 }
26726
26727 function createLocal(input, format, locale, strict) {
26728 return createLocalOrUTC(input, format, locale, strict, false);
26729 }
26730
26731 var prototypeMin = deprecate('moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/', function () {
26732 var other = createLocal.apply(null, arguments);
26733
26734 if (this.isValid() && other.isValid()) {
26735 return other < this ? this : other;
26736 } else {
26737 return createInvalid();
26738 }
26739 });
26740 var prototypeMax = deprecate('moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/', function () {
26741 var other = createLocal.apply(null, arguments);
26742
26743 if (this.isValid() && other.isValid()) {
26744 return other > this ? this : other;
26745 } else {
26746 return createInvalid();
26747 }
26748 }); // Pick a moment m from moments so that m[fn](other) is true for all
26749 // other. This relies on the function fn to be transitive.
26750 //
26751 // moments should either be an array of moment objects or an array, whose
26752 // first element is an array of moment objects.
26753
26754 function pickBy(fn, moments) {
26755 var res, i;
26756
26757 if (moments.length === 1 && isArray(moments[0])) {
26758 moments = moments[0];
26759 }
26760
26761 if (!moments.length) {
26762 return createLocal();
26763 }
26764
26765 res = moments[0];
26766
26767 for (i = 1; i < moments.length; ++i) {
26768 if (!moments[i].isValid() || moments[i][fn](res)) {
26769 res = moments[i];
26770 }
26771 }
26772
26773 return res;
26774 } // TODO: Use [].sort instead?
26775
26776
26777 function min() {
26778 var args = [].slice.call(arguments, 0);
26779 return pickBy('isBefore', args);
26780 }
26781
26782 function max() {
26783 var args = [].slice.call(arguments, 0);
26784 return pickBy('isAfter', args);
26785 }
26786
26787 var now = function () {
26788 return Date.now ? Date.now() : +new Date();
26789 };
26790
26791 var ordering = ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond'];
26792
26793 function isDurationValid(m) {
26794 for (var key in m) {
26795 if (!(indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])))) {
26796 return false;
26797 }
26798 }
26799
26800 var unitHasDecimal = false;
26801
26802 for (var i = 0; i < ordering.length; ++i) {
26803 if (m[ordering[i]]) {
26804 if (unitHasDecimal) {
26805 return false; // only allow non-integers for smallest unit
26806 }
26807
26808 if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) {
26809 unitHasDecimal = true;
26810 }
26811 }
26812 }
26813
26814 return true;
26815 }
26816
26817 function isValid$1() {
26818 return this._isValid;
26819 }
26820
26821 function createInvalid$1() {
26822 return createDuration(NaN);
26823 }
26824
26825 function Duration(duration) {
26826 var normalizedInput = normalizeObjectUnits(duration),
26827 years = normalizedInput.year || 0,
26828 quarters = normalizedInput.quarter || 0,
26829 months = normalizedInput.month || 0,
26830 weeks = normalizedInput.week || normalizedInput.isoWeek || 0,
26831 days = normalizedInput.day || 0,
26832 hours = normalizedInput.hour || 0,
26833 minutes = normalizedInput.minute || 0,
26834 seconds = normalizedInput.second || 0,
26835 milliseconds = normalizedInput.millisecond || 0;
26836 this._isValid = isDurationValid(normalizedInput); // representation for dateAddRemove
26837
26838 this._milliseconds = +milliseconds + seconds * 1e3 + // 1000
26839 minutes * 6e4 + // 1000 * 60
26840 hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
26841 // Because of dateAddRemove treats 24 hours as different from a
26842 // day when working around DST, we need to store them separately
26843
26844 this._days = +days + weeks * 7; // It is impossible to translate months into days without knowing
26845 // which months you are are talking about, so we have to store
26846 // it separately.
26847
26848 this._months = +months + quarters * 3 + years * 12;
26849 this._data = {};
26850 this._locale = getLocale();
26851
26852 this._bubble();
26853 }
26854
26855 function isDuration(obj) {
26856 return obj instanceof Duration;
26857 }
26858
26859 function absRound(number) {
26860 if (number < 0) {
26861 return Math.round(-1 * number) * -1;
26862 } else {
26863 return Math.round(number);
26864 }
26865 } // FORMATTING
26866
26867
26868 function offset(token, separator) {
26869 addFormatToken(token, 0, 0, function () {
26870 var offset = this.utcOffset();
26871 var sign = '+';
26872
26873 if (offset < 0) {
26874 offset = -offset;
26875 sign = '-';
26876 }
26877
26878 return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~offset % 60, 2);
26879 });
26880 }
26881
26882 offset('Z', ':');
26883 offset('ZZ', ''); // PARSING
26884
26885 addRegexToken('Z', matchShortOffset);
26886 addRegexToken('ZZ', matchShortOffset);
26887 addParseToken(['Z', 'ZZ'], function (input, array, config) {
26888 config._useUTC = true;
26889 config._tzm = offsetFromString(matchShortOffset, input);
26890 }); // HELPERS
26891 // timezone chunker
26892 // '+10:00' > ['10', '00']
26893 // '-1530' > ['-15', '30']
26894
26895 var chunkOffset = /([\+\-]|\d\d)/gi;
26896
26897 function offsetFromString(matcher, string) {
26898 var matches = (string || '').match(matcher);
26899
26900 if (matches === null) {
26901 return null;
26902 }
26903
26904 var chunk = matches[matches.length - 1] || [];
26905 var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
26906 var minutes = +(parts[1] * 60) + toInt(parts[2]);
26907 return minutes === 0 ? 0 : parts[0] === '+' ? minutes : -minutes;
26908 } // Return a moment from input, that is local/utc/zone equivalent to model.
26909
26910
26911 function cloneWithOffset(input, model) {
26912 var res, diff;
26913
26914 if (model._isUTC) {
26915 res = model.clone();
26916 diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf(); // Use low-level api, because this fn is low-level api.
26917
26918 res._d.setTime(res._d.valueOf() + diff);
26919
26920 hooks.updateOffset(res, false);
26921 return res;
26922 } else {
26923 return createLocal(input).local();
26924 }
26925 }
26926
26927 function getDateOffset(m) {
26928 // On Firefox.24 Date#getTimezoneOffset returns a floating point.
26929 // https://github.com/moment/moment/pull/1871
26930 return -Math.round(m._d.getTimezoneOffset() / 15) * 15;
26931 } // HOOKS
26932 // This function will be called whenever a moment is mutated.
26933 // It is intended to keep the offset in sync with the timezone.
26934
26935
26936 hooks.updateOffset = function () {}; // MOMENTS
26937 // keepLocalTime = true means only change the timezone, without
26938 // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
26939 // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
26940 // +0200, so we adjust the time as needed, to be valid.
26941 //
26942 // Keeping the time actually adds/subtracts (one hour)
26943 // from the actual represented time. That is why we call updateOffset
26944 // a second time. In case it wants us to change the offset again
26945 // _changeInProgress == true case, then we have to adjust, because
26946 // there is no such time in the given timezone.
26947
26948
26949 function getSetOffset(input, keepLocalTime, keepMinutes) {
26950 var offset = this._offset || 0,
26951 localAdjust;
26952
26953 if (!this.isValid()) {
26954 return input != null ? this : NaN;
26955 }
26956
26957 if (input != null) {
26958 if (typeof input === 'string') {
26959 input = offsetFromString(matchShortOffset, input);
26960
26961 if (input === null) {
26962 return this;
26963 }
26964 } else if (Math.abs(input) < 16 && !keepMinutes) {
26965 input = input * 60;
26966 }
26967
26968 if (!this._isUTC && keepLocalTime) {
26969 localAdjust = getDateOffset(this);
26970 }
26971
26972 this._offset = input;
26973 this._isUTC = true;
26974
26975 if (localAdjust != null) {
26976 this.add(localAdjust, 'm');
26977 }
26978
26979 if (offset !== input) {
26980 if (!keepLocalTime || this._changeInProgress) {
26981 addSubtract(this, createDuration(input - offset, 'm'), 1, false);
26982 } else if (!this._changeInProgress) {
26983 this._changeInProgress = true;
26984 hooks.updateOffset(this, true);
26985 this._changeInProgress = null;
26986 }
26987 }
26988
26989 return this;
26990 } else {
26991 return this._isUTC ? offset : getDateOffset(this);
26992 }
26993 }
26994
26995 function getSetZone(input, keepLocalTime) {
26996 if (input != null) {
26997 if (typeof input !== 'string') {
26998 input = -input;
26999 }
27000
27001 this.utcOffset(input, keepLocalTime);
27002 return this;
27003 } else {
27004 return -this.utcOffset();
27005 }
27006 }
27007
27008 function setOffsetToUTC(keepLocalTime) {
27009 return this.utcOffset(0, keepLocalTime);
27010 }
27011
27012 function setOffsetToLocal(keepLocalTime) {
27013 if (this._isUTC) {
27014 this.utcOffset(0, keepLocalTime);
27015 this._isUTC = false;
27016
27017 if (keepLocalTime) {
27018 this.subtract(getDateOffset(this), 'm');
27019 }
27020 }
27021
27022 return this;
27023 }
27024
27025 function setOffsetToParsedOffset() {
27026 if (this._tzm != null) {
27027 this.utcOffset(this._tzm, false, true);
27028 } else if (typeof this._i === 'string') {
27029 var tZone = offsetFromString(matchOffset, this._i);
27030
27031 if (tZone != null) {
27032 this.utcOffset(tZone);
27033 } else {
27034 this.utcOffset(0, true);
27035 }
27036 }
27037
27038 return this;
27039 }
27040
27041 function hasAlignedHourOffset(input) {
27042 if (!this.isValid()) {
27043 return false;
27044 }
27045
27046 input = input ? createLocal(input).utcOffset() : 0;
27047 return (this.utcOffset() - input) % 60 === 0;
27048 }
27049
27050 function isDaylightSavingTime() {
27051 return this.utcOffset() > this.clone().month(0).utcOffset() || this.utcOffset() > this.clone().month(5).utcOffset();
27052 }
27053
27054 function isDaylightSavingTimeShifted() {
27055 if (!isUndefined(this._isDSTShifted)) {
27056 return this._isDSTShifted;
27057 }
27058
27059 var c = {};
27060 copyConfig(c, this);
27061 c = prepareConfig(c);
27062
27063 if (c._a) {
27064 var other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
27065 this._isDSTShifted = this.isValid() && compareArrays(c._a, other.toArray()) > 0;
27066 } else {
27067 this._isDSTShifted = false;
27068 }
27069
27070 return this._isDSTShifted;
27071 }
27072
27073 function isLocal() {
27074 return this.isValid() ? !this._isUTC : false;
27075 }
27076
27077 function isUtcOffset() {
27078 return this.isValid() ? this._isUTC : false;
27079 }
27080
27081 function isUtc() {
27082 return this.isValid() ? this._isUTC && this._offset === 0 : false;
27083 } // ASP.NET json date format regex
27084
27085
27086 var aspNetRegex = /^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/; // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
27087 // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
27088 // and further modified to allow for strings containing both week and day
27089
27090 var isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
27091
27092 function createDuration(input, key) {
27093 var duration = input,
27094 // matching against regexp is expensive, do it on demand
27095 match = null,
27096 sign,
27097 ret,
27098 diffRes;
27099
27100 if (isDuration(input)) {
27101 duration = {
27102 ms: input._milliseconds,
27103 d: input._days,
27104 M: input._months
27105 };
27106 } else if (isNumber(input)) {
27107 duration = {};
27108
27109 if (key) {
27110 duration[key] = input;
27111 } else {
27112 duration.milliseconds = input;
27113 }
27114 } else if (!!(match = aspNetRegex.exec(input))) {
27115 sign = match[1] === '-' ? -1 : 1;
27116 duration = {
27117 y: 0,
27118 d: toInt(match[DATE]) * sign,
27119 h: toInt(match[HOUR]) * sign,
27120 m: toInt(match[MINUTE]) * sign,
27121 s: toInt(match[SECOND]) * sign,
27122 ms: toInt(absRound(match[MILLISECOND] * 1000)) * sign // the millisecond decimal point is included in the match
27123
27124 };
27125 } else if (!!(match = isoRegex.exec(input))) {
27126 sign = match[1] === '-' ? -1 : 1;
27127 duration = {
27128 y: parseIso(match[2], sign),
27129 M: parseIso(match[3], sign),
27130 w: parseIso(match[4], sign),
27131 d: parseIso(match[5], sign),
27132 h: parseIso(match[6], sign),
27133 m: parseIso(match[7], sign),
27134 s: parseIso(match[8], sign)
27135 };
27136 } else if (duration == null) {
27137 // checks for null or undefined
27138 duration = {};
27139 } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) {
27140 diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to));
27141 duration = {};
27142 duration.ms = diffRes.milliseconds;
27143 duration.M = diffRes.months;
27144 }
27145
27146 ret = new Duration(duration);
27147
27148 if (isDuration(input) && hasOwnProp(input, '_locale')) {
27149 ret._locale = input._locale;
27150 }
27151
27152 return ret;
27153 }
27154
27155 createDuration.fn = Duration.prototype;
27156 createDuration.invalid = createInvalid$1;
27157
27158 function parseIso(inp, sign) {
27159 // We'd normally use ~~inp for this, but unfortunately it also
27160 // converts floats to ints.
27161 // inp may be undefined, so careful calling replace on it.
27162 var res = inp && parseFloat(inp.replace(',', '.')); // apply sign while we're at it
27163
27164 return (isNaN(res) ? 0 : res) * sign;
27165 }
27166
27167 function positiveMomentsDifference(base, other) {
27168 var res = {};
27169 res.months = other.month() - base.month() + (other.year() - base.year()) * 12;
27170
27171 if (base.clone().add(res.months, 'M').isAfter(other)) {
27172 --res.months;
27173 }
27174
27175 res.milliseconds = +other - +base.clone().add(res.months, 'M');
27176 return res;
27177 }
27178
27179 function momentsDifference(base, other) {
27180 var res;
27181
27182 if (!(base.isValid() && other.isValid())) {
27183 return {
27184 milliseconds: 0,
27185 months: 0
27186 };
27187 }
27188
27189 other = cloneWithOffset(other, base);
27190
27191 if (base.isBefore(other)) {
27192 res = positiveMomentsDifference(base, other);
27193 } else {
27194 res = positiveMomentsDifference(other, base);
27195 res.milliseconds = -res.milliseconds;
27196 res.months = -res.months;
27197 }
27198
27199 return res;
27200 } // TODO: remove 'name' arg after deprecation is removed
27201
27202
27203 function createAdder(direction, name) {
27204 return function (val, period) {
27205 var dur, tmp; //invert the arguments, but complain about it
27206
27207 if (period !== null && !isNaN(+period)) {
27208 deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' + 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.');
27209 tmp = val;
27210 val = period;
27211 period = tmp;
27212 }
27213
27214 val = typeof val === 'string' ? +val : val;
27215 dur = createDuration(val, period);
27216 addSubtract(this, dur, direction);
27217 return this;
27218 };
27219 }
27220
27221 function addSubtract(mom, duration, isAdding, updateOffset) {
27222 var milliseconds = duration._milliseconds,
27223 days = absRound(duration._days),
27224 months = absRound(duration._months);
27225
27226 if (!mom.isValid()) {
27227 // No op
27228 return;
27229 }
27230
27231 updateOffset = updateOffset == null ? true : updateOffset;
27232
27233 if (months) {
27234 setMonth(mom, get(mom, 'Month') + months * isAdding);
27235 }
27236
27237 if (days) {
27238 set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);
27239 }
27240
27241 if (milliseconds) {
27242 mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
27243 }
27244
27245 if (updateOffset) {
27246 hooks.updateOffset(mom, days || months);
27247 }
27248 }
27249
27250 var add = createAdder(1, 'add');
27251 var subtract = createAdder(-1, 'subtract');
27252
27253 function getCalendarFormat(myMoment, now) {
27254 var diff = myMoment.diff(now, 'days', true);
27255 return diff < -6 ? 'sameElse' : diff < -1 ? 'lastWeek' : diff < 0 ? 'lastDay' : diff < 1 ? 'sameDay' : diff < 2 ? 'nextDay' : diff < 7 ? 'nextWeek' : 'sameElse';
27256 }
27257
27258 function calendar$1(time, formats) {
27259 // We want to compare the start of today, vs this.
27260 // Getting start-of-today depends on whether we're local/utc/offset or not.
27261 var now = time || createLocal(),
27262 sod = cloneWithOffset(now, this).startOf('day'),
27263 format = hooks.calendarFormat(this, sod) || 'sameElse';
27264 var output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]);
27265 return this.format(output || this.localeData().calendar(format, this, createLocal(now)));
27266 }
27267
27268 function clone() {
27269 return new Moment(this);
27270 }
27271
27272 function isAfter(input, units) {
27273 var localInput = isMoment(input) ? input : createLocal(input);
27274
27275 if (!(this.isValid() && localInput.isValid())) {
27276 return false;
27277 }
27278
27279 units = normalizeUnits(units) || 'millisecond';
27280
27281 if (units === 'millisecond') {
27282 return this.valueOf() > localInput.valueOf();
27283 } else {
27284 return localInput.valueOf() < this.clone().startOf(units).valueOf();
27285 }
27286 }
27287
27288 function isBefore(input, units) {
27289 var localInput = isMoment(input) ? input : createLocal(input);
27290
27291 if (!(this.isValid() && localInput.isValid())) {
27292 return false;
27293 }
27294
27295 units = normalizeUnits(units) || 'millisecond';
27296
27297 if (units === 'millisecond') {
27298 return this.valueOf() < localInput.valueOf();
27299 } else {
27300 return this.clone().endOf(units).valueOf() < localInput.valueOf();
27301 }
27302 }
27303
27304 function isBetween(from, to, units, inclusivity) {
27305 var localFrom = isMoment(from) ? from : createLocal(from),
27306 localTo = isMoment(to) ? to : createLocal(to);
27307
27308 if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) {
27309 return false;
27310 }
27311
27312 inclusivity = inclusivity || '()';
27313 return (inclusivity[0] === '(' ? this.isAfter(localFrom, units) : !this.isBefore(localFrom, units)) && (inclusivity[1] === ')' ? this.isBefore(localTo, units) : !this.isAfter(localTo, units));
27314 }
27315
27316 function isSame(input, units) {
27317 var localInput = isMoment(input) ? input : createLocal(input),
27318 inputMs;
27319
27320 if (!(this.isValid() && localInput.isValid())) {
27321 return false;
27322 }
27323
27324 units = normalizeUnits(units) || 'millisecond';
27325
27326 if (units === 'millisecond') {
27327 return this.valueOf() === localInput.valueOf();
27328 } else {
27329 inputMs = localInput.valueOf();
27330 return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf();
27331 }
27332 }
27333
27334 function isSameOrAfter(input, units) {
27335 return this.isSame(input, units) || this.isAfter(input, units);
27336 }
27337
27338 function isSameOrBefore(input, units) {
27339 return this.isSame(input, units) || this.isBefore(input, units);
27340 }
27341
27342 function diff(input, units, asFloat) {
27343 var that, zoneDelta, output;
27344
27345 if (!this.isValid()) {
27346 return NaN;
27347 }
27348
27349 that = cloneWithOffset(input, this);
27350
27351 if (!that.isValid()) {
27352 return NaN;
27353 }
27354
27355 zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
27356 units = normalizeUnits(units);
27357
27358 switch (units) {
27359 case 'year':
27360 output = monthDiff(this, that) / 12;
27361 break;
27362
27363 case 'month':
27364 output = monthDiff(this, that);
27365 break;
27366
27367 case 'quarter':
27368 output = monthDiff(this, that) / 3;
27369 break;
27370
27371 case 'second':
27372 output = (this - that) / 1e3;
27373 break;
27374 // 1000
27375
27376 case 'minute':
27377 output = (this - that) / 6e4;
27378 break;
27379 // 1000 * 60
27380
27381 case 'hour':
27382 output = (this - that) / 36e5;
27383 break;
27384 // 1000 * 60 * 60
27385
27386 case 'day':
27387 output = (this - that - zoneDelta) / 864e5;
27388 break;
27389 // 1000 * 60 * 60 * 24, negate dst
27390
27391 case 'week':
27392 output = (this - that - zoneDelta) / 6048e5;
27393 break;
27394 // 1000 * 60 * 60 * 24 * 7, negate dst
27395
27396 default:
27397 output = this - that;
27398 }
27399
27400 return asFloat ? output : absFloor(output);
27401 }
27402
27403 function monthDiff(a, b) {
27404 // difference in months
27405 var wholeMonthDiff = (b.year() - a.year()) * 12 + (b.month() - a.month()),
27406 // b is in (anchor - 1 month, anchor + 1 month)
27407 anchor = a.clone().add(wholeMonthDiff, 'months'),
27408 anchor2,
27409 adjust;
27410
27411 if (b - anchor < 0) {
27412 anchor2 = a.clone().add(wholeMonthDiff - 1, 'months'); // linear across the month
27413
27414 adjust = (b - anchor) / (anchor - anchor2);
27415 } else {
27416 anchor2 = a.clone().add(wholeMonthDiff + 1, 'months'); // linear across the month
27417
27418 adjust = (b - anchor) / (anchor2 - anchor);
27419 } //check for negative zero, return zero if negative zero
27420
27421
27422 return -(wholeMonthDiff + adjust) || 0;
27423 }
27424
27425 hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
27426 hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';
27427
27428 function toString() {
27429 return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
27430 }
27431
27432 function toISOString(keepOffset) {
27433 if (!this.isValid()) {
27434 return null;
27435 }
27436
27437 var utc = keepOffset !== true;
27438 var m = utc ? this.clone().utc() : this;
27439
27440 if (m.year() < 0 || m.year() > 9999) {
27441 return formatMoment(m, utc ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ');
27442 }
27443
27444 if (isFunction(Date.prototype.toISOString)) {
27445 // native implementation is ~50x faster, use it when we can
27446 if (utc) {
27447 return this.toDate().toISOString();
27448 } else {
27449 return new Date(this.valueOf() + this.utcOffset() * 60 * 1000).toISOString().replace('Z', formatMoment(m, 'Z'));
27450 }
27451 }
27452
27453 return formatMoment(m, utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ');
27454 }
27455 /**
27456 * Return a human readable representation of a moment that can
27457 * also be evaluated to get a new moment which is the same
27458 *
27459 * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
27460 */
27461
27462
27463 function inspect() {
27464 if (!this.isValid()) {
27465 return 'moment.invalid(/* ' + this._i + ' */)';
27466 }
27467
27468 var func = 'moment';
27469 var zone = '';
27470
27471 if (!this.isLocal()) {
27472 func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
27473 zone = 'Z';
27474 }
27475
27476 var prefix = '[' + func + '("]';
27477 var year = 0 <= this.year() && this.year() <= 9999 ? 'YYYY' : 'YYYYYY';
27478 var datetime = '-MM-DD[T]HH:mm:ss.SSS';
27479 var suffix = zone + '[")]';
27480 return this.format(prefix + year + datetime + suffix);
27481 }
27482
27483 function format(inputString) {
27484 if (!inputString) {
27485 inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat;
27486 }
27487
27488 var output = formatMoment(this, inputString);
27489 return this.localeData().postformat(output);
27490 }
27491
27492 function from(time, withoutSuffix) {
27493 if (this.isValid() && (isMoment(time) && time.isValid() || createLocal(time).isValid())) {
27494 return createDuration({
27495 to: this,
27496 from: time
27497 }).locale(this.locale()).humanize(!withoutSuffix);
27498 } else {
27499 return this.localeData().invalidDate();
27500 }
27501 }
27502
27503 function fromNow(withoutSuffix) {
27504 return this.from(createLocal(), withoutSuffix);
27505 }
27506
27507 function to(time, withoutSuffix) {
27508 if (this.isValid() && (isMoment(time) && time.isValid() || createLocal(time).isValid())) {
27509 return createDuration({
27510 from: this,
27511 to: time
27512 }).locale(this.locale()).humanize(!withoutSuffix);
27513 } else {
27514 return this.localeData().invalidDate();
27515 }
27516 }
27517
27518 function toNow(withoutSuffix) {
27519 return this.to(createLocal(), withoutSuffix);
27520 } // If passed a locale key, it will set the locale for this
27521 // instance. Otherwise, it will return the locale configuration
27522 // variables for this instance.
27523
27524
27525 function locale(key) {
27526 var newLocaleData;
27527
27528 if (key === undefined) {
27529 return this._locale._abbr;
27530 } else {
27531 newLocaleData = getLocale(key);
27532
27533 if (newLocaleData != null) {
27534 this._locale = newLocaleData;
27535 }
27536
27537 return this;
27538 }
27539 }
27540
27541 var lang = deprecate('moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', function (key) {
27542 if (key === undefined) {
27543 return this.localeData();
27544 } else {
27545 return this.locale(key);
27546 }
27547 });
27548
27549 function localeData() {
27550 return this._locale;
27551 }
27552
27553 var MS_PER_SECOND = 1000;
27554 var MS_PER_MINUTE = 60 * MS_PER_SECOND;
27555 var MS_PER_HOUR = 60 * MS_PER_MINUTE;
27556 var MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR; // actual modulo - handles negative numbers (for dates before 1970):
27557
27558 function mod$1(dividend, divisor) {
27559 return (dividend % divisor + divisor) % divisor;
27560 }
27561
27562 function localStartOfDate(y, m, d) {
27563 // the date constructor remaps years 0-99 to 1900-1999
27564 if (y < 100 && y >= 0) {
27565 // preserve leap years using a full 400 year cycle, then reset
27566 return new Date(y + 400, m, d) - MS_PER_400_YEARS;
27567 } else {
27568 return new Date(y, m, d).valueOf();
27569 }
27570 }
27571
27572 function utcStartOfDate(y, m, d) {
27573 // Date.UTC remaps years 0-99 to 1900-1999
27574 if (y < 100 && y >= 0) {
27575 // preserve leap years using a full 400 year cycle, then reset
27576 return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS;
27577 } else {
27578 return Date.UTC(y, m, d);
27579 }
27580 }
27581
27582 function startOf(units) {
27583 var time;
27584 units = normalizeUnits(units);
27585
27586 if (units === undefined || units === 'millisecond' || !this.isValid()) {
27587 return this;
27588 }
27589
27590 var startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
27591
27592 switch (units) {
27593 case 'year':
27594 time = startOfDate(this.year(), 0, 1);
27595 break;
27596
27597 case 'quarter':
27598 time = startOfDate(this.year(), this.month() - this.month() % 3, 1);
27599 break;
27600
27601 case 'month':
27602 time = startOfDate(this.year(), this.month(), 1);
27603 break;
27604
27605 case 'week':
27606 time = startOfDate(this.year(), this.month(), this.date() - this.weekday());
27607 break;
27608
27609 case 'isoWeek':
27610 time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1));
27611 break;
27612
27613 case 'day':
27614 case 'date':
27615 time = startOfDate(this.year(), this.month(), this.date());
27616 break;
27617
27618 case 'hour':
27619 time = this._d.valueOf();
27620 time -= mod$1(time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR);
27621 break;
27622
27623 case 'minute':
27624 time = this._d.valueOf();
27625 time -= mod$1(time, MS_PER_MINUTE);
27626 break;
27627
27628 case 'second':
27629 time = this._d.valueOf();
27630 time -= mod$1(time, MS_PER_SECOND);
27631 break;
27632 }
27633
27634 this._d.setTime(time);
27635
27636 hooks.updateOffset(this, true);
27637 return this;
27638 }
27639
27640 function endOf(units) {
27641 var time;
27642 units = normalizeUnits(units);
27643
27644 if (units === undefined || units === 'millisecond' || !this.isValid()) {
27645 return this;
27646 }
27647
27648 var startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
27649
27650 switch (units) {
27651 case 'year':
27652 time = startOfDate(this.year() + 1, 0, 1) - 1;
27653 break;
27654
27655 case 'quarter':
27656 time = startOfDate(this.year(), this.month() - this.month() % 3 + 3, 1) - 1;
27657 break;
27658
27659 case 'month':
27660 time = startOfDate(this.year(), this.month() + 1, 1) - 1;
27661 break;
27662
27663 case 'week':
27664 time = startOfDate(this.year(), this.month(), this.date() - this.weekday() + 7) - 1;
27665 break;
27666
27667 case 'isoWeek':
27668 time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1) + 7) - 1;
27669 break;
27670
27671 case 'day':
27672 case 'date':
27673 time = startOfDate(this.year(), this.month(), this.date() + 1) - 1;
27674 break;
27675
27676 case 'hour':
27677 time = this._d.valueOf();
27678 time += MS_PER_HOUR - mod$1(time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR) - 1;
27679 break;
27680
27681 case 'minute':
27682 time = this._d.valueOf();
27683 time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1;
27684 break;
27685
27686 case 'second':
27687 time = this._d.valueOf();
27688 time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1;
27689 break;
27690 }
27691
27692 this._d.setTime(time);
27693
27694 hooks.updateOffset(this, true);
27695 return this;
27696 }
27697
27698 function valueOf() {
27699 return this._d.valueOf() - (this._offset || 0) * 60000;
27700 }
27701
27702 function unix() {
27703 return Math.floor(this.valueOf() / 1000);
27704 }
27705
27706 function toDate() {
27707 return new Date(this.valueOf());
27708 }
27709
27710 function toArray() {
27711 var m = this;
27712 return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()];
27713 }
27714
27715 function toObject() {
27716 var m = this;
27717 return {
27718 years: m.year(),
27719 months: m.month(),
27720 date: m.date(),
27721 hours: m.hours(),
27722 minutes: m.minutes(),
27723 seconds: m.seconds(),
27724 milliseconds: m.milliseconds()
27725 };
27726 }
27727
27728 function toJSON() {
27729 // new Date(NaN).toJSON() === null
27730 return this.isValid() ? this.toISOString() : null;
27731 }
27732
27733 function isValid$2() {
27734 return isValid(this);
27735 }
27736
27737 function parsingFlags() {
27738 return extend({}, getParsingFlags(this));
27739 }
27740
27741 function invalidAt() {
27742 return getParsingFlags(this).overflow;
27743 }
27744
27745 function creationData() {
27746 return {
27747 input: this._i,
27748 format: this._f,
27749 locale: this._locale,
27750 isUTC: this._isUTC,
27751 strict: this._strict
27752 };
27753 } // FORMATTING
27754
27755
27756 addFormatToken(0, ['gg', 2], 0, function () {
27757 return this.weekYear() % 100;
27758 });
27759 addFormatToken(0, ['GG', 2], 0, function () {
27760 return this.isoWeekYear() % 100;
27761 });
27762
27763 function addWeekYearFormatToken(token, getter) {
27764 addFormatToken(0, [token, token.length], 0, getter);
27765 }
27766
27767 addWeekYearFormatToken('gggg', 'weekYear');
27768 addWeekYearFormatToken('ggggg', 'weekYear');
27769 addWeekYearFormatToken('GGGG', 'isoWeekYear');
27770 addWeekYearFormatToken('GGGGG', 'isoWeekYear'); // ALIASES
27771
27772 addUnitAlias('weekYear', 'gg');
27773 addUnitAlias('isoWeekYear', 'GG'); // PRIORITY
27774
27775 addUnitPriority('weekYear', 1);
27776 addUnitPriority('isoWeekYear', 1); // PARSING
27777
27778 addRegexToken('G', matchSigned);
27779 addRegexToken('g', matchSigned);
27780 addRegexToken('GG', match1to2, match2);
27781 addRegexToken('gg', match1to2, match2);
27782 addRegexToken('GGGG', match1to4, match4);
27783 addRegexToken('gggg', match1to4, match4);
27784 addRegexToken('GGGGG', match1to6, match6);
27785 addRegexToken('ggggg', match1to6, match6);
27786 addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) {
27787 week[token.substr(0, 2)] = toInt(input);
27788 });
27789 addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
27790 week[token] = hooks.parseTwoDigitYear(input);
27791 }); // MOMENTS
27792
27793 function getSetWeekYear(input) {
27794 return getSetWeekYearHelper.call(this, input, this.week(), this.weekday(), this.localeData()._week.dow, this.localeData()._week.doy);
27795 }
27796
27797 function getSetISOWeekYear(input) {
27798 return getSetWeekYearHelper.call(this, input, this.isoWeek(), this.isoWeekday(), 1, 4);
27799 }
27800
27801 function getISOWeeksInYear() {
27802 return weeksInYear(this.year(), 1, 4);
27803 }
27804
27805 function getWeeksInYear() {
27806 var weekInfo = this.localeData()._week;
27807
27808 return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
27809 }
27810
27811 function getSetWeekYearHelper(input, week, weekday, dow, doy) {
27812 var weeksTarget;
27813
27814 if (input == null) {
27815 return weekOfYear(this, dow, doy).year;
27816 } else {
27817 weeksTarget = weeksInYear(input, dow, doy);
27818
27819 if (week > weeksTarget) {
27820 week = weeksTarget;
27821 }
27822
27823 return setWeekAll.call(this, input, week, weekday, dow, doy);
27824 }
27825 }
27826
27827 function setWeekAll(weekYear, week, weekday, dow, doy) {
27828 var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
27829 date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
27830 this.year(date.getUTCFullYear());
27831 this.month(date.getUTCMonth());
27832 this.date(date.getUTCDate());
27833 return this;
27834 } // FORMATTING
27835
27836
27837 addFormatToken('Q', 0, 'Qo', 'quarter'); // ALIASES
27838
27839 addUnitAlias('quarter', 'Q'); // PRIORITY
27840
27841 addUnitPriority('quarter', 7); // PARSING
27842
27843 addRegexToken('Q', match1);
27844 addParseToken('Q', function (input, array) {
27845 array[MONTH] = (toInt(input) - 1) * 3;
27846 }); // MOMENTS
27847
27848 function getSetQuarter(input) {
27849 return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
27850 } // FORMATTING
27851
27852
27853 addFormatToken('D', ['DD', 2], 'Do', 'date'); // ALIASES
27854
27855 addUnitAlias('date', 'D'); // PRIORITY
27856
27857 addUnitPriority('date', 9); // PARSING
27858
27859 addRegexToken('D', match1to2);
27860 addRegexToken('DD', match1to2, match2);
27861 addRegexToken('Do', function (isStrict, locale) {
27862 // TODO: Remove "ordinalParse" fallback in next major release.
27863 return isStrict ? locale._dayOfMonthOrdinalParse || locale._ordinalParse : locale._dayOfMonthOrdinalParseLenient;
27864 });
27865 addParseToken(['D', 'DD'], DATE);
27866 addParseToken('Do', function (input, array) {
27867 array[DATE] = toInt(input.match(match1to2)[0]);
27868 }); // MOMENTS
27869
27870 var getSetDayOfMonth = makeGetSet('Date', true); // FORMATTING
27871
27872 addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear'); // ALIASES
27873
27874 addUnitAlias('dayOfYear', 'DDD'); // PRIORITY
27875
27876 addUnitPriority('dayOfYear', 4); // PARSING
27877
27878 addRegexToken('DDD', match1to3);
27879 addRegexToken('DDDD', match3);
27880 addParseToken(['DDD', 'DDDD'], function (input, array, config) {
27881 config._dayOfYear = toInt(input);
27882 }); // HELPERS
27883 // MOMENTS
27884
27885 function getSetDayOfYear(input) {
27886 var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1;
27887 return input == null ? dayOfYear : this.add(input - dayOfYear, 'd');
27888 } // FORMATTING
27889
27890
27891 addFormatToken('m', ['mm', 2], 0, 'minute'); // ALIASES
27892
27893 addUnitAlias('minute', 'm'); // PRIORITY
27894
27895 addUnitPriority('minute', 14); // PARSING
27896
27897 addRegexToken('m', match1to2);
27898 addRegexToken('mm', match1to2, match2);
27899 addParseToken(['m', 'mm'], MINUTE); // MOMENTS
27900
27901 var getSetMinute = makeGetSet('Minutes', false); // FORMATTING
27902
27903 addFormatToken('s', ['ss', 2], 0, 'second'); // ALIASES
27904
27905 addUnitAlias('second', 's'); // PRIORITY
27906
27907 addUnitPriority('second', 15); // PARSING
27908
27909 addRegexToken('s', match1to2);
27910 addRegexToken('ss', match1to2, match2);
27911 addParseToken(['s', 'ss'], SECOND); // MOMENTS
27912
27913 var getSetSecond = makeGetSet('Seconds', false); // FORMATTING
27914
27915 addFormatToken('S', 0, 0, function () {
27916 return ~~(this.millisecond() / 100);
27917 });
27918 addFormatToken(0, ['SS', 2], 0, function () {
27919 return ~~(this.millisecond() / 10);
27920 });
27921 addFormatToken(0, ['SSS', 3], 0, 'millisecond');
27922 addFormatToken(0, ['SSSS', 4], 0, function () {
27923 return this.millisecond() * 10;
27924 });
27925 addFormatToken(0, ['SSSSS', 5], 0, function () {
27926 return this.millisecond() * 100;
27927 });
27928 addFormatToken(0, ['SSSSSS', 6], 0, function () {
27929 return this.millisecond() * 1000;
27930 });
27931 addFormatToken(0, ['SSSSSSS', 7], 0, function () {
27932 return this.millisecond() * 10000;
27933 });
27934 addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
27935 return this.millisecond() * 100000;
27936 });
27937 addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
27938 return this.millisecond() * 1000000;
27939 }); // ALIASES
27940
27941 addUnitAlias('millisecond', 'ms'); // PRIORITY
27942
27943 addUnitPriority('millisecond', 16); // PARSING
27944
27945 addRegexToken('S', match1to3, match1);
27946 addRegexToken('SS', match1to3, match2);
27947 addRegexToken('SSS', match1to3, match3);
27948 var token;
27949
27950 for (token = 'SSSS'; token.length <= 9; token += 'S') {
27951 addRegexToken(token, matchUnsigned);
27952 }
27953
27954 function parseMs(input, array) {
27955 array[MILLISECOND] = toInt(('0.' + input) * 1000);
27956 }
27957
27958 for (token = 'S'; token.length <= 9; token += 'S') {
27959 addParseToken(token, parseMs);
27960 } // MOMENTS
27961
27962
27963 var getSetMillisecond = makeGetSet('Milliseconds', false); // FORMATTING
27964
27965 addFormatToken('z', 0, 0, 'zoneAbbr');
27966 addFormatToken('zz', 0, 0, 'zoneName'); // MOMENTS
27967
27968 function getZoneAbbr() {
27969 return this._isUTC ? 'UTC' : '';
27970 }
27971
27972 function getZoneName() {
27973 return this._isUTC ? 'Coordinated Universal Time' : '';
27974 }
27975
27976 var proto = Moment.prototype;
27977 proto.add = add;
27978 proto.calendar = calendar$1;
27979 proto.clone = clone;
27980 proto.diff = diff;
27981 proto.endOf = endOf;
27982 proto.format = format;
27983 proto.from = from;
27984 proto.fromNow = fromNow;
27985 proto.to = to;
27986 proto.toNow = toNow;
27987 proto.get = stringGet;
27988 proto.invalidAt = invalidAt;
27989 proto.isAfter = isAfter;
27990 proto.isBefore = isBefore;
27991 proto.isBetween = isBetween;
27992 proto.isSame = isSame;
27993 proto.isSameOrAfter = isSameOrAfter;
27994 proto.isSameOrBefore = isSameOrBefore;
27995 proto.isValid = isValid$2;
27996 proto.lang = lang;
27997 proto.locale = locale;
27998 proto.localeData = localeData;
27999 proto.max = prototypeMax;
28000 proto.min = prototypeMin;
28001 proto.parsingFlags = parsingFlags;
28002 proto.set = stringSet;
28003 proto.startOf = startOf;
28004 proto.subtract = subtract;
28005 proto.toArray = toArray;
28006 proto.toObject = toObject;
28007 proto.toDate = toDate;
28008 proto.toISOString = toISOString;
28009 proto.inspect = inspect;
28010 proto.toJSON = toJSON;
28011 proto.toString = toString;
28012 proto.unix = unix;
28013 proto.valueOf = valueOf;
28014 proto.creationData = creationData;
28015 proto.year = getSetYear;
28016 proto.isLeapYear = getIsLeapYear;
28017 proto.weekYear = getSetWeekYear;
28018 proto.isoWeekYear = getSetISOWeekYear;
28019 proto.quarter = proto.quarters = getSetQuarter;
28020 proto.month = getSetMonth;
28021 proto.daysInMonth = getDaysInMonth;
28022 proto.week = proto.weeks = getSetWeek;
28023 proto.isoWeek = proto.isoWeeks = getSetISOWeek;
28024 proto.weeksInYear = getWeeksInYear;
28025 proto.isoWeeksInYear = getISOWeeksInYear;
28026 proto.date = getSetDayOfMonth;
28027 proto.day = proto.days = getSetDayOfWeek;
28028 proto.weekday = getSetLocaleDayOfWeek;
28029 proto.isoWeekday = getSetISODayOfWeek;
28030 proto.dayOfYear = getSetDayOfYear;
28031 proto.hour = proto.hours = getSetHour;
28032 proto.minute = proto.minutes = getSetMinute;
28033 proto.second = proto.seconds = getSetSecond;
28034 proto.millisecond = proto.milliseconds = getSetMillisecond;
28035 proto.utcOffset = getSetOffset;
28036 proto.utc = setOffsetToUTC;
28037 proto.local = setOffsetToLocal;
28038 proto.parseZone = setOffsetToParsedOffset;
28039 proto.hasAlignedHourOffset = hasAlignedHourOffset;
28040 proto.isDST = isDaylightSavingTime;
28041 proto.isLocal = isLocal;
28042 proto.isUtcOffset = isUtcOffset;
28043 proto.isUtc = isUtc;
28044 proto.isUTC = isUtc;
28045 proto.zoneAbbr = getZoneAbbr;
28046 proto.zoneName = getZoneName;
28047 proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth);
28048 proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth);
28049 proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear);
28050 proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone);
28051 proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted);
28052
28053 function createUnix(input) {
28054 return createLocal(input * 1000);
28055 }
28056
28057 function createInZone() {
28058 return createLocal.apply(null, arguments).parseZone();
28059 }
28060
28061 function preParsePostFormat(string) {
28062 return string;
28063 }
28064
28065 var proto$1 = Locale.prototype;
28066 proto$1.calendar = calendar;
28067 proto$1.longDateFormat = longDateFormat;
28068 proto$1.invalidDate = invalidDate;
28069 proto$1.ordinal = ordinal;
28070 proto$1.preparse = preParsePostFormat;
28071 proto$1.postformat = preParsePostFormat;
28072 proto$1.relativeTime = relativeTime;
28073 proto$1.pastFuture = pastFuture;
28074 proto$1.set = set;
28075 proto$1.months = localeMonths;
28076 proto$1.monthsShort = localeMonthsShort;
28077 proto$1.monthsParse = localeMonthsParse;
28078 proto$1.monthsRegex = monthsRegex;
28079 proto$1.monthsShortRegex = monthsShortRegex;
28080 proto$1.week = localeWeek;
28081 proto$1.firstDayOfYear = localeFirstDayOfYear;
28082 proto$1.firstDayOfWeek = localeFirstDayOfWeek;
28083 proto$1.weekdays = localeWeekdays;
28084 proto$1.weekdaysMin = localeWeekdaysMin;
28085 proto$1.weekdaysShort = localeWeekdaysShort;
28086 proto$1.weekdaysParse = localeWeekdaysParse;
28087 proto$1.weekdaysRegex = weekdaysRegex;
28088 proto$1.weekdaysShortRegex = weekdaysShortRegex;
28089 proto$1.weekdaysMinRegex = weekdaysMinRegex;
28090 proto$1.isPM = localeIsPM;
28091 proto$1.meridiem = localeMeridiem;
28092
28093 function get$1(format, index, field, setter) {
28094 var locale = getLocale();
28095 var utc = createUTC().set(setter, index);
28096 return locale[field](utc, format);
28097 }
28098
28099 function listMonthsImpl(format, index, field) {
28100 if (isNumber(format)) {
28101 index = format;
28102 format = undefined;
28103 }
28104
28105 format = format || '';
28106
28107 if (index != null) {
28108 return get$1(format, index, field, 'month');
28109 }
28110
28111 var i;
28112 var out = [];
28113
28114 for (i = 0; i < 12; i++) {
28115 out[i] = get$1(format, i, field, 'month');
28116 }
28117
28118 return out;
28119 } // ()
28120 // (5)
28121 // (fmt, 5)
28122 // (fmt)
28123 // (true)
28124 // (true, 5)
28125 // (true, fmt, 5)
28126 // (true, fmt)
28127
28128
28129 function listWeekdaysImpl(localeSorted, format, index, field) {
28130 if (typeof localeSorted === 'boolean') {
28131 if (isNumber(format)) {
28132 index = format;
28133 format = undefined;
28134 }
28135
28136 format = format || '';
28137 } else {
28138 format = localeSorted;
28139 index = format;
28140 localeSorted = false;
28141
28142 if (isNumber(format)) {
28143 index = format;
28144 format = undefined;
28145 }
28146
28147 format = format || '';
28148 }
28149
28150 var locale = getLocale(),
28151 shift = localeSorted ? locale._week.dow : 0;
28152
28153 if (index != null) {
28154 return get$1(format, (index + shift) % 7, field, 'day');
28155 }
28156
28157 var i;
28158 var out = [];
28159
28160 for (i = 0; i < 7; i++) {
28161 out[i] = get$1(format, (i + shift) % 7, field, 'day');
28162 }
28163
28164 return out;
28165 }
28166
28167 function listMonths(format, index) {
28168 return listMonthsImpl(format, index, 'months');
28169 }
28170
28171 function listMonthsShort(format, index) {
28172 return listMonthsImpl(format, index, 'monthsShort');
28173 }
28174
28175 function listWeekdays(localeSorted, format, index) {
28176 return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
28177 }
28178
28179 function listWeekdaysShort(localeSorted, format, index) {
28180 return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
28181 }
28182
28183 function listWeekdaysMin(localeSorted, format, index) {
28184 return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
28185 }
28186
28187 getSetGlobalLocale('en', {
28188 dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
28189 ordinal: function (number) {
28190 var b = number % 10,
28191 output = toInt(number % 100 / 10) === 1 ? 'th' : b === 1 ? 'st' : b === 2 ? 'nd' : b === 3 ? 'rd' : 'th';
28192 return number + output;
28193 }
28194 }); // Side effect imports
28195
28196 hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale);
28197 hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', getLocale);
28198 var mathAbs = Math.abs;
28199
28200 function abs() {
28201 var data = this._data;
28202 this._milliseconds = mathAbs(this._milliseconds);
28203 this._days = mathAbs(this._days);
28204 this._months = mathAbs(this._months);
28205 data.milliseconds = mathAbs(data.milliseconds);
28206 data.seconds = mathAbs(data.seconds);
28207 data.minutes = mathAbs(data.minutes);
28208 data.hours = mathAbs(data.hours);
28209 data.months = mathAbs(data.months);
28210 data.years = mathAbs(data.years);
28211 return this;
28212 }
28213
28214 function addSubtract$1(duration, input, value, direction) {
28215 var other = createDuration(input, value);
28216 duration._milliseconds += direction * other._milliseconds;
28217 duration._days += direction * other._days;
28218 duration._months += direction * other._months;
28219 return duration._bubble();
28220 } // supports only 2.0-style add(1, 's') or add(duration)
28221
28222
28223 function add$1(input, value) {
28224 return addSubtract$1(this, input, value, 1);
28225 } // supports only 2.0-style subtract(1, 's') or subtract(duration)
28226
28227
28228 function subtract$1(input, value) {
28229 return addSubtract$1(this, input, value, -1);
28230 }
28231
28232 function absCeil(number) {
28233 if (number < 0) {
28234 return Math.floor(number);
28235 } else {
28236 return Math.ceil(number);
28237 }
28238 }
28239
28240 function bubble() {
28241 var milliseconds = this._milliseconds;
28242 var days = this._days;
28243 var months = this._months;
28244 var data = this._data;
28245 var seconds, minutes, hours, years, monthsFromDays; // if we have a mix of positive and negative values, bubble down first
28246 // check: https://github.com/moment/moment/issues/2166
28247
28248 if (!(milliseconds >= 0 && days >= 0 && months >= 0 || milliseconds <= 0 && days <= 0 && months <= 0)) {
28249 milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
28250 days = 0;
28251 months = 0;
28252 } // The following code bubbles up values, see the tests for
28253 // examples of what that means.
28254
28255
28256 data.milliseconds = milliseconds % 1000;
28257 seconds = absFloor(milliseconds / 1000);
28258 data.seconds = seconds % 60;
28259 minutes = absFloor(seconds / 60);
28260 data.minutes = minutes % 60;
28261 hours = absFloor(minutes / 60);
28262 data.hours = hours % 24;
28263 days += absFloor(hours / 24); // convert days to months
28264
28265 monthsFromDays = absFloor(daysToMonths(days));
28266 months += monthsFromDays;
28267 days -= absCeil(monthsToDays(monthsFromDays)); // 12 months -> 1 year
28268
28269 years = absFloor(months / 12);
28270 months %= 12;
28271 data.days = days;
28272 data.months = months;
28273 data.years = years;
28274 return this;
28275 }
28276
28277 function daysToMonths(days) {
28278 // 400 years have 146097 days (taking into account leap year rules)
28279 // 400 years have 12 months === 4800
28280 return days * 4800 / 146097;
28281 }
28282
28283 function monthsToDays(months) {
28284 // the reverse of daysToMonths
28285 return months * 146097 / 4800;
28286 }
28287
28288 function as(units) {
28289 if (!this.isValid()) {
28290 return NaN;
28291 }
28292
28293 var days;
28294 var months;
28295 var milliseconds = this._milliseconds;
28296 units = normalizeUnits(units);
28297
28298 if (units === 'month' || units === 'quarter' || units === 'year') {
28299 days = this._days + milliseconds / 864e5;
28300 months = this._months + daysToMonths(days);
28301
28302 switch (units) {
28303 case 'month':
28304 return months;
28305
28306 case 'quarter':
28307 return months / 3;
28308
28309 case 'year':
28310 return months / 12;
28311 }
28312 } else {
28313 // handle milliseconds separately because of floating point math errors (issue #1867)
28314 days = this._days + Math.round(monthsToDays(this._months));
28315
28316 switch (units) {
28317 case 'week':
28318 return days / 7 + milliseconds / 6048e5;
28319
28320 case 'day':
28321 return days + milliseconds / 864e5;
28322
28323 case 'hour':
28324 return days * 24 + milliseconds / 36e5;
28325
28326 case 'minute':
28327 return days * 1440 + milliseconds / 6e4;
28328
28329 case 'second':
28330 return days * 86400 + milliseconds / 1000;
28331 // Math.floor prevents floating point math errors here
28332
28333 case 'millisecond':
28334 return Math.floor(days * 864e5) + milliseconds;
28335
28336 default:
28337 throw new Error('Unknown unit ' + units);
28338 }
28339 }
28340 } // TODO: Use this.as('ms')?
28341
28342
28343 function valueOf$1() {
28344 if (!this.isValid()) {
28345 return NaN;
28346 }
28347
28348 return this._milliseconds + this._days * 864e5 + this._months % 12 * 2592e6 + toInt(this._months / 12) * 31536e6;
28349 }
28350
28351 function makeAs(alias) {
28352 return function () {
28353 return this.as(alias);
28354 };
28355 }
28356
28357 var asMilliseconds = makeAs('ms');
28358 var asSeconds = makeAs('s');
28359 var asMinutes = makeAs('m');
28360 var asHours = makeAs('h');
28361 var asDays = makeAs('d');
28362 var asWeeks = makeAs('w');
28363 var asMonths = makeAs('M');
28364 var asQuarters = makeAs('Q');
28365 var asYears = makeAs('y');
28366
28367 function clone$1() {
28368 return createDuration(this);
28369 }
28370
28371 function get$2(units) {
28372 units = normalizeUnits(units);
28373 return this.isValid() ? this[units + 's']() : NaN;
28374 }
28375
28376 function makeGetter(name) {
28377 return function () {
28378 return this.isValid() ? this._data[name] : NaN;
28379 };
28380 }
28381
28382 var milliseconds = makeGetter('milliseconds');
28383 var seconds = makeGetter('seconds');
28384 var minutes = makeGetter('minutes');
28385 var hours = makeGetter('hours');
28386 var days = makeGetter('days');
28387 var months = makeGetter('months');
28388 var years = makeGetter('years');
28389
28390 function weeks() {
28391 return absFloor(this.days() / 7);
28392 }
28393
28394 var round = Math.round;
28395 var thresholds = {
28396 ss: 44,
28397 // a few seconds to seconds
28398 s: 45,
28399 // seconds to minute
28400 m: 45,
28401 // minutes to hour
28402 h: 22,
28403 // hours to day
28404 d: 26,
28405 // days to month
28406 M: 11 // months to year
28407
28408 }; // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
28409
28410 function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
28411 return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
28412 }
28413
28414 function relativeTime$1(posNegDuration, withoutSuffix, locale) {
28415 var duration = createDuration(posNegDuration).abs();
28416 var seconds = round(duration.as('s'));
28417 var minutes = round(duration.as('m'));
28418 var hours = round(duration.as('h'));
28419 var days = round(duration.as('d'));
28420 var months = round(duration.as('M'));
28421 var years = round(duration.as('y'));
28422 var a = seconds <= thresholds.ss && ['s', seconds] || seconds < thresholds.s && ['ss', seconds] || minutes <= 1 && ['m'] || minutes < thresholds.m && ['mm', minutes] || hours <= 1 && ['h'] || hours < thresholds.h && ['hh', hours] || days <= 1 && ['d'] || days < thresholds.d && ['dd', days] || months <= 1 && ['M'] || months < thresholds.M && ['MM', months] || years <= 1 && ['y'] || ['yy', years];
28423 a[2] = withoutSuffix;
28424 a[3] = +posNegDuration > 0;
28425 a[4] = locale;
28426 return substituteTimeAgo.apply(null, a);
28427 } // This function allows you to set the rounding function for relative time strings
28428
28429
28430 function getSetRelativeTimeRounding(roundingFunction) {
28431 if (roundingFunction === undefined) {
28432 return round;
28433 }
28434
28435 if (typeof roundingFunction === 'function') {
28436 round = roundingFunction;
28437 return true;
28438 }
28439
28440 return false;
28441 } // This function allows you to set a threshold for relative time strings
28442
28443
28444 function getSetRelativeTimeThreshold(threshold, limit) {
28445 if (thresholds[threshold] === undefined) {
28446 return false;
28447 }
28448
28449 if (limit === undefined) {
28450 return thresholds[threshold];
28451 }
28452
28453 thresholds[threshold] = limit;
28454
28455 if (threshold === 's') {
28456 thresholds.ss = limit - 1;
28457 }
28458
28459 return true;
28460 }
28461
28462 function humanize(withSuffix) {
28463 if (!this.isValid()) {
28464 return this.localeData().invalidDate();
28465 }
28466
28467 var locale = this.localeData();
28468 var output = relativeTime$1(this, !withSuffix, locale);
28469
28470 if (withSuffix) {
28471 output = locale.pastFuture(+this, output);
28472 }
28473
28474 return locale.postformat(output);
28475 }
28476
28477 var abs$1 = Math.abs;
28478
28479 function sign(x) {
28480 return (x > 0) - (x < 0) || +x;
28481 }
28482
28483 function toISOString$1() {
28484 // for ISO strings we do not use the normal bubbling rules:
28485 // * milliseconds bubble up until they become hours
28486 // * days do not bubble at all
28487 // * months bubble up until they become years
28488 // This is because there is no context-free conversion between hours and days
28489 // (think of clock changes)
28490 // and also not between days and months (28-31 days per month)
28491 if (!this.isValid()) {
28492 return this.localeData().invalidDate();
28493 }
28494
28495 var seconds = abs$1(this._milliseconds) / 1000;
28496 var days = abs$1(this._days);
28497 var months = abs$1(this._months);
28498 var minutes, hours, years; // 3600 seconds -> 60 minutes -> 1 hour
28499
28500 minutes = absFloor(seconds / 60);
28501 hours = absFloor(minutes / 60);
28502 seconds %= 60;
28503 minutes %= 60; // 12 months -> 1 year
28504
28505 years = absFloor(months / 12);
28506 months %= 12; // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
28507
28508 var Y = years;
28509 var M = months;
28510 var D = days;
28511 var h = hours;
28512 var m = minutes;
28513 var s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : '';
28514 var total = this.asSeconds();
28515
28516 if (!total) {
28517 // this is the same as C#'s (Noda) and python (isodate)...
28518 // but not other JS (goog.date)
28519 return 'P0D';
28520 }
28521
28522 var totalSign = total < 0 ? '-' : '';
28523 var ymSign = sign(this._months) !== sign(total) ? '-' : '';
28524 var daysSign = sign(this._days) !== sign(total) ? '-' : '';
28525 var hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '';
28526 return totalSign + 'P' + (Y ? ymSign + Y + 'Y' : '') + (M ? ymSign + M + 'M' : '') + (D ? daysSign + D + 'D' : '') + (h || m || s ? 'T' : '') + (h ? hmsSign + h + 'H' : '') + (m ? hmsSign + m + 'M' : '') + (s ? hmsSign + s + 'S' : '');
28527 }
28528
28529 var proto$2 = Duration.prototype;
28530 proto$2.isValid = isValid$1;
28531 proto$2.abs = abs;
28532 proto$2.add = add$1;
28533 proto$2.subtract = subtract$1;
28534 proto$2.as = as;
28535 proto$2.asMilliseconds = asMilliseconds;
28536 proto$2.asSeconds = asSeconds;
28537 proto$2.asMinutes = asMinutes;
28538 proto$2.asHours = asHours;
28539 proto$2.asDays = asDays;
28540 proto$2.asWeeks = asWeeks;
28541 proto$2.asMonths = asMonths;
28542 proto$2.asQuarters = asQuarters;
28543 proto$2.asYears = asYears;
28544 proto$2.valueOf = valueOf$1;
28545 proto$2._bubble = bubble;
28546 proto$2.clone = clone$1;
28547 proto$2.get = get$2;
28548 proto$2.milliseconds = milliseconds;
28549 proto$2.seconds = seconds;
28550 proto$2.minutes = minutes;
28551 proto$2.hours = hours;
28552 proto$2.days = days;
28553 proto$2.weeks = weeks;
28554 proto$2.months = months;
28555 proto$2.years = years;
28556 proto$2.humanize = humanize;
28557 proto$2.toISOString = toISOString$1;
28558 proto$2.toString = toISOString$1;
28559 proto$2.toJSON = toISOString$1;
28560 proto$2.locale = locale;
28561 proto$2.localeData = localeData;
28562 proto$2.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1);
28563 proto$2.lang = lang; // Side effect imports
28564 // FORMATTING
28565
28566 addFormatToken('X', 0, 0, 'unix');
28567 addFormatToken('x', 0, 0, 'valueOf'); // PARSING
28568
28569 addRegexToken('x', matchSigned);
28570 addRegexToken('X', matchTimestamp);
28571 addParseToken('X', function (input, array, config) {
28572 config._d = new Date(parseFloat(input, 10) * 1000);
28573 });
28574 addParseToken('x', function (input, array, config) {
28575 config._d = new Date(toInt(input));
28576 }); // Side effect imports
28577
28578 hooks.version = '2.24.0';
28579 setHookCallback(createLocal);
28580 hooks.fn = proto;
28581 hooks.min = min;
28582 hooks.max = max;
28583 hooks.now = now;
28584 hooks.utc = createUTC;
28585 hooks.unix = createUnix;
28586 hooks.months = listMonths;
28587 hooks.isDate = isDate;
28588 hooks.locale = getSetGlobalLocale;
28589 hooks.invalid = createInvalid;
28590 hooks.duration = createDuration;
28591 hooks.isMoment = isMoment;
28592 hooks.weekdays = listWeekdays;
28593 hooks.parseZone = createInZone;
28594 hooks.localeData = getLocale;
28595 hooks.isDuration = isDuration;
28596 hooks.monthsShort = listMonthsShort;
28597 hooks.weekdaysMin = listWeekdaysMin;
28598 hooks.defineLocale = defineLocale;
28599 hooks.updateLocale = updateLocale;
28600 hooks.locales = listLocales;
28601 hooks.weekdaysShort = listWeekdaysShort;
28602 hooks.normalizeUnits = normalizeUnits;
28603 hooks.relativeTimeRounding = getSetRelativeTimeRounding;
28604 hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
28605 hooks.calendarFormat = getCalendarFormat;
28606 hooks.prototype = proto; // currently HTML5 input type only supports 24-hour formats
28607
28608 hooks.HTML5_FMT = {
28609 DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm',
28610 // <input type="datetime-local" />
28611 DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss',
28612 // <input type="datetime-local" step="1" />
28613 DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS',
28614 // <input type="datetime-local" step="0.001" />
28615 DATE: 'YYYY-MM-DD',
28616 // <input type="date" />
28617 TIME: 'HH:mm',
28618 // <input type="time" />
28619 TIME_SECONDS: 'HH:mm:ss',
28620 // <input type="time" step="1" />
28621 TIME_MS: 'HH:mm:ss.SSS',
28622 // <input type="time" step="0.001" />
28623 WEEK: 'GGGG-[W]WW',
28624 // <input type="week" />
28625 MONTH: 'YYYY-MM' // <input type="month" />
28626
28627 };
28628 return hooks;
28629 });
28630});
28631
28632// use this instance. Else, load via commonjs.
28633
28634var moment$3 = typeof window !== 'undefined' && window['moment'] || moment$2;
28635
28636var propagating = createCommonjsModule$1(function (module, exports) {
28637
28638 (function (factory) {
28639 {
28640 // Node. Does not work with strict CommonJS, but
28641 // only CommonJS-like environments that support module.exports,
28642 // like Node.
28643 module.exports = factory();
28644 }
28645 })(function () {
28646 var _firstTarget = null; // singleton, will contain the target element where the touch event started
28647
28648 /**
28649 * Extend an Hammer.js instance with event propagation.
28650 *
28651 * Features:
28652 * - Events emitted by hammer will propagate in order from child to parent
28653 * elements.
28654 * - Events are extended with a function `event.stopPropagation()` to stop
28655 * propagation to parent elements.
28656 * - An option `preventDefault` to stop all default browser behavior.
28657 *
28658 * Usage:
28659 * var hammer = propagatingHammer(new Hammer(element));
28660 * var hammer = propagatingHammer(new Hammer(element), {preventDefault: true});
28661 *
28662 * @param {Hammer.Manager} hammer An hammer instance.
28663 * @param {Object} [options] Available options:
28664 * - `preventDefault: true | false | 'mouse' | 'touch' | 'pen'`.
28665 * Enforce preventing the default browser behavior.
28666 * Cannot be set to `false`.
28667 * @return {Hammer.Manager} Returns the same hammer instance with extended
28668 * functionality
28669 */
28670
28671 return function propagating(hammer, options) {
28672 var _options = options || {
28673 preventDefault: false
28674 };
28675
28676 if (hammer.Manager) {
28677 // This looks like the Hammer constructor.
28678 // Overload the constructors with our own.
28679 var Hammer = hammer;
28680
28681 var PropagatingHammer = function (element, options) {
28682 var o = Object.create(_options);
28683 if (options) Hammer.assign(o, options);
28684 return propagating(new Hammer(element, o), o);
28685 };
28686
28687 Hammer.assign(PropagatingHammer, Hammer);
28688
28689 PropagatingHammer.Manager = function (element, options) {
28690 var o = Object.create(_options);
28691 if (options) Hammer.assign(o, options);
28692 return propagating(new Hammer.Manager(element, o), o);
28693 };
28694
28695 return PropagatingHammer;
28696 } // create a wrapper object which will override the functions
28697 // `on`, `off`, `destroy`, and `emit` of the hammer instance
28698
28699
28700 var wrapper = Object.create(hammer); // attach to DOM element
28701
28702 var element = hammer.element;
28703 if (!element.hammer) element.hammer = [];
28704 element.hammer.push(wrapper); // register an event to catch the start of a gesture and store the
28705 // target in a singleton
28706
28707 hammer.on('hammer.input', function (event) {
28708 if (_options.preventDefault === true || _options.preventDefault === event.pointerType) {
28709 event.preventDefault();
28710 }
28711
28712 if (event.isFirst) {
28713 _firstTarget = event.target;
28714 }
28715 });
28716 /** @type {Object.<String, Array.<function>>} */
28717
28718 wrapper._handlers = {};
28719 /**
28720 * Register a handler for one or multiple events
28721 * @param {String} events A space separated string with events
28722 * @param {function} handler A callback function, called as handler(event)
28723 * @returns {Hammer.Manager} Returns the hammer instance
28724 */
28725
28726 wrapper.on = function (events, handler) {
28727 // register the handler
28728 split(events).forEach(function (event) {
28729 var _handlers = wrapper._handlers[event];
28730
28731 if (!_handlers) {
28732 wrapper._handlers[event] = _handlers = []; // register the static, propagated handler
28733
28734 hammer.on(event, propagatedHandler);
28735 }
28736
28737 _handlers.push(handler);
28738 });
28739 return wrapper;
28740 };
28741 /**
28742 * Unregister a handler for one or multiple events
28743 * @param {String} events A space separated string with events
28744 * @param {function} [handler] Optional. The registered handler. If not
28745 * provided, all handlers for given events
28746 * are removed.
28747 * @returns {Hammer.Manager} Returns the hammer instance
28748 */
28749
28750
28751 wrapper.off = function (events, handler) {
28752 // unregister the handler
28753 split(events).forEach(function (event) {
28754 var _handlers = wrapper._handlers[event];
28755
28756 if (_handlers) {
28757 _handlers = handler ? _handlers.filter(function (h) {
28758 return h !== handler;
28759 }) : [];
28760
28761 if (_handlers.length > 0) {
28762 wrapper._handlers[event] = _handlers;
28763 } else {
28764 // remove static, propagated handler
28765 hammer.off(event, propagatedHandler);
28766 delete wrapper._handlers[event];
28767 }
28768 }
28769 });
28770 return wrapper;
28771 };
28772 /**
28773 * Emit to the event listeners
28774 * @param {string} eventType
28775 * @param {Event} event
28776 */
28777
28778
28779 wrapper.emit = function (eventType, event) {
28780 _firstTarget = event.target;
28781 hammer.emit(eventType, event);
28782 };
28783
28784 wrapper.destroy = function () {
28785 // Detach from DOM element
28786 var hammers = hammer.element.hammer;
28787 var idx = hammers.indexOf(wrapper);
28788 if (idx !== -1) hammers.splice(idx, 1);
28789 if (!hammers.length) delete hammer.element.hammer; // clear all handlers
28790
28791 wrapper._handlers = {}; // call original hammer destroy
28792
28793 hammer.destroy();
28794 }; // split a string with space separated words
28795
28796
28797 function split(events) {
28798 return events.match(/[^ ]+/g);
28799 }
28800 /**
28801 * A static event handler, applying event propagation.
28802 * @param {Object} event
28803 */
28804
28805
28806 function propagatedHandler(event) {
28807 // let only a single hammer instance handle this event
28808 if (event.type !== 'hammer.input') {
28809 // it is possible that the same srcEvent is used with multiple hammer events,
28810 // we keep track on which events are handled in an object _handled
28811 if (!event.srcEvent._handled) {
28812 event.srcEvent._handled = {};
28813 }
28814
28815 if (event.srcEvent._handled[event.type]) {
28816 return;
28817 } else {
28818 event.srcEvent._handled[event.type] = true;
28819 }
28820 } // attach a stopPropagation function to the event
28821
28822
28823 var stopped = false;
28824
28825 event.stopPropagation = function () {
28826 stopped = true;
28827 }; //wrap the srcEvent's stopPropagation to also stop hammer propagation:
28828
28829
28830 var srcStop = event.srcEvent.stopPropagation.bind(event.srcEvent);
28831
28832 if (typeof srcStop == "function") {
28833 event.srcEvent.stopPropagation = function () {
28834 srcStop();
28835 event.stopPropagation();
28836 };
28837 } // attach firstTarget property to the event
28838
28839
28840 event.firstTarget = _firstTarget; // propagate over all elements (until stopped)
28841
28842 var elem = _firstTarget;
28843
28844 while (elem && !stopped) {
28845 var elemHammer = elem.hammer;
28846
28847 if (elemHammer) {
28848 var _handlers;
28849
28850 for (var k = 0; k < elemHammer.length; k++) {
28851 _handlers = elemHammer[k]._handlers[event.type];
28852 if (_handlers) for (var i = 0; i < _handlers.length && !stopped; i++) {
28853 _handlers[i](event);
28854 }
28855 }
28856 }
28857
28858 elem = elem.parentNode;
28859 }
28860 }
28861
28862 return wrapper;
28863 };
28864 });
28865});
28866
28867var hammer = createCommonjsModule$1(function (module) {
28868 /*! Hammer.JS - v2.0.7 - 2016-04-22
28869 * http://hammerjs.github.io/
28870 *
28871 * Copyright (c) 2016 Jorik Tangelder;
28872 * Licensed under the MIT license */
28873 (function (window, document, exportName, undefined$1) {
28874
28875 var VENDOR_PREFIXES = ['', 'webkit', 'Moz', 'MS', 'ms', 'o'];
28876 var TEST_ELEMENT = document.createElement('div');
28877 var TYPE_FUNCTION = 'function';
28878 var round = Math.round;
28879 var abs = Math.abs;
28880 var now = Date.now;
28881 /**
28882 * set a timeout with a given scope
28883 * @param {Function} fn
28884 * @param {Number} timeout
28885 * @param {Object} context
28886 * @returns {number}
28887 */
28888
28889 function setTimeoutContext(fn, timeout, context) {
28890 return setTimeout(bindFn(fn, context), timeout);
28891 }
28892 /**
28893 * if the argument is an array, we want to execute the fn on each entry
28894 * if it aint an array we don't want to do a thing.
28895 * this is used by all the methods that accept a single and array argument.
28896 * @param {*|Array} arg
28897 * @param {String} fn
28898 * @param {Object} [context]
28899 * @returns {Boolean}
28900 */
28901
28902
28903 function invokeArrayArg(arg, fn, context) {
28904 if (Array.isArray(arg)) {
28905 each(arg, context[fn], context);
28906 return true;
28907 }
28908
28909 return false;
28910 }
28911 /**
28912 * walk objects and arrays
28913 * @param {Object} obj
28914 * @param {Function} iterator
28915 * @param {Object} context
28916 */
28917
28918
28919 function each(obj, iterator, context) {
28920 var i;
28921
28922 if (!obj) {
28923 return;
28924 }
28925
28926 if (obj.forEach) {
28927 obj.forEach(iterator, context);
28928 } else if (obj.length !== undefined$1) {
28929 i = 0;
28930
28931 while (i < obj.length) {
28932 iterator.call(context, obj[i], i, obj);
28933 i++;
28934 }
28935 } else {
28936 for (i in obj) {
28937 obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj);
28938 }
28939 }
28940 }
28941 /**
28942 * wrap a method with a deprecation warning and stack trace
28943 * @param {Function} method
28944 * @param {String} name
28945 * @param {String} message
28946 * @returns {Function} A new function wrapping the supplied method.
28947 */
28948
28949
28950 function deprecate(method, name, message) {
28951 var deprecationMessage = 'DEPRECATED METHOD: ' + name + '\n' + message + ' AT \n';
28952 return function () {
28953 var e = new Error('get-stack-trace');
28954 var stack = e && e.stack ? e.stack.replace(/^[^\(]+?[\n$]/gm, '').replace(/^\s+at\s+/gm, '').replace(/^Object.<anonymous>\s*\(/gm, '{anonymous}()@') : 'Unknown Stack Trace';
28955 var log = window.console && (window.console.warn || window.console.log);
28956
28957 if (log) {
28958 log.call(window.console, deprecationMessage, stack);
28959 }
28960
28961 return method.apply(this, arguments);
28962 };
28963 }
28964 /**
28965 * extend object.
28966 * means that properties in dest will be overwritten by the ones in src.
28967 * @param {Object} target
28968 * @param {...Object} objects_to_assign
28969 * @returns {Object} target
28970 */
28971
28972
28973 var assign;
28974
28975 if (typeof Object.assign !== 'function') {
28976 assign = function assign(target) {
28977 if (target === undefined$1 || target === null) {
28978 throw new TypeError('Cannot convert undefined or null to object');
28979 }
28980
28981 var output = Object(target);
28982
28983 for (var index = 1; index < arguments.length; index++) {
28984 var source = arguments[index];
28985
28986 if (source !== undefined$1 && source !== null) {
28987 for (var nextKey in source) {
28988 if (source.hasOwnProperty(nextKey)) {
28989 output[nextKey] = source[nextKey];
28990 }
28991 }
28992 }
28993 }
28994
28995 return output;
28996 };
28997 } else {
28998 assign = Object.assign;
28999 }
29000 /**
29001 * extend object.
29002 * means that properties in dest will be overwritten by the ones in src.
29003 * @param {Object} dest
29004 * @param {Object} src
29005 * @param {Boolean} [merge=false]
29006 * @returns {Object} dest
29007 */
29008
29009
29010 var extend = deprecate(function extend(dest, src, merge) {
29011 var keys = Object.keys(src);
29012 var i = 0;
29013
29014 while (i < keys.length) {
29015 if (!merge || merge && dest[keys[i]] === undefined$1) {
29016 dest[keys[i]] = src[keys[i]];
29017 }
29018
29019 i++;
29020 }
29021
29022 return dest;
29023 }, 'extend', 'Use `assign`.');
29024 /**
29025 * merge the values from src in the dest.
29026 * means that properties that exist in dest will not be overwritten by src
29027 * @param {Object} dest
29028 * @param {Object} src
29029 * @returns {Object} dest
29030 */
29031
29032 var merge = deprecate(function merge(dest, src) {
29033 return extend(dest, src, true);
29034 }, 'merge', 'Use `assign`.');
29035 /**
29036 * simple class inheritance
29037 * @param {Function} child
29038 * @param {Function} base
29039 * @param {Object} [properties]
29040 */
29041
29042 function inherit(child, base, properties) {
29043 var baseP = base.prototype,
29044 childP;
29045 childP = child.prototype = Object.create(baseP);
29046 childP.constructor = child;
29047 childP._super = baseP;
29048
29049 if (properties) {
29050 assign(childP, properties);
29051 }
29052 }
29053 /**
29054 * simple function bind
29055 * @param {Function} fn
29056 * @param {Object} context
29057 * @returns {Function}
29058 */
29059
29060
29061 function bindFn(fn, context) {
29062 return function boundFn() {
29063 return fn.apply(context, arguments);
29064 };
29065 }
29066 /**
29067 * let a boolean value also be a function that must return a boolean
29068 * this first item in args will be used as the context
29069 * @param {Boolean|Function} val
29070 * @param {Array} [args]
29071 * @returns {Boolean}
29072 */
29073
29074
29075 function boolOrFn(val, args) {
29076 if (typeof val == TYPE_FUNCTION) {
29077 return val.apply(args ? args[0] || undefined$1 : undefined$1, args);
29078 }
29079
29080 return val;
29081 }
29082 /**
29083 * use the val2 when val1 is undefined
29084 * @param {*} val1
29085 * @param {*} val2
29086 * @returns {*}
29087 */
29088
29089
29090 function ifUndefined(val1, val2) {
29091 return val1 === undefined$1 ? val2 : val1;
29092 }
29093 /**
29094 * addEventListener with multiple events at once
29095 * @param {EventTarget} target
29096 * @param {String} types
29097 * @param {Function} handler
29098 */
29099
29100
29101 function addEventListeners(target, types, handler) {
29102 each(splitStr(types), function (type) {
29103 target.addEventListener(type, handler, false);
29104 });
29105 }
29106 /**
29107 * removeEventListener with multiple events at once
29108 * @param {EventTarget} target
29109 * @param {String} types
29110 * @param {Function} handler
29111 */
29112
29113
29114 function removeEventListeners(target, types, handler) {
29115 each(splitStr(types), function (type) {
29116 target.removeEventListener(type, handler, false);
29117 });
29118 }
29119 /**
29120 * find if a node is in the given parent
29121 * @method hasParent
29122 * @param {HTMLElement} node
29123 * @param {HTMLElement} parent
29124 * @return {Boolean} found
29125 */
29126
29127
29128 function hasParent(node, parent) {
29129 while (node) {
29130 if (node == parent) {
29131 return true;
29132 }
29133
29134 node = node.parentNode;
29135 }
29136
29137 return false;
29138 }
29139 /**
29140 * small indexOf wrapper
29141 * @param {String} str
29142 * @param {String} find
29143 * @returns {Boolean} found
29144 */
29145
29146
29147 function inStr(str, find) {
29148 return str.indexOf(find) > -1;
29149 }
29150 /**
29151 * split string on whitespace
29152 * @param {String} str
29153 * @returns {Array} words
29154 */
29155
29156
29157 function splitStr(str) {
29158 return str.trim().split(/\s+/g);
29159 }
29160 /**
29161 * find if a array contains the object using indexOf or a simple polyFill
29162 * @param {Array} src
29163 * @param {String} find
29164 * @param {String} [findByKey]
29165 * @return {Boolean|Number} false when not found, or the index
29166 */
29167
29168
29169 function inArray(src, find, findByKey) {
29170 if (src.indexOf && !findByKey) {
29171 return src.indexOf(find);
29172 } else {
29173 var i = 0;
29174
29175 while (i < src.length) {
29176 if (findByKey && src[i][findByKey] == find || !findByKey && src[i] === find) {
29177 return i;
29178 }
29179
29180 i++;
29181 }
29182
29183 return -1;
29184 }
29185 }
29186 /**
29187 * convert array-like objects to real arrays
29188 * @param {Object} obj
29189 * @returns {Array}
29190 */
29191
29192
29193 function toArray(obj) {
29194 return Array.prototype.slice.call(obj, 0);
29195 }
29196 /**
29197 * unique array with objects based on a key (like 'id') or just by the array's value
29198 * @param {Array} src [{id:1},{id:2},{id:1}]
29199 * @param {String} [key]
29200 * @param {Boolean} [sort=False]
29201 * @returns {Array} [{id:1},{id:2}]
29202 */
29203
29204
29205 function uniqueArray(src, key, sort) {
29206 var results = [];
29207 var values = [];
29208 var i = 0;
29209
29210 while (i < src.length) {
29211 var val = key ? src[i][key] : src[i];
29212
29213 if (inArray(values, val) < 0) {
29214 results.push(src[i]);
29215 }
29216
29217 values[i] = val;
29218 i++;
29219 }
29220
29221 if (sort) {
29222 if (!key) {
29223 results = results.sort();
29224 } else {
29225 results = results.sort(function sortUniqueArray(a, b) {
29226 return a[key] > b[key];
29227 });
29228 }
29229 }
29230
29231 return results;
29232 }
29233 /**
29234 * get the prefixed property
29235 * @param {Object} obj
29236 * @param {String} property
29237 * @returns {String|Undefined} prefixed
29238 */
29239
29240
29241 function prefixed(obj, property) {
29242 var prefix, prop;
29243 var camelProp = property[0].toUpperCase() + property.slice(1);
29244 var i = 0;
29245
29246 while (i < VENDOR_PREFIXES.length) {
29247 prefix = VENDOR_PREFIXES[i];
29248 prop = prefix ? prefix + camelProp : property;
29249
29250 if (prop in obj) {
29251 return prop;
29252 }
29253
29254 i++;
29255 }
29256
29257 return undefined$1;
29258 }
29259 /**
29260 * get a unique id
29261 * @returns {number} uniqueId
29262 */
29263
29264
29265 var _uniqueId = 1;
29266
29267 function uniqueId() {
29268 return _uniqueId++;
29269 }
29270 /**
29271 * get the window object of an element
29272 * @param {HTMLElement} element
29273 * @returns {DocumentView|Window}
29274 */
29275
29276
29277 function getWindowForElement(element) {
29278 var doc = element.ownerDocument || element;
29279 return doc.defaultView || doc.parentWindow || window;
29280 }
29281
29282 var MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
29283 var SUPPORT_TOUCH = 'ontouchstart' in window;
29284 var SUPPORT_POINTER_EVENTS = prefixed(window, 'PointerEvent') !== undefined$1;
29285 var SUPPORT_ONLY_TOUCH = SUPPORT_TOUCH && MOBILE_REGEX.test(navigator.userAgent);
29286 var INPUT_TYPE_TOUCH = 'touch';
29287 var INPUT_TYPE_PEN = 'pen';
29288 var INPUT_TYPE_MOUSE = 'mouse';
29289 var INPUT_TYPE_KINECT = 'kinect';
29290 var COMPUTE_INTERVAL = 25;
29291 var INPUT_START = 1;
29292 var INPUT_MOVE = 2;
29293 var INPUT_END = 4;
29294 var INPUT_CANCEL = 8;
29295 var DIRECTION_NONE = 1;
29296 var DIRECTION_LEFT = 2;
29297 var DIRECTION_RIGHT = 4;
29298 var DIRECTION_UP = 8;
29299 var DIRECTION_DOWN = 16;
29300 var DIRECTION_HORIZONTAL = DIRECTION_LEFT | DIRECTION_RIGHT;
29301 var DIRECTION_VERTICAL = DIRECTION_UP | DIRECTION_DOWN;
29302 var DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL;
29303 var PROPS_XY = ['x', 'y'];
29304 var PROPS_CLIENT_XY = ['clientX', 'clientY'];
29305 /**
29306 * create new input type manager
29307 * @param {Manager} manager
29308 * @param {Function} callback
29309 * @returns {Input}
29310 * @constructor
29311 */
29312
29313 function Input(manager, callback) {
29314 var self = this;
29315 this.manager = manager;
29316 this.callback = callback;
29317 this.element = manager.element;
29318 this.target = manager.options.inputTarget; // smaller wrapper around the handler, for the scope and the enabled state of the manager,
29319 // so when disabled the input events are completely bypassed.
29320
29321 this.domHandler = function (ev) {
29322 if (boolOrFn(manager.options.enable, [manager])) {
29323 self.handler(ev);
29324 }
29325 };
29326
29327 this.init();
29328 }
29329
29330 Input.prototype = {
29331 /**
29332 * should handle the inputEvent data and trigger the callback
29333 * @virtual
29334 */
29335 handler: function () {},
29336
29337 /**
29338 * bind the events
29339 */
29340 init: function () {
29341 this.evEl && addEventListeners(this.element, this.evEl, this.domHandler);
29342 this.evTarget && addEventListeners(this.target, this.evTarget, this.domHandler);
29343 this.evWin && addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
29344 },
29345
29346 /**
29347 * unbind the events
29348 */
29349 destroy: function () {
29350 this.evEl && removeEventListeners(this.element, this.evEl, this.domHandler);
29351 this.evTarget && removeEventListeners(this.target, this.evTarget, this.domHandler);
29352 this.evWin && removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
29353 }
29354 };
29355 /**
29356 * create new input type manager
29357 * called by the Manager constructor
29358 * @param {Hammer} manager
29359 * @returns {Input}
29360 */
29361
29362 function createInputInstance(manager) {
29363 var Type;
29364 var inputClass = manager.options.inputClass;
29365
29366 if (inputClass) {
29367 Type = inputClass;
29368 } else if (SUPPORT_POINTER_EVENTS) {
29369 Type = PointerEventInput;
29370 } else if (SUPPORT_ONLY_TOUCH) {
29371 Type = TouchInput;
29372 } else if (!SUPPORT_TOUCH) {
29373 Type = MouseInput;
29374 } else {
29375 Type = TouchMouseInput;
29376 }
29377
29378 return new Type(manager, inputHandler);
29379 }
29380 /**
29381 * handle input events
29382 * @param {Manager} manager
29383 * @param {String} eventType
29384 * @param {Object} input
29385 */
29386
29387
29388 function inputHandler(manager, eventType, input) {
29389 var pointersLen = input.pointers.length;
29390 var changedPointersLen = input.changedPointers.length;
29391 var isFirst = eventType & INPUT_START && pointersLen - changedPointersLen === 0;
29392 var isFinal = eventType & (INPUT_END | INPUT_CANCEL) && pointersLen - changedPointersLen === 0;
29393 input.isFirst = !!isFirst;
29394 input.isFinal = !!isFinal;
29395
29396 if (isFirst) {
29397 manager.session = {};
29398 } // source event is the normalized value of the domEvents
29399 // like 'touchstart, mouseup, pointerdown'
29400
29401
29402 input.eventType = eventType; // compute scale, rotation etc
29403
29404 computeInputData(manager, input); // emit secret event
29405
29406 manager.emit('hammer.input', input);
29407 manager.recognize(input);
29408 manager.session.prevInput = input;
29409 }
29410 /**
29411 * extend the data with some usable properties like scale, rotate, velocity etc
29412 * @param {Object} manager
29413 * @param {Object} input
29414 */
29415
29416
29417 function computeInputData(manager, input) {
29418 var session = manager.session;
29419 var pointers = input.pointers;
29420 var pointersLength = pointers.length; // store the first input to calculate the distance and direction
29421
29422 if (!session.firstInput) {
29423 session.firstInput = simpleCloneInputData(input);
29424 } // to compute scale and rotation we need to store the multiple touches
29425
29426
29427 if (pointersLength > 1 && !session.firstMultiple) {
29428 session.firstMultiple = simpleCloneInputData(input);
29429 } else if (pointersLength === 1) {
29430 session.firstMultiple = false;
29431 }
29432
29433 var firstInput = session.firstInput;
29434 var firstMultiple = session.firstMultiple;
29435 var offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center;
29436 var center = input.center = getCenter(pointers);
29437 input.timeStamp = now();
29438 input.deltaTime = input.timeStamp - firstInput.timeStamp;
29439 input.angle = getAngle(offsetCenter, center);
29440 input.distance = getDistance(offsetCenter, center);
29441 computeDeltaXY(session, input);
29442 input.offsetDirection = getDirection(input.deltaX, input.deltaY);
29443 var overallVelocity = getVelocity(input.deltaTime, input.deltaX, input.deltaY);
29444 input.overallVelocityX = overallVelocity.x;
29445 input.overallVelocityY = overallVelocity.y;
29446 input.overallVelocity = abs(overallVelocity.x) > abs(overallVelocity.y) ? overallVelocity.x : overallVelocity.y;
29447 input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1;
29448 input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0;
29449 input.maxPointers = !session.prevInput ? input.pointers.length : input.pointers.length > session.prevInput.maxPointers ? input.pointers.length : session.prevInput.maxPointers;
29450 computeIntervalInputData(session, input); // find the correct target
29451
29452 var target = manager.element;
29453
29454 if (hasParent(input.srcEvent.target, target)) {
29455 target = input.srcEvent.target;
29456 }
29457
29458 input.target = target;
29459 }
29460
29461 function computeDeltaXY(session, input) {
29462 var center = input.center;
29463 var offset = session.offsetDelta || {};
29464 var prevDelta = session.prevDelta || {};
29465 var prevInput = session.prevInput || {};
29466
29467 if (input.eventType === INPUT_START || prevInput.eventType === INPUT_END) {
29468 prevDelta = session.prevDelta = {
29469 x: prevInput.deltaX || 0,
29470 y: prevInput.deltaY || 0
29471 };
29472 offset = session.offsetDelta = {
29473 x: center.x,
29474 y: center.y
29475 };
29476 }
29477
29478 input.deltaX = prevDelta.x + (center.x - offset.x);
29479 input.deltaY = prevDelta.y + (center.y - offset.y);
29480 }
29481 /**
29482 * velocity is calculated every x ms
29483 * @param {Object} session
29484 * @param {Object} input
29485 */
29486
29487
29488 function computeIntervalInputData(session, input) {
29489 var last = session.lastInterval || input,
29490 deltaTime = input.timeStamp - last.timeStamp,
29491 velocity,
29492 velocityX,
29493 velocityY,
29494 direction;
29495
29496 if (input.eventType != INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined$1)) {
29497 var deltaX = input.deltaX - last.deltaX;
29498 var deltaY = input.deltaY - last.deltaY;
29499 var v = getVelocity(deltaTime, deltaX, deltaY);
29500 velocityX = v.x;
29501 velocityY = v.y;
29502 velocity = abs(v.x) > abs(v.y) ? v.x : v.y;
29503 direction = getDirection(deltaX, deltaY);
29504 session.lastInterval = input;
29505 } else {
29506 // use latest velocity info if it doesn't overtake a minimum period
29507 velocity = last.velocity;
29508 velocityX = last.velocityX;
29509 velocityY = last.velocityY;
29510 direction = last.direction;
29511 }
29512
29513 input.velocity = velocity;
29514 input.velocityX = velocityX;
29515 input.velocityY = velocityY;
29516 input.direction = direction;
29517 }
29518 /**
29519 * create a simple clone from the input used for storage of firstInput and firstMultiple
29520 * @param {Object} input
29521 * @returns {Object} clonedInputData
29522 */
29523
29524
29525 function simpleCloneInputData(input) {
29526 // make a simple copy of the pointers because we will get a reference if we don't
29527 // we only need clientXY for the calculations
29528 var pointers = [];
29529 var i = 0;
29530
29531 while (i < input.pointers.length) {
29532 pointers[i] = {
29533 clientX: round(input.pointers[i].clientX),
29534 clientY: round(input.pointers[i].clientY)
29535 };
29536 i++;
29537 }
29538
29539 return {
29540 timeStamp: now(),
29541 pointers: pointers,
29542 center: getCenter(pointers),
29543 deltaX: input.deltaX,
29544 deltaY: input.deltaY
29545 };
29546 }
29547 /**
29548 * get the center of all the pointers
29549 * @param {Array} pointers
29550 * @return {Object} center contains `x` and `y` properties
29551 */
29552
29553
29554 function getCenter(pointers) {
29555 var pointersLength = pointers.length; // no need to loop when only one touch
29556
29557 if (pointersLength === 1) {
29558 return {
29559 x: round(pointers[0].clientX),
29560 y: round(pointers[0].clientY)
29561 };
29562 }
29563
29564 var x = 0,
29565 y = 0,
29566 i = 0;
29567
29568 while (i < pointersLength) {
29569 x += pointers[i].clientX;
29570 y += pointers[i].clientY;
29571 i++;
29572 }
29573
29574 return {
29575 x: round(x / pointersLength),
29576 y: round(y / pointersLength)
29577 };
29578 }
29579 /**
29580 * calculate the velocity between two points. unit is in px per ms.
29581 * @param {Number} deltaTime
29582 * @param {Number} x
29583 * @param {Number} y
29584 * @return {Object} velocity `x` and `y`
29585 */
29586
29587
29588 function getVelocity(deltaTime, x, y) {
29589 return {
29590 x: x / deltaTime || 0,
29591 y: y / deltaTime || 0
29592 };
29593 }
29594 /**
29595 * get the direction between two points
29596 * @param {Number} x
29597 * @param {Number} y
29598 * @return {Number} direction
29599 */
29600
29601
29602 function getDirection(x, y) {
29603 if (x === y) {
29604 return DIRECTION_NONE;
29605 }
29606
29607 if (abs(x) >= abs(y)) {
29608 return x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
29609 }
29610
29611 return y < 0 ? DIRECTION_UP : DIRECTION_DOWN;
29612 }
29613 /**
29614 * calculate the absolute distance between two points
29615 * @param {Object} p1 {x, y}
29616 * @param {Object} p2 {x, y}
29617 * @param {Array} [props] containing x and y keys
29618 * @return {Number} distance
29619 */
29620
29621
29622 function getDistance(p1, p2, props) {
29623 if (!props) {
29624 props = PROPS_XY;
29625 }
29626
29627 var x = p2[props[0]] - p1[props[0]],
29628 y = p2[props[1]] - p1[props[1]];
29629 return Math.sqrt(x * x + y * y);
29630 }
29631 /**
29632 * calculate the angle between two coordinates
29633 * @param {Object} p1
29634 * @param {Object} p2
29635 * @param {Array} [props] containing x and y keys
29636 * @return {Number} angle
29637 */
29638
29639
29640 function getAngle(p1, p2, props) {
29641 if (!props) {
29642 props = PROPS_XY;
29643 }
29644
29645 var x = p2[props[0]] - p1[props[0]],
29646 y = p2[props[1]] - p1[props[1]];
29647 return Math.atan2(y, x) * 180 / Math.PI;
29648 }
29649 /**
29650 * calculate the rotation degrees between two pointersets
29651 * @param {Array} start array of pointers
29652 * @param {Array} end array of pointers
29653 * @return {Number} rotation
29654 */
29655
29656
29657 function getRotation(start, end) {
29658 return getAngle(end[1], end[0], PROPS_CLIENT_XY) + getAngle(start[1], start[0], PROPS_CLIENT_XY);
29659 }
29660 /**
29661 * calculate the scale factor between two pointersets
29662 * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
29663 * @param {Array} start array of pointers
29664 * @param {Array} end array of pointers
29665 * @return {Number} scale
29666 */
29667
29668
29669 function getScale(start, end) {
29670 return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0], start[1], PROPS_CLIENT_XY);
29671 }
29672
29673 var MOUSE_INPUT_MAP = {
29674 mousedown: INPUT_START,
29675 mousemove: INPUT_MOVE,
29676 mouseup: INPUT_END
29677 };
29678 var MOUSE_ELEMENT_EVENTS = 'mousedown';
29679 var MOUSE_WINDOW_EVENTS = 'mousemove mouseup';
29680 /**
29681 * Mouse events input
29682 * @constructor
29683 * @extends Input
29684 */
29685
29686 function MouseInput() {
29687 this.evEl = MOUSE_ELEMENT_EVENTS;
29688 this.evWin = MOUSE_WINDOW_EVENTS;
29689 this.pressed = false; // mousedown state
29690
29691 Input.apply(this, arguments);
29692 }
29693
29694 inherit(MouseInput, Input, {
29695 /**
29696 * handle mouse events
29697 * @param {Object} ev
29698 */
29699 handler: function MEhandler(ev) {
29700 var eventType = MOUSE_INPUT_MAP[ev.type]; // on start we want to have the left mouse button down
29701
29702 if (eventType & INPUT_START && ev.button === 0) {
29703 this.pressed = true;
29704 }
29705
29706 if (eventType & INPUT_MOVE && ev.which !== 1) {
29707 eventType = INPUT_END;
29708 } // mouse must be down
29709
29710
29711 if (!this.pressed) {
29712 return;
29713 }
29714
29715 if (eventType & INPUT_END) {
29716 this.pressed = false;
29717 }
29718
29719 this.callback(this.manager, eventType, {
29720 pointers: [ev],
29721 changedPointers: [ev],
29722 pointerType: INPUT_TYPE_MOUSE,
29723 srcEvent: ev
29724 });
29725 }
29726 });
29727 var POINTER_INPUT_MAP = {
29728 pointerdown: INPUT_START,
29729 pointermove: INPUT_MOVE,
29730 pointerup: INPUT_END,
29731 pointercancel: INPUT_CANCEL,
29732 pointerout: INPUT_CANCEL
29733 }; // in IE10 the pointer types is defined as an enum
29734
29735 var IE10_POINTER_TYPE_ENUM = {
29736 2: INPUT_TYPE_TOUCH,
29737 3: INPUT_TYPE_PEN,
29738 4: INPUT_TYPE_MOUSE,
29739 5: INPUT_TYPE_KINECT // see https://twitter.com/jacobrossi/status/480596438489890816
29740
29741 };
29742 var POINTER_ELEMENT_EVENTS = 'pointerdown';
29743 var POINTER_WINDOW_EVENTS = 'pointermove pointerup pointercancel'; // IE10 has prefixed support, and case-sensitive
29744
29745 if (window.MSPointerEvent && !window.PointerEvent) {
29746 POINTER_ELEMENT_EVENTS = 'MSPointerDown';
29747 POINTER_WINDOW_EVENTS = 'MSPointerMove MSPointerUp MSPointerCancel';
29748 }
29749 /**
29750 * Pointer events input
29751 * @constructor
29752 * @extends Input
29753 */
29754
29755
29756 function PointerEventInput() {
29757 this.evEl = POINTER_ELEMENT_EVENTS;
29758 this.evWin = POINTER_WINDOW_EVENTS;
29759 Input.apply(this, arguments);
29760 this.store = this.manager.session.pointerEvents = [];
29761 }
29762
29763 inherit(PointerEventInput, Input, {
29764 /**
29765 * handle mouse events
29766 * @param {Object} ev
29767 */
29768 handler: function PEhandler(ev) {
29769 var store = this.store;
29770 var removePointer = false;
29771 var eventTypeNormalized = ev.type.toLowerCase().replace('ms', '');
29772 var eventType = POINTER_INPUT_MAP[eventTypeNormalized];
29773 var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType;
29774 var isTouch = pointerType == INPUT_TYPE_TOUCH; // get index of the event in the store
29775
29776 var storeIndex = inArray(store, ev.pointerId, 'pointerId'); // start and mouse must be down
29777
29778 if (eventType & INPUT_START && (ev.button === 0 || isTouch)) {
29779 if (storeIndex < 0) {
29780 store.push(ev);
29781 storeIndex = store.length - 1;
29782 }
29783 } else if (eventType & (INPUT_END | INPUT_CANCEL)) {
29784 removePointer = true;
29785 } // it not found, so the pointer hasn't been down (so it's probably a hover)
29786
29787
29788 if (storeIndex < 0) {
29789 return;
29790 } // update the event in the store
29791
29792
29793 store[storeIndex] = ev;
29794 this.callback(this.manager, eventType, {
29795 pointers: store,
29796 changedPointers: [ev],
29797 pointerType: pointerType,
29798 srcEvent: ev
29799 });
29800
29801 if (removePointer) {
29802 // remove from the store
29803 store.splice(storeIndex, 1);
29804 }
29805 }
29806 });
29807 var SINGLE_TOUCH_INPUT_MAP = {
29808 touchstart: INPUT_START,
29809 touchmove: INPUT_MOVE,
29810 touchend: INPUT_END,
29811 touchcancel: INPUT_CANCEL
29812 };
29813 var SINGLE_TOUCH_TARGET_EVENTS = 'touchstart';
29814 var SINGLE_TOUCH_WINDOW_EVENTS = 'touchstart touchmove touchend touchcancel';
29815 /**
29816 * Touch events input
29817 * @constructor
29818 * @extends Input
29819 */
29820
29821 function SingleTouchInput() {
29822 this.evTarget = SINGLE_TOUCH_TARGET_EVENTS;
29823 this.evWin = SINGLE_TOUCH_WINDOW_EVENTS;
29824 this.started = false;
29825 Input.apply(this, arguments);
29826 }
29827
29828 inherit(SingleTouchInput, Input, {
29829 handler: function TEhandler(ev) {
29830 var type = SINGLE_TOUCH_INPUT_MAP[ev.type]; // should we handle the touch events?
29831
29832 if (type === INPUT_START) {
29833 this.started = true;
29834 }
29835
29836 if (!this.started) {
29837 return;
29838 }
29839
29840 var touches = normalizeSingleTouches.call(this, ev, type); // when done, reset the started state
29841
29842 if (type & (INPUT_END | INPUT_CANCEL) && touches[0].length - touches[1].length === 0) {
29843 this.started = false;
29844 }
29845
29846 this.callback(this.manager, type, {
29847 pointers: touches[0],
29848 changedPointers: touches[1],
29849 pointerType: INPUT_TYPE_TOUCH,
29850 srcEvent: ev
29851 });
29852 }
29853 });
29854 /**
29855 * @this {TouchInput}
29856 * @param {Object} ev
29857 * @param {Number} type flag
29858 * @returns {undefined|Array} [all, changed]
29859 */
29860
29861 function normalizeSingleTouches(ev, type) {
29862 var all = toArray(ev.touches);
29863 var changed = toArray(ev.changedTouches);
29864
29865 if (type & (INPUT_END | INPUT_CANCEL)) {
29866 all = uniqueArray(all.concat(changed), 'identifier', true);
29867 }
29868
29869 return [all, changed];
29870 }
29871
29872 var TOUCH_INPUT_MAP = {
29873 touchstart: INPUT_START,
29874 touchmove: INPUT_MOVE,
29875 touchend: INPUT_END,
29876 touchcancel: INPUT_CANCEL
29877 };
29878 var TOUCH_TARGET_EVENTS = 'touchstart touchmove touchend touchcancel';
29879 /**
29880 * Multi-user touch events input
29881 * @constructor
29882 * @extends Input
29883 */
29884
29885 function TouchInput() {
29886 this.evTarget = TOUCH_TARGET_EVENTS;
29887 this.targetIds = {};
29888 Input.apply(this, arguments);
29889 }
29890
29891 inherit(TouchInput, Input, {
29892 handler: function MTEhandler(ev) {
29893 var type = TOUCH_INPUT_MAP[ev.type];
29894 var touches = getTouches.call(this, ev, type);
29895
29896 if (!touches) {
29897 return;
29898 }
29899
29900 this.callback(this.manager, type, {
29901 pointers: touches[0],
29902 changedPointers: touches[1],
29903 pointerType: INPUT_TYPE_TOUCH,
29904 srcEvent: ev
29905 });
29906 }
29907 });
29908 /**
29909 * @this {TouchInput}
29910 * @param {Object} ev
29911 * @param {Number} type flag
29912 * @returns {undefined|Array} [all, changed]
29913 */
29914
29915 function getTouches(ev, type) {
29916 var allTouches = toArray(ev.touches);
29917 var targetIds = this.targetIds; // when there is only one touch, the process can be simplified
29918
29919 if (type & (INPUT_START | INPUT_MOVE) && allTouches.length === 1) {
29920 targetIds[allTouches[0].identifier] = true;
29921 return [allTouches, allTouches];
29922 }
29923
29924 var i,
29925 targetTouches,
29926 changedTouches = toArray(ev.changedTouches),
29927 changedTargetTouches = [],
29928 target = this.target; // get target touches from touches
29929
29930 targetTouches = allTouches.filter(function (touch) {
29931 return hasParent(touch.target, target);
29932 }); // collect touches
29933
29934 if (type === INPUT_START) {
29935 i = 0;
29936
29937 while (i < targetTouches.length) {
29938 targetIds[targetTouches[i].identifier] = true;
29939 i++;
29940 }
29941 } // filter changed touches to only contain touches that exist in the collected target ids
29942
29943
29944 i = 0;
29945
29946 while (i < changedTouches.length) {
29947 if (targetIds[changedTouches[i].identifier]) {
29948 changedTargetTouches.push(changedTouches[i]);
29949 } // cleanup removed touches
29950
29951
29952 if (type & (INPUT_END | INPUT_CANCEL)) {
29953 delete targetIds[changedTouches[i].identifier];
29954 }
29955
29956 i++;
29957 }
29958
29959 if (!changedTargetTouches.length) {
29960 return;
29961 }
29962
29963 return [// merge targetTouches with changedTargetTouches so it contains ALL touches, including 'end' and 'cancel'
29964 uniqueArray(targetTouches.concat(changedTargetTouches), 'identifier', true), changedTargetTouches];
29965 }
29966 /**
29967 * Combined touch and mouse input
29968 *
29969 * Touch has a higher priority then mouse, and while touching no mouse events are allowed.
29970 * This because touch devices also emit mouse events while doing a touch.
29971 *
29972 * @constructor
29973 * @extends Input
29974 */
29975
29976
29977 var DEDUP_TIMEOUT = 2500;
29978 var DEDUP_DISTANCE = 25;
29979
29980 function TouchMouseInput() {
29981 Input.apply(this, arguments);
29982 var handler = bindFn(this.handler, this);
29983 this.touch = new TouchInput(this.manager, handler);
29984 this.mouse = new MouseInput(this.manager, handler);
29985 this.primaryTouch = null;
29986 this.lastTouches = [];
29987 }
29988
29989 inherit(TouchMouseInput, Input, {
29990 /**
29991 * handle mouse and touch events
29992 * @param {Hammer} manager
29993 * @param {String} inputEvent
29994 * @param {Object} inputData
29995 */
29996 handler: function TMEhandler(manager, inputEvent, inputData) {
29997 var isTouch = inputData.pointerType == INPUT_TYPE_TOUCH,
29998 isMouse = inputData.pointerType == INPUT_TYPE_MOUSE;
29999
30000 if (isMouse && inputData.sourceCapabilities && inputData.sourceCapabilities.firesTouchEvents) {
30001 return;
30002 } // when we're in a touch event, record touches to de-dupe synthetic mouse event
30003
30004
30005 if (isTouch) {
30006 recordTouches.call(this, inputEvent, inputData);
30007 } else if (isMouse && isSyntheticEvent.call(this, inputData)) {
30008 return;
30009 }
30010
30011 this.callback(manager, inputEvent, inputData);
30012 },
30013
30014 /**
30015 * remove the event listeners
30016 */
30017 destroy: function destroy() {
30018 this.touch.destroy();
30019 this.mouse.destroy();
30020 }
30021 });
30022
30023 function recordTouches(eventType, eventData) {
30024 if (eventType & INPUT_START) {
30025 this.primaryTouch = eventData.changedPointers[0].identifier;
30026 setLastTouch.call(this, eventData);
30027 } else if (eventType & (INPUT_END | INPUT_CANCEL)) {
30028 setLastTouch.call(this, eventData);
30029 }
30030 }
30031
30032 function setLastTouch(eventData) {
30033 var touch = eventData.changedPointers[0];
30034
30035 if (touch.identifier === this.primaryTouch) {
30036 var lastTouch = {
30037 x: touch.clientX,
30038 y: touch.clientY
30039 };
30040 this.lastTouches.push(lastTouch);
30041 var lts = this.lastTouches;
30042
30043 var removeLastTouch = function () {
30044 var i = lts.indexOf(lastTouch);
30045
30046 if (i > -1) {
30047 lts.splice(i, 1);
30048 }
30049 };
30050
30051 setTimeout(removeLastTouch, DEDUP_TIMEOUT);
30052 }
30053 }
30054
30055 function isSyntheticEvent(eventData) {
30056 var x = eventData.srcEvent.clientX,
30057 y = eventData.srcEvent.clientY;
30058
30059 for (var i = 0; i < this.lastTouches.length; i++) {
30060 var t = this.lastTouches[i];
30061 var dx = Math.abs(x - t.x),
30062 dy = Math.abs(y - t.y);
30063
30064 if (dx <= DEDUP_DISTANCE && dy <= DEDUP_DISTANCE) {
30065 return true;
30066 }
30067 }
30068
30069 return false;
30070 }
30071
30072 var PREFIXED_TOUCH_ACTION = prefixed(TEST_ELEMENT.style, 'touchAction');
30073 var NATIVE_TOUCH_ACTION = PREFIXED_TOUCH_ACTION !== undefined$1; // magical touchAction value
30074
30075 var TOUCH_ACTION_COMPUTE = 'compute';
30076 var TOUCH_ACTION_AUTO = 'auto';
30077 var TOUCH_ACTION_MANIPULATION = 'manipulation'; // not implemented
30078
30079 var TOUCH_ACTION_NONE = 'none';
30080 var TOUCH_ACTION_PAN_X = 'pan-x';
30081 var TOUCH_ACTION_PAN_Y = 'pan-y';
30082 var TOUCH_ACTION_MAP = getTouchActionProps();
30083 /**
30084 * Touch Action
30085 * sets the touchAction property or uses the js alternative
30086 * @param {Manager} manager
30087 * @param {String} value
30088 * @constructor
30089 */
30090
30091 function TouchAction(manager, value) {
30092 this.manager = manager;
30093 this.set(value);
30094 }
30095
30096 TouchAction.prototype = {
30097 /**
30098 * set the touchAction value on the element or enable the polyfill
30099 * @param {String} value
30100 */
30101 set: function (value) {
30102 // find out the touch-action by the event handlers
30103 if (value == TOUCH_ACTION_COMPUTE) {
30104 value = this.compute();
30105 }
30106
30107 if (NATIVE_TOUCH_ACTION && this.manager.element.style && TOUCH_ACTION_MAP[value]) {
30108 this.manager.element.style[PREFIXED_TOUCH_ACTION] = value;
30109 }
30110
30111 this.actions = value.toLowerCase().trim();
30112 },
30113
30114 /**
30115 * just re-set the touchAction value
30116 */
30117 update: function () {
30118 this.set(this.manager.options.touchAction);
30119 },
30120
30121 /**
30122 * compute the value for the touchAction property based on the recognizer's settings
30123 * @returns {String} value
30124 */
30125 compute: function () {
30126 var actions = [];
30127 each(this.manager.recognizers, function (recognizer) {
30128 if (boolOrFn(recognizer.options.enable, [recognizer])) {
30129 actions = actions.concat(recognizer.getTouchAction());
30130 }
30131 });
30132 return cleanTouchActions(actions.join(' '));
30133 },
30134
30135 /**
30136 * this method is called on each input cycle and provides the preventing of the browser behavior
30137 * @param {Object} input
30138 */
30139 preventDefaults: function (input) {
30140 var srcEvent = input.srcEvent;
30141 var direction = input.offsetDirection; // if the touch action did prevented once this session
30142
30143 if (this.manager.session.prevented) {
30144 srcEvent.preventDefault();
30145 return;
30146 }
30147
30148 var actions = this.actions;
30149 var hasNone = inStr(actions, TOUCH_ACTION_NONE) && !TOUCH_ACTION_MAP[TOUCH_ACTION_NONE];
30150 var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_Y];
30151 var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_X];
30152
30153 if (hasNone) {
30154 //do not prevent defaults if this is a tap gesture
30155 var isTapPointer = input.pointers.length === 1;
30156 var isTapMovement = input.distance < 2;
30157 var isTapTouchTime = input.deltaTime < 250;
30158
30159 if (isTapPointer && isTapMovement && isTapTouchTime) {
30160 return;
30161 }
30162 }
30163
30164 if (hasPanX && hasPanY) {
30165 // `pan-x pan-y` means browser handles all scrolling/panning, do not prevent
30166 return;
30167 }
30168
30169 if (hasNone || hasPanY && direction & DIRECTION_HORIZONTAL || hasPanX && direction & DIRECTION_VERTICAL) {
30170 return this.preventSrc(srcEvent);
30171 }
30172 },
30173
30174 /**
30175 * call preventDefault to prevent the browser's default behavior (scrolling in most cases)
30176 * @param {Object} srcEvent
30177 */
30178 preventSrc: function (srcEvent) {
30179 this.manager.session.prevented = true;
30180 srcEvent.preventDefault();
30181 }
30182 };
30183 /**
30184 * when the touchActions are collected they are not a valid value, so we need to clean things up. *
30185 * @param {String} actions
30186 * @returns {*}
30187 */
30188
30189 function cleanTouchActions(actions) {
30190 // none
30191 if (inStr(actions, TOUCH_ACTION_NONE)) {
30192 return TOUCH_ACTION_NONE;
30193 }
30194
30195 var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X);
30196 var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y); // if both pan-x and pan-y are set (different recognizers
30197 // for different directions, e.g. horizontal pan but vertical swipe?)
30198 // we need none (as otherwise with pan-x pan-y combined none of these
30199 // recognizers will work, since the browser would handle all panning
30200
30201 if (hasPanX && hasPanY) {
30202 return TOUCH_ACTION_NONE;
30203 } // pan-x OR pan-y
30204
30205
30206 if (hasPanX || hasPanY) {
30207 return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y;
30208 } // manipulation
30209
30210
30211 if (inStr(actions, TOUCH_ACTION_MANIPULATION)) {
30212 return TOUCH_ACTION_MANIPULATION;
30213 }
30214
30215 return TOUCH_ACTION_AUTO;
30216 }
30217
30218 function getTouchActionProps() {
30219 if (!NATIVE_TOUCH_ACTION) {
30220 return false;
30221 }
30222
30223 var touchMap = {};
30224 var cssSupports = window.CSS && window.CSS.supports;
30225 ['auto', 'manipulation', 'pan-y', 'pan-x', 'pan-x pan-y', 'none'].forEach(function (val) {
30226 // If css.supports is not supported but there is native touch-action assume it supports
30227 // all values. This is the case for IE 10 and 11.
30228 touchMap[val] = cssSupports ? window.CSS.supports('touch-action', val) : true;
30229 });
30230 return touchMap;
30231 }
30232 /**
30233 * Recognizer flow explained; *
30234 * All recognizers have the initial state of POSSIBLE when a input session starts.
30235 * The definition of a input session is from the first input until the last input, with all it's movement in it. *
30236 * Example session for mouse-input: mousedown -> mousemove -> mouseup
30237 *
30238 * On each recognizing cycle (see Manager.recognize) the .recognize() method is executed
30239 * which determines with state it should be.
30240 *
30241 * If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to
30242 * POSSIBLE to give it another change on the next cycle.
30243 *
30244 * Possible
30245 * |
30246 * +-----+---------------+
30247 * | |
30248 * +-----+-----+ |
30249 * | | |
30250 * Failed Cancelled |
30251 * +-------+------+
30252 * | |
30253 * Recognized Began
30254 * |
30255 * Changed
30256 * |
30257 * Ended/Recognized
30258 */
30259
30260
30261 var STATE_POSSIBLE = 1;
30262 var STATE_BEGAN = 2;
30263 var STATE_CHANGED = 4;
30264 var STATE_ENDED = 8;
30265 var STATE_RECOGNIZED = STATE_ENDED;
30266 var STATE_CANCELLED = 16;
30267 var STATE_FAILED = 32;
30268 /**
30269 * Recognizer
30270 * Every recognizer needs to extend from this class.
30271 * @constructor
30272 * @param {Object} options
30273 */
30274
30275 function Recognizer(options) {
30276 this.options = assign({}, this.defaults, options || {});
30277 this.id = uniqueId();
30278 this.manager = null; // default is enable true
30279
30280 this.options.enable = ifUndefined(this.options.enable, true);
30281 this.state = STATE_POSSIBLE;
30282 this.simultaneous = {};
30283 this.requireFail = [];
30284 }
30285
30286 Recognizer.prototype = {
30287 /**
30288 * @virtual
30289 * @type {Object}
30290 */
30291 defaults: {},
30292
30293 /**
30294 * set options
30295 * @param {Object} options
30296 * @return {Recognizer}
30297 */
30298 set: function (options) {
30299 assign(this.options, options); // also update the touchAction, in case something changed about the directions/enabled state
30300
30301 this.manager && this.manager.touchAction.update();
30302 return this;
30303 },
30304
30305 /**
30306 * recognize simultaneous with an other recognizer.
30307 * @param {Recognizer} otherRecognizer
30308 * @returns {Recognizer} this
30309 */
30310 recognizeWith: function (otherRecognizer) {
30311 if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) {
30312 return this;
30313 }
30314
30315 var simultaneous = this.simultaneous;
30316 otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
30317
30318 if (!simultaneous[otherRecognizer.id]) {
30319 simultaneous[otherRecognizer.id] = otherRecognizer;
30320 otherRecognizer.recognizeWith(this);
30321 }
30322
30323 return this;
30324 },
30325
30326 /**
30327 * drop the simultaneous link. it doesnt remove the link on the other recognizer.
30328 * @param {Recognizer} otherRecognizer
30329 * @returns {Recognizer} this
30330 */
30331 dropRecognizeWith: function (otherRecognizer) {
30332 if (invokeArrayArg(otherRecognizer, 'dropRecognizeWith', this)) {
30333 return this;
30334 }
30335
30336 otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
30337 delete this.simultaneous[otherRecognizer.id];
30338 return this;
30339 },
30340
30341 /**
30342 * recognizer can only run when an other is failing
30343 * @param {Recognizer} otherRecognizer
30344 * @returns {Recognizer} this
30345 */
30346 requireFailure: function (otherRecognizer) {
30347 if (invokeArrayArg(otherRecognizer, 'requireFailure', this)) {
30348 return this;
30349 }
30350
30351 var requireFail = this.requireFail;
30352 otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
30353
30354 if (inArray(requireFail, otherRecognizer) === -1) {
30355 requireFail.push(otherRecognizer);
30356 otherRecognizer.requireFailure(this);
30357 }
30358
30359 return this;
30360 },
30361
30362 /**
30363 * drop the requireFailure link. it does not remove the link on the other recognizer.
30364 * @param {Recognizer} otherRecognizer
30365 * @returns {Recognizer} this
30366 */
30367 dropRequireFailure: function (otherRecognizer) {
30368 if (invokeArrayArg(otherRecognizer, 'dropRequireFailure', this)) {
30369 return this;
30370 }
30371
30372 otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
30373 var index = inArray(this.requireFail, otherRecognizer);
30374
30375 if (index > -1) {
30376 this.requireFail.splice(index, 1);
30377 }
30378
30379 return this;
30380 },
30381
30382 /**
30383 * has require failures boolean
30384 * @returns {boolean}
30385 */
30386 hasRequireFailures: function () {
30387 return this.requireFail.length > 0;
30388 },
30389
30390 /**
30391 * if the recognizer can recognize simultaneous with an other recognizer
30392 * @param {Recognizer} otherRecognizer
30393 * @returns {Boolean}
30394 */
30395 canRecognizeWith: function (otherRecognizer) {
30396 return !!this.simultaneous[otherRecognizer.id];
30397 },
30398
30399 /**
30400 * You should use `tryEmit` instead of `emit` directly to check
30401 * that all the needed recognizers has failed before emitting.
30402 * @param {Object} input
30403 */
30404 emit: function (input) {
30405 var self = this;
30406 var state = this.state;
30407
30408 function emit(event) {
30409 self.manager.emit(event, input);
30410 } // 'panstart' and 'panmove'
30411
30412
30413 if (state < STATE_ENDED) {
30414 emit(self.options.event + stateStr(state));
30415 }
30416
30417 emit(self.options.event); // simple 'eventName' events
30418
30419 if (input.additionalEvent) {
30420 // additional event(panleft, panright, pinchin, pinchout...)
30421 emit(input.additionalEvent);
30422 } // panend and pancancel
30423
30424
30425 if (state >= STATE_ENDED) {
30426 emit(self.options.event + stateStr(state));
30427 }
30428 },
30429
30430 /**
30431 * Check that all the require failure recognizers has failed,
30432 * if true, it emits a gesture event,
30433 * otherwise, setup the state to FAILED.
30434 * @param {Object} input
30435 */
30436 tryEmit: function (input) {
30437 if (this.canEmit()) {
30438 return this.emit(input);
30439 } // it's failing anyway
30440
30441
30442 this.state = STATE_FAILED;
30443 },
30444
30445 /**
30446 * can we emit?
30447 * @returns {boolean}
30448 */
30449 canEmit: function () {
30450 var i = 0;
30451
30452 while (i < this.requireFail.length) {
30453 if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) {
30454 return false;
30455 }
30456
30457 i++;
30458 }
30459
30460 return true;
30461 },
30462
30463 /**
30464 * update the recognizer
30465 * @param {Object} inputData
30466 */
30467 recognize: function (inputData) {
30468 // make a new copy of the inputData
30469 // so we can change the inputData without messing up the other recognizers
30470 var inputDataClone = assign({}, inputData); // is is enabled and allow recognizing?
30471
30472 if (!boolOrFn(this.options.enable, [this, inputDataClone])) {
30473 this.reset();
30474 this.state = STATE_FAILED;
30475 return;
30476 } // reset when we've reached the end
30477
30478
30479 if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) {
30480 this.state = STATE_POSSIBLE;
30481 }
30482
30483 this.state = this.process(inputDataClone); // the recognizer has recognized a gesture
30484 // so trigger an event
30485
30486 if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) {
30487 this.tryEmit(inputDataClone);
30488 }
30489 },
30490
30491 /**
30492 * return the state of the recognizer
30493 * the actual recognizing happens in this method
30494 * @virtual
30495 * @param {Object} inputData
30496 * @returns {Const} STATE
30497 */
30498 process: function (inputData) {},
30499 // jshint ignore:line
30500
30501 /**
30502 * return the preferred touch-action
30503 * @virtual
30504 * @returns {Array}
30505 */
30506 getTouchAction: function () {},
30507
30508 /**
30509 * called when the gesture isn't allowed to recognize
30510 * like when another is being recognized or it is disabled
30511 * @virtual
30512 */
30513 reset: function () {}
30514 };
30515 /**
30516 * get a usable string, used as event postfix
30517 * @param {Const} state
30518 * @returns {String} state
30519 */
30520
30521 function stateStr(state) {
30522 if (state & STATE_CANCELLED) {
30523 return 'cancel';
30524 } else if (state & STATE_ENDED) {
30525 return 'end';
30526 } else if (state & STATE_CHANGED) {
30527 return 'move';
30528 } else if (state & STATE_BEGAN) {
30529 return 'start';
30530 }
30531
30532 return '';
30533 }
30534 /**
30535 * direction cons to string
30536 * @param {Const} direction
30537 * @returns {String}
30538 */
30539
30540
30541 function directionStr(direction) {
30542 if (direction == DIRECTION_DOWN) {
30543 return 'down';
30544 } else if (direction == DIRECTION_UP) {
30545 return 'up';
30546 } else if (direction == DIRECTION_LEFT) {
30547 return 'left';
30548 } else if (direction == DIRECTION_RIGHT) {
30549 return 'right';
30550 }
30551
30552 return '';
30553 }
30554 /**
30555 * get a recognizer by name if it is bound to a manager
30556 * @param {Recognizer|String} otherRecognizer
30557 * @param {Recognizer} recognizer
30558 * @returns {Recognizer}
30559 */
30560
30561
30562 function getRecognizerByNameIfManager(otherRecognizer, recognizer) {
30563 var manager = recognizer.manager;
30564
30565 if (manager) {
30566 return manager.get(otherRecognizer);
30567 }
30568
30569 return otherRecognizer;
30570 }
30571 /**
30572 * This recognizer is just used as a base for the simple attribute recognizers.
30573 * @constructor
30574 * @extends Recognizer
30575 */
30576
30577
30578 function AttrRecognizer() {
30579 Recognizer.apply(this, arguments);
30580 }
30581
30582 inherit(AttrRecognizer, Recognizer, {
30583 /**
30584 * @namespace
30585 * @memberof AttrRecognizer
30586 */
30587 defaults: {
30588 /**
30589 * @type {Number}
30590 * @default 1
30591 */
30592 pointers: 1
30593 },
30594
30595 /**
30596 * Used to check if it the recognizer receives valid input, like input.distance > 10.
30597 * @memberof AttrRecognizer
30598 * @param {Object} input
30599 * @returns {Boolean} recognized
30600 */
30601 attrTest: function (input) {
30602 var optionPointers = this.options.pointers;
30603 return optionPointers === 0 || input.pointers.length === optionPointers;
30604 },
30605
30606 /**
30607 * Process the input and return the state for the recognizer
30608 * @memberof AttrRecognizer
30609 * @param {Object} input
30610 * @returns {*} State
30611 */
30612 process: function (input) {
30613 var state = this.state;
30614 var eventType = input.eventType;
30615 var isRecognized = state & (STATE_BEGAN | STATE_CHANGED);
30616 var isValid = this.attrTest(input); // on cancel input and we've recognized before, return STATE_CANCELLED
30617
30618 if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) {
30619 return state | STATE_CANCELLED;
30620 } else if (isRecognized || isValid) {
30621 if (eventType & INPUT_END) {
30622 return state | STATE_ENDED;
30623 } else if (!(state & STATE_BEGAN)) {
30624 return STATE_BEGAN;
30625 }
30626
30627 return state | STATE_CHANGED;
30628 }
30629
30630 return STATE_FAILED;
30631 }
30632 });
30633 /**
30634 * Pan
30635 * Recognized when the pointer is down and moved in the allowed direction.
30636 * @constructor
30637 * @extends AttrRecognizer
30638 */
30639
30640 function PanRecognizer() {
30641 AttrRecognizer.apply(this, arguments);
30642 this.pX = null;
30643 this.pY = null;
30644 }
30645
30646 inherit(PanRecognizer, AttrRecognizer, {
30647 /**
30648 * @namespace
30649 * @memberof PanRecognizer
30650 */
30651 defaults: {
30652 event: 'pan',
30653 threshold: 10,
30654 pointers: 1,
30655 direction: DIRECTION_ALL
30656 },
30657 getTouchAction: function () {
30658 var direction = this.options.direction;
30659 var actions = [];
30660
30661 if (direction & DIRECTION_HORIZONTAL) {
30662 actions.push(TOUCH_ACTION_PAN_Y);
30663 }
30664
30665 if (direction & DIRECTION_VERTICAL) {
30666 actions.push(TOUCH_ACTION_PAN_X);
30667 }
30668
30669 return actions;
30670 },
30671 directionTest: function (input) {
30672 var options = this.options;
30673 var hasMoved = true;
30674 var distance = input.distance;
30675 var direction = input.direction;
30676 var x = input.deltaX;
30677 var y = input.deltaY; // lock to axis?
30678
30679 if (!(direction & options.direction)) {
30680 if (options.direction & DIRECTION_HORIZONTAL) {
30681 direction = x === 0 ? DIRECTION_NONE : x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
30682 hasMoved = x != this.pX;
30683 distance = Math.abs(input.deltaX);
30684 } else {
30685 direction = y === 0 ? DIRECTION_NONE : y < 0 ? DIRECTION_UP : DIRECTION_DOWN;
30686 hasMoved = y != this.pY;
30687 distance = Math.abs(input.deltaY);
30688 }
30689 }
30690
30691 input.direction = direction;
30692 return hasMoved && distance > options.threshold && direction & options.direction;
30693 },
30694 attrTest: function (input) {
30695 return AttrRecognizer.prototype.attrTest.call(this, input) && (this.state & STATE_BEGAN || !(this.state & STATE_BEGAN) && this.directionTest(input));
30696 },
30697 emit: function (input) {
30698 this.pX = input.deltaX;
30699 this.pY = input.deltaY;
30700 var direction = directionStr(input.direction);
30701
30702 if (direction) {
30703 input.additionalEvent = this.options.event + direction;
30704 }
30705
30706 this._super.emit.call(this, input);
30707 }
30708 });
30709 /**
30710 * Pinch
30711 * Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out).
30712 * @constructor
30713 * @extends AttrRecognizer
30714 */
30715
30716 function PinchRecognizer() {
30717 AttrRecognizer.apply(this, arguments);
30718 }
30719
30720 inherit(PinchRecognizer, AttrRecognizer, {
30721 /**
30722 * @namespace
30723 * @memberof PinchRecognizer
30724 */
30725 defaults: {
30726 event: 'pinch',
30727 threshold: 0,
30728 pointers: 2
30729 },
30730 getTouchAction: function () {
30731 return [TOUCH_ACTION_NONE];
30732 },
30733 attrTest: function (input) {
30734 return this._super.attrTest.call(this, input) && (Math.abs(input.scale - 1) > this.options.threshold || this.state & STATE_BEGAN);
30735 },
30736 emit: function (input) {
30737 if (input.scale !== 1) {
30738 var inOut = input.scale < 1 ? 'in' : 'out';
30739 input.additionalEvent = this.options.event + inOut;
30740 }
30741
30742 this._super.emit.call(this, input);
30743 }
30744 });
30745 /**
30746 * Press
30747 * Recognized when the pointer is down for x ms without any movement.
30748 * @constructor
30749 * @extends Recognizer
30750 */
30751
30752 function PressRecognizer() {
30753 Recognizer.apply(this, arguments);
30754 this._timer = null;
30755 this._input = null;
30756 }
30757
30758 inherit(PressRecognizer, Recognizer, {
30759 /**
30760 * @namespace
30761 * @memberof PressRecognizer
30762 */
30763 defaults: {
30764 event: 'press',
30765 pointers: 1,
30766 time: 251,
30767 // minimal time of the pointer to be pressed
30768 threshold: 9 // a minimal movement is ok, but keep it low
30769
30770 },
30771 getTouchAction: function () {
30772 return [TOUCH_ACTION_AUTO];
30773 },
30774 process: function (input) {
30775 var options = this.options;
30776 var validPointers = input.pointers.length === options.pointers;
30777 var validMovement = input.distance < options.threshold;
30778 var validTime = input.deltaTime > options.time;
30779 this._input = input; // we only allow little movement
30780 // and we've reached an end event, so a tap is possible
30781
30782 if (!validMovement || !validPointers || input.eventType & (INPUT_END | INPUT_CANCEL) && !validTime) {
30783 this.reset();
30784 } else if (input.eventType & INPUT_START) {
30785 this.reset();
30786 this._timer = setTimeoutContext(function () {
30787 this.state = STATE_RECOGNIZED;
30788 this.tryEmit();
30789 }, options.time, this);
30790 } else if (input.eventType & INPUT_END) {
30791 return STATE_RECOGNIZED;
30792 }
30793
30794 return STATE_FAILED;
30795 },
30796 reset: function () {
30797 clearTimeout(this._timer);
30798 },
30799 emit: function (input) {
30800 if (this.state !== STATE_RECOGNIZED) {
30801 return;
30802 }
30803
30804 if (input && input.eventType & INPUT_END) {
30805 this.manager.emit(this.options.event + 'up', input);
30806 } else {
30807 this._input.timeStamp = now();
30808 this.manager.emit(this.options.event, this._input);
30809 }
30810 }
30811 });
30812 /**
30813 * Rotate
30814 * Recognized when two or more pointer are moving in a circular motion.
30815 * @constructor
30816 * @extends AttrRecognizer
30817 */
30818
30819 function RotateRecognizer() {
30820 AttrRecognizer.apply(this, arguments);
30821 }
30822
30823 inherit(RotateRecognizer, AttrRecognizer, {
30824 /**
30825 * @namespace
30826 * @memberof RotateRecognizer
30827 */
30828 defaults: {
30829 event: 'rotate',
30830 threshold: 0,
30831 pointers: 2
30832 },
30833 getTouchAction: function () {
30834 return [TOUCH_ACTION_NONE];
30835 },
30836 attrTest: function (input) {
30837 return this._super.attrTest.call(this, input) && (Math.abs(input.rotation) > this.options.threshold || this.state & STATE_BEGAN);
30838 }
30839 });
30840 /**
30841 * Swipe
30842 * Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction.
30843 * @constructor
30844 * @extends AttrRecognizer
30845 */
30846
30847 function SwipeRecognizer() {
30848 AttrRecognizer.apply(this, arguments);
30849 }
30850
30851 inherit(SwipeRecognizer, AttrRecognizer, {
30852 /**
30853 * @namespace
30854 * @memberof SwipeRecognizer
30855 */
30856 defaults: {
30857 event: 'swipe',
30858 threshold: 10,
30859 velocity: 0.3,
30860 direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL,
30861 pointers: 1
30862 },
30863 getTouchAction: function () {
30864 return PanRecognizer.prototype.getTouchAction.call(this);
30865 },
30866 attrTest: function (input) {
30867 var direction = this.options.direction;
30868 var velocity;
30869
30870 if (direction & (DIRECTION_HORIZONTAL | DIRECTION_VERTICAL)) {
30871 velocity = input.overallVelocity;
30872 } else if (direction & DIRECTION_HORIZONTAL) {
30873 velocity = input.overallVelocityX;
30874 } else if (direction & DIRECTION_VERTICAL) {
30875 velocity = input.overallVelocityY;
30876 }
30877
30878 return this._super.attrTest.call(this, input) && direction & input.offsetDirection && input.distance > this.options.threshold && input.maxPointers == this.options.pointers && abs(velocity) > this.options.velocity && input.eventType & INPUT_END;
30879 },
30880 emit: function (input) {
30881 var direction = directionStr(input.offsetDirection);
30882
30883 if (direction) {
30884 this.manager.emit(this.options.event + direction, input);
30885 }
30886
30887 this.manager.emit(this.options.event, input);
30888 }
30889 });
30890 /**
30891 * A tap is ecognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur
30892 * between the given interval and position. The delay option can be used to recognize multi-taps without firing
30893 * a single tap.
30894 *
30895 * The eventData from the emitted event contains the property `tapCount`, which contains the amount of
30896 * multi-taps being recognized.
30897 * @constructor
30898 * @extends Recognizer
30899 */
30900
30901 function TapRecognizer() {
30902 Recognizer.apply(this, arguments); // previous time and center,
30903 // used for tap counting
30904
30905 this.pTime = false;
30906 this.pCenter = false;
30907 this._timer = null;
30908 this._input = null;
30909 this.count = 0;
30910 }
30911
30912 inherit(TapRecognizer, Recognizer, {
30913 /**
30914 * @namespace
30915 * @memberof PinchRecognizer
30916 */
30917 defaults: {
30918 event: 'tap',
30919 pointers: 1,
30920 taps: 1,
30921 interval: 300,
30922 // max time between the multi-tap taps
30923 time: 250,
30924 // max time of the pointer to be down (like finger on the screen)
30925 threshold: 9,
30926 // a minimal movement is ok, but keep it low
30927 posThreshold: 10 // a multi-tap can be a bit off the initial position
30928
30929 },
30930 getTouchAction: function () {
30931 return [TOUCH_ACTION_MANIPULATION];
30932 },
30933 process: function (input) {
30934 var options = this.options;
30935 var validPointers = input.pointers.length === options.pointers;
30936 var validMovement = input.distance < options.threshold;
30937 var validTouchTime = input.deltaTime < options.time;
30938 this.reset();
30939
30940 if (input.eventType & INPUT_START && this.count === 0) {
30941 return this.failTimeout();
30942 } // we only allow little movement
30943 // and we've reached an end event, so a tap is possible
30944
30945
30946 if (validMovement && validTouchTime && validPointers) {
30947 if (input.eventType != INPUT_END) {
30948 return this.failTimeout();
30949 }
30950
30951 var validInterval = this.pTime ? input.timeStamp - this.pTime < options.interval : true;
30952 var validMultiTap = !this.pCenter || getDistance(this.pCenter, input.center) < options.posThreshold;
30953 this.pTime = input.timeStamp;
30954 this.pCenter = input.center;
30955
30956 if (!validMultiTap || !validInterval) {
30957 this.count = 1;
30958 } else {
30959 this.count += 1;
30960 }
30961
30962 this._input = input; // if tap count matches we have recognized it,
30963 // else it has began recognizing...
30964
30965 var tapCount = this.count % options.taps;
30966
30967 if (tapCount === 0) {
30968 // no failing requirements, immediately trigger the tap event
30969 // or wait as long as the multitap interval to trigger
30970 if (!this.hasRequireFailures()) {
30971 return STATE_RECOGNIZED;
30972 } else {
30973 this._timer = setTimeoutContext(function () {
30974 this.state = STATE_RECOGNIZED;
30975 this.tryEmit();
30976 }, options.interval, this);
30977 return STATE_BEGAN;
30978 }
30979 }
30980 }
30981
30982 return STATE_FAILED;
30983 },
30984 failTimeout: function () {
30985 this._timer = setTimeoutContext(function () {
30986 this.state = STATE_FAILED;
30987 }, this.options.interval, this);
30988 return STATE_FAILED;
30989 },
30990 reset: function () {
30991 clearTimeout(this._timer);
30992 },
30993 emit: function () {
30994 if (this.state == STATE_RECOGNIZED) {
30995 this._input.tapCount = this.count;
30996 this.manager.emit(this.options.event, this._input);
30997 }
30998 }
30999 });
31000 /**
31001 * Simple way to create a manager with a default set of recognizers.
31002 * @param {HTMLElement} element
31003 * @param {Object} [options]
31004 * @constructor
31005 */
31006
31007 function Hammer(element, options) {
31008 options = options || {};
31009 options.recognizers = ifUndefined(options.recognizers, Hammer.defaults.preset);
31010 return new Manager(element, options);
31011 }
31012 /**
31013 * @const {string}
31014 */
31015
31016
31017 Hammer.VERSION = '2.0.7';
31018 /**
31019 * default settings
31020 * @namespace
31021 */
31022
31023 Hammer.defaults = {
31024 /**
31025 * set if DOM events are being triggered.
31026 * But this is slower and unused by simple implementations, so disabled by default.
31027 * @type {Boolean}
31028 * @default false
31029 */
31030 domEvents: false,
31031
31032 /**
31033 * The value for the touchAction property/fallback.
31034 * When set to `compute` it will magically set the correct value based on the added recognizers.
31035 * @type {String}
31036 * @default compute
31037 */
31038 touchAction: TOUCH_ACTION_COMPUTE,
31039
31040 /**
31041 * @type {Boolean}
31042 * @default true
31043 */
31044 enable: true,
31045
31046 /**
31047 * EXPERIMENTAL FEATURE -- can be removed/changed
31048 * Change the parent input target element.
31049 * If Null, then it is being set the to main element.
31050 * @type {Null|EventTarget}
31051 * @default null
31052 */
31053 inputTarget: null,
31054
31055 /**
31056 * force an input class
31057 * @type {Null|Function}
31058 * @default null
31059 */
31060 inputClass: null,
31061
31062 /**
31063 * Default recognizer setup when calling `Hammer()`
31064 * When creating a new Manager these will be skipped.
31065 * @type {Array}
31066 */
31067 preset: [// RecognizerClass, options, [recognizeWith, ...], [requireFailure, ...]
31068 [RotateRecognizer, {
31069 enable: false
31070 }], [PinchRecognizer, {
31071 enable: false
31072 }, ['rotate']], [SwipeRecognizer, {
31073 direction: DIRECTION_HORIZONTAL
31074 }], [PanRecognizer, {
31075 direction: DIRECTION_HORIZONTAL
31076 }, ['swipe']], [TapRecognizer], [TapRecognizer, {
31077 event: 'doubletap',
31078 taps: 2
31079 }, ['tap']], [PressRecognizer]],
31080
31081 /**
31082 * Some CSS properties can be used to improve the working of Hammer.
31083 * Add them to this method and they will be set when creating a new Manager.
31084 * @namespace
31085 */
31086 cssProps: {
31087 /**
31088 * Disables text selection to improve the dragging gesture. Mainly for desktop browsers.
31089 * @type {String}
31090 * @default 'none'
31091 */
31092 userSelect: 'none',
31093
31094 /**
31095 * Disable the Windows Phone grippers when pressing an element.
31096 * @type {String}
31097 * @default 'none'
31098 */
31099 touchSelect: 'none',
31100
31101 /**
31102 * Disables the default callout shown when you touch and hold a touch target.
31103 * On iOS, when you touch and hold a touch target such as a link, Safari displays
31104 * a callout containing information about the link. This property allows you to disable that callout.
31105 * @type {String}
31106 * @default 'none'
31107 */
31108 touchCallout: 'none',
31109
31110 /**
31111 * Specifies whether zooming is enabled. Used by IE10>
31112 * @type {String}
31113 * @default 'none'
31114 */
31115 contentZooming: 'none',
31116
31117 /**
31118 * Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers.
31119 * @type {String}
31120 * @default 'none'
31121 */
31122 userDrag: 'none',
31123
31124 /**
31125 * Overrides the highlight color shown when the user taps a link or a JavaScript
31126 * clickable element in iOS. This property obeys the alpha value, if specified.
31127 * @type {String}
31128 * @default 'rgba(0,0,0,0)'
31129 */
31130 tapHighlightColor: 'rgba(0,0,0,0)'
31131 }
31132 };
31133 var STOP = 1;
31134 var FORCED_STOP = 2;
31135 /**
31136 * Manager
31137 * @param {HTMLElement} element
31138 * @param {Object} [options]
31139 * @constructor
31140 */
31141
31142 function Manager(element, options) {
31143 this.options = assign({}, Hammer.defaults, options || {});
31144 this.options.inputTarget = this.options.inputTarget || element;
31145 this.handlers = {};
31146 this.session = {};
31147 this.recognizers = [];
31148 this.oldCssProps = {};
31149 this.element = element;
31150 this.input = createInputInstance(this);
31151 this.touchAction = new TouchAction(this, this.options.touchAction);
31152 toggleCssProps(this, true);
31153 each(this.options.recognizers, function (item) {
31154 var recognizer = this.add(new item[0](item[1]));
31155 item[2] && recognizer.recognizeWith(item[2]);
31156 item[3] && recognizer.requireFailure(item[3]);
31157 }, this);
31158 }
31159
31160 Manager.prototype = {
31161 /**
31162 * set options
31163 * @param {Object} options
31164 * @returns {Manager}
31165 */
31166 set: function (options) {
31167 assign(this.options, options); // Options that need a little more setup
31168
31169 if (options.touchAction) {
31170 this.touchAction.update();
31171 }
31172
31173 if (options.inputTarget) {
31174 // Clean up existing event listeners and reinitialize
31175 this.input.destroy();
31176 this.input.target = options.inputTarget;
31177 this.input.init();
31178 }
31179
31180 return this;
31181 },
31182
31183 /**
31184 * stop recognizing for this session.
31185 * This session will be discarded, when a new [input]start event is fired.
31186 * When forced, the recognizer cycle is stopped immediately.
31187 * @param {Boolean} [force]
31188 */
31189 stop: function (force) {
31190 this.session.stopped = force ? FORCED_STOP : STOP;
31191 },
31192
31193 /**
31194 * run the recognizers!
31195 * called by the inputHandler function on every movement of the pointers (touches)
31196 * it walks through all the recognizers and tries to detect the gesture that is being made
31197 * @param {Object} inputData
31198 */
31199 recognize: function (inputData) {
31200 var session = this.session;
31201
31202 if (session.stopped) {
31203 return;
31204 } // run the touch-action polyfill
31205
31206
31207 this.touchAction.preventDefaults(inputData);
31208 var recognizer;
31209 var recognizers = this.recognizers; // this holds the recognizer that is being recognized.
31210 // so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED
31211 // if no recognizer is detecting a thing, it is set to `null`
31212
31213 var curRecognizer = session.curRecognizer; // reset when the last recognizer is recognized
31214 // or when we're in a new session
31215
31216 if (!curRecognizer || curRecognizer && curRecognizer.state & STATE_RECOGNIZED) {
31217 curRecognizer = session.curRecognizer = null;
31218 }
31219
31220 var i = 0;
31221
31222 while (i < recognizers.length) {
31223 recognizer = recognizers[i]; // find out if we are allowed try to recognize the input for this one.
31224 // 1. allow if the session is NOT forced stopped (see the .stop() method)
31225 // 2. allow if we still haven't recognized a gesture in this session, or the this recognizer is the one
31226 // that is being recognized.
31227 // 3. allow if the recognizer is allowed to run simultaneous with the current recognized recognizer.
31228 // this can be setup with the `recognizeWith()` method on the recognizer.
31229
31230 if (session.stopped !== FORCED_STOP && ( // 1
31231 !curRecognizer || recognizer == curRecognizer || // 2
31232 recognizer.canRecognizeWith(curRecognizer))) {
31233 // 3
31234 recognizer.recognize(inputData);
31235 } else {
31236 recognizer.reset();
31237 } // if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the
31238 // current active recognizer. but only if we don't already have an active recognizer
31239
31240
31241 if (!curRecognizer && recognizer.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED)) {
31242 curRecognizer = session.curRecognizer = recognizer;
31243 }
31244
31245 i++;
31246 }
31247 },
31248
31249 /**
31250 * get a recognizer by its event name.
31251 * @param {Recognizer|String} recognizer
31252 * @returns {Recognizer|Null}
31253 */
31254 get: function (recognizer) {
31255 if (recognizer instanceof Recognizer) {
31256 return recognizer;
31257 }
31258
31259 var recognizers = this.recognizers;
31260
31261 for (var i = 0; i < recognizers.length; i++) {
31262 if (recognizers[i].options.event == recognizer) {
31263 return recognizers[i];
31264 }
31265 }
31266
31267 return null;
31268 },
31269
31270 /**
31271 * add a recognizer to the manager
31272 * existing recognizers with the same event name will be removed
31273 * @param {Recognizer} recognizer
31274 * @returns {Recognizer|Manager}
31275 */
31276 add: function (recognizer) {
31277 if (invokeArrayArg(recognizer, 'add', this)) {
31278 return this;
31279 } // remove existing
31280
31281
31282 var existing = this.get(recognizer.options.event);
31283
31284 if (existing) {
31285 this.remove(existing);
31286 }
31287
31288 this.recognizers.push(recognizer);
31289 recognizer.manager = this;
31290 this.touchAction.update();
31291 return recognizer;
31292 },
31293
31294 /**
31295 * remove a recognizer by name or instance
31296 * @param {Recognizer|String} recognizer
31297 * @returns {Manager}
31298 */
31299 remove: function (recognizer) {
31300 if (invokeArrayArg(recognizer, 'remove', this)) {
31301 return this;
31302 }
31303
31304 recognizer = this.get(recognizer); // let's make sure this recognizer exists
31305
31306 if (recognizer) {
31307 var recognizers = this.recognizers;
31308 var index = inArray(recognizers, recognizer);
31309
31310 if (index !== -1) {
31311 recognizers.splice(index, 1);
31312 this.touchAction.update();
31313 }
31314 }
31315
31316 return this;
31317 },
31318
31319 /**
31320 * bind event
31321 * @param {String} events
31322 * @param {Function} handler
31323 * @returns {EventEmitter} this
31324 */
31325 on: function (events, handler) {
31326 if (events === undefined$1) {
31327 return;
31328 }
31329
31330 if (handler === undefined$1) {
31331 return;
31332 }
31333
31334 var handlers = this.handlers;
31335 each(splitStr(events), function (event) {
31336 handlers[event] = handlers[event] || [];
31337 handlers[event].push(handler);
31338 });
31339 return this;
31340 },
31341
31342 /**
31343 * unbind event, leave emit blank to remove all handlers
31344 * @param {String} events
31345 * @param {Function} [handler]
31346 * @returns {EventEmitter} this
31347 */
31348 off: function (events, handler) {
31349 if (events === undefined$1) {
31350 return;
31351 }
31352
31353 var handlers = this.handlers;
31354 each(splitStr(events), function (event) {
31355 if (!handler) {
31356 delete handlers[event];
31357 } else {
31358 handlers[event] && handlers[event].splice(inArray(handlers[event], handler), 1);
31359 }
31360 });
31361 return this;
31362 },
31363
31364 /**
31365 * emit event to the listeners
31366 * @param {String} event
31367 * @param {Object} data
31368 */
31369 emit: function (event, data) {
31370 // we also want to trigger dom events
31371 if (this.options.domEvents) {
31372 triggerDomEvent(event, data);
31373 } // no handlers, so skip it all
31374
31375
31376 var handlers = this.handlers[event] && this.handlers[event].slice();
31377
31378 if (!handlers || !handlers.length) {
31379 return;
31380 }
31381
31382 data.type = event;
31383
31384 data.preventDefault = function () {
31385 data.srcEvent.preventDefault();
31386 };
31387
31388 var i = 0;
31389
31390 while (i < handlers.length) {
31391 handlers[i](data);
31392 i++;
31393 }
31394 },
31395
31396 /**
31397 * destroy the manager and unbinds all events
31398 * it doesn't unbind dom events, that is the user own responsibility
31399 */
31400 destroy: function () {
31401 this.element && toggleCssProps(this, false);
31402 this.handlers = {};
31403 this.session = {};
31404 this.input.destroy();
31405 this.element = null;
31406 }
31407 };
31408 /**
31409 * add/remove the css properties as defined in manager.options.cssProps
31410 * @param {Manager} manager
31411 * @param {Boolean} add
31412 */
31413
31414 function toggleCssProps(manager, add) {
31415 var element = manager.element;
31416
31417 if (!element.style) {
31418 return;
31419 }
31420
31421 var prop;
31422 each(manager.options.cssProps, function (value, name) {
31423 prop = prefixed(element.style, name);
31424
31425 if (add) {
31426 manager.oldCssProps[prop] = element.style[prop];
31427 element.style[prop] = value;
31428 } else {
31429 element.style[prop] = manager.oldCssProps[prop] || '';
31430 }
31431 });
31432
31433 if (!add) {
31434 manager.oldCssProps = {};
31435 }
31436 }
31437 /**
31438 * trigger dom event
31439 * @param {String} event
31440 * @param {Object} data
31441 */
31442
31443
31444 function triggerDomEvent(event, data) {
31445 var gestureEvent = document.createEvent('Event');
31446 gestureEvent.initEvent(event, true, true);
31447 gestureEvent.gesture = data;
31448 data.target.dispatchEvent(gestureEvent);
31449 }
31450
31451 assign(Hammer, {
31452 INPUT_START: INPUT_START,
31453 INPUT_MOVE: INPUT_MOVE,
31454 INPUT_END: INPUT_END,
31455 INPUT_CANCEL: INPUT_CANCEL,
31456 STATE_POSSIBLE: STATE_POSSIBLE,
31457 STATE_BEGAN: STATE_BEGAN,
31458 STATE_CHANGED: STATE_CHANGED,
31459 STATE_ENDED: STATE_ENDED,
31460 STATE_RECOGNIZED: STATE_RECOGNIZED,
31461 STATE_CANCELLED: STATE_CANCELLED,
31462 STATE_FAILED: STATE_FAILED,
31463 DIRECTION_NONE: DIRECTION_NONE,
31464 DIRECTION_LEFT: DIRECTION_LEFT,
31465 DIRECTION_RIGHT: DIRECTION_RIGHT,
31466 DIRECTION_UP: DIRECTION_UP,
31467 DIRECTION_DOWN: DIRECTION_DOWN,
31468 DIRECTION_HORIZONTAL: DIRECTION_HORIZONTAL,
31469 DIRECTION_VERTICAL: DIRECTION_VERTICAL,
31470 DIRECTION_ALL: DIRECTION_ALL,
31471 Manager: Manager,
31472 Input: Input,
31473 TouchAction: TouchAction,
31474 TouchInput: TouchInput,
31475 MouseInput: MouseInput,
31476 PointerEventInput: PointerEventInput,
31477 TouchMouseInput: TouchMouseInput,
31478 SingleTouchInput: SingleTouchInput,
31479 Recognizer: Recognizer,
31480 AttrRecognizer: AttrRecognizer,
31481 Tap: TapRecognizer,
31482 Pan: PanRecognizer,
31483 Swipe: SwipeRecognizer,
31484 Pinch: PinchRecognizer,
31485 Rotate: RotateRecognizer,
31486 Press: PressRecognizer,
31487 on: addEventListeners,
31488 off: removeEventListeners,
31489 each: each,
31490 merge: merge,
31491 extend: extend,
31492 assign: assign,
31493 inherit: inherit,
31494 bindFn: bindFn,
31495 prefixed: prefixed
31496 }); // this prevents errors when Hammer is loaded in the presence of an AMD
31497 // style loader but by script tag, not by the loader.
31498
31499 var freeGlobal = typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}; // jshint ignore:line
31500
31501 freeGlobal.Hammer = Hammer;
31502
31503 if (typeof undefined$1 === 'function' && undefined$1.amd) {
31504 undefined$1(function () {
31505 return Hammer;
31506 });
31507 } else if ( module.exports) {
31508 module.exports = Hammer;
31509 } else {
31510 window[exportName] = Hammer;
31511 }
31512 })(window, document, 'Hammer');
31513});
31514
31515var hammer$1 = createCommonjsModule$1(function (module) {
31516 /**
31517 * Setup a mock hammer.js object, for unit testing.
31518 *
31519 * Inspiration: https://github.com/uber/deck.gl/pull/658
31520 *
31521 * @returns {{on: noop, off: noop, destroy: noop, emit: noop, get: get}}
31522 */
31523 function hammerMock() {
31524 var noop = function noop() {};
31525
31526 return {
31527 on: noop,
31528 off: noop,
31529 destroy: noop,
31530 emit: noop,
31531 get: function get(m) {
31532 //eslint-disable-line no-unused-vars
31533 return {
31534 set: noop
31535 };
31536 }
31537 };
31538 }
31539
31540 if (typeof window !== 'undefined') {
31541 var propagating$1 = propagating;
31542 var Hammer = window['Hammer'] || hammer;
31543 module.exports = propagating$1(Hammer, {
31544 preventDefault: 'mouse'
31545 });
31546 } else {
31547 module.exports = function () {
31548 // hammer.js is only available in a browser, not in node.js. Replacing it with a mock object.
31549 return hammerMock();
31550 };
31551 }
31552});
31553
31554var keycharm = createCommonjsModule$1(function (module, exports) {
31555 /**
31556 * Created by Alex on 11/6/2014.
31557 */
31558 // https://github.com/umdjs/umd/blob/master/returnExports.js#L40-L60
31559 // if the module has no dependencies, the above pattern can be simplified to
31560
31561 (function (root, factory) {
31562 {
31563 // Node. Does not work with strict CommonJS, but
31564 // only CommonJS-like environments that support module.exports,
31565 // like Node.
31566 module.exports = factory();
31567 }
31568 })(commonjsGlobal$1, function () {
31569 function keycharm(options) {
31570 var preventDefault = options && options.preventDefault || false;
31571 var container = options && options.container || window;
31572 var _exportFunctions = {};
31573 var _bound = {
31574 keydown: {},
31575 keyup: {}
31576 };
31577 var _keys = {};
31578 var i; // a - z
31579
31580 for (i = 97; i <= 122; i++) {
31581 _keys[String.fromCharCode(i)] = {
31582 code: 65 + (i - 97),
31583 shift: false
31584 };
31585 } // A - Z
31586
31587
31588 for (i = 65; i <= 90; i++) {
31589 _keys[String.fromCharCode(i)] = {
31590 code: i,
31591 shift: true
31592 };
31593 } // 0 - 9
31594
31595
31596 for (i = 0; i <= 9; i++) {
31597 _keys['' + i] = {
31598 code: 48 + i,
31599 shift: false
31600 };
31601 } // F1 - F12
31602
31603
31604 for (i = 1; i <= 12; i++) {
31605 _keys['F' + i] = {
31606 code: 111 + i,
31607 shift: false
31608 };
31609 } // num0 - num9
31610
31611
31612 for (i = 0; i <= 9; i++) {
31613 _keys['num' + i] = {
31614 code: 96 + i,
31615 shift: false
31616 };
31617 } // numpad misc
31618
31619
31620 _keys['num*'] = {
31621 code: 106,
31622 shift: false
31623 };
31624 _keys['num+'] = {
31625 code: 107,
31626 shift: false
31627 };
31628 _keys['num-'] = {
31629 code: 109,
31630 shift: false
31631 };
31632 _keys['num/'] = {
31633 code: 111,
31634 shift: false
31635 };
31636 _keys['num.'] = {
31637 code: 110,
31638 shift: false
31639 }; // arrows
31640
31641 _keys['left'] = {
31642 code: 37,
31643 shift: false
31644 };
31645 _keys['up'] = {
31646 code: 38,
31647 shift: false
31648 };
31649 _keys['right'] = {
31650 code: 39,
31651 shift: false
31652 };
31653 _keys['down'] = {
31654 code: 40,
31655 shift: false
31656 }; // extra keys
31657
31658 _keys['space'] = {
31659 code: 32,
31660 shift: false
31661 };
31662 _keys['enter'] = {
31663 code: 13,
31664 shift: false
31665 };
31666 _keys['shift'] = {
31667 code: 16,
31668 shift: undefined
31669 };
31670 _keys['esc'] = {
31671 code: 27,
31672 shift: false
31673 };
31674 _keys['backspace'] = {
31675 code: 8,
31676 shift: false
31677 };
31678 _keys['tab'] = {
31679 code: 9,
31680 shift: false
31681 };
31682 _keys['ctrl'] = {
31683 code: 17,
31684 shift: false
31685 };
31686 _keys['alt'] = {
31687 code: 18,
31688 shift: false
31689 };
31690 _keys['delete'] = {
31691 code: 46,
31692 shift: false
31693 };
31694 _keys['pageup'] = {
31695 code: 33,
31696 shift: false
31697 };
31698 _keys['pagedown'] = {
31699 code: 34,
31700 shift: false
31701 }; // symbols
31702
31703 _keys['='] = {
31704 code: 187,
31705 shift: false
31706 };
31707 _keys['-'] = {
31708 code: 189,
31709 shift: false
31710 };
31711 _keys[']'] = {
31712 code: 221,
31713 shift: false
31714 };
31715 _keys['['] = {
31716 code: 219,
31717 shift: false
31718 };
31719
31720 var down = function (event) {
31721 handleEvent(event, 'keydown');
31722 };
31723
31724 var up = function (event) {
31725 handleEvent(event, 'keyup');
31726 }; // handle the actualy bound key with the event
31727
31728
31729 var handleEvent = function (event, type) {
31730 if (_bound[type][event.keyCode] !== undefined) {
31731 var bound = _bound[type][event.keyCode];
31732
31733 for (var i = 0; i < bound.length; i++) {
31734 if (bound[i].shift === undefined) {
31735 bound[i].fn(event);
31736 } else if (bound[i].shift == true && event.shiftKey == true) {
31737 bound[i].fn(event);
31738 } else if (bound[i].shift == false && event.shiftKey == false) {
31739 bound[i].fn(event);
31740 }
31741 }
31742
31743 if (preventDefault == true) {
31744 event.preventDefault();
31745 }
31746 }
31747 }; // bind a key to a callback
31748
31749
31750 _exportFunctions.bind = function (key, callback, type) {
31751 if (type === undefined) {
31752 type = 'keydown';
31753 }
31754
31755 if (_keys[key] === undefined) {
31756 throw new Error("unsupported key: " + key);
31757 }
31758
31759 if (_bound[type][_keys[key].code] === undefined) {
31760 _bound[type][_keys[key].code] = [];
31761 }
31762
31763 _bound[type][_keys[key].code].push({
31764 fn: callback,
31765 shift: _keys[key].shift
31766 });
31767 }; // bind all keys to a call back (demo purposes)
31768
31769
31770 _exportFunctions.bindAll = function (callback, type) {
31771 if (type === undefined) {
31772 type = 'keydown';
31773 }
31774
31775 for (var key in _keys) {
31776 if (_keys.hasOwnProperty(key)) {
31777 _exportFunctions.bind(key, callback, type);
31778 }
31779 }
31780 }; // get the key label from an event
31781
31782
31783 _exportFunctions.getKey = function (event) {
31784 for (var key in _keys) {
31785 if (_keys.hasOwnProperty(key)) {
31786 if (event.shiftKey == true && _keys[key].shift == true && event.keyCode == _keys[key].code) {
31787 return key;
31788 } else if (event.shiftKey == false && _keys[key].shift == false && event.keyCode == _keys[key].code) {
31789 return key;
31790 } else if (event.keyCode == _keys[key].code && key == 'shift') {
31791 return key;
31792 }
31793 }
31794 }
31795
31796 return "unknown key, currently not supported";
31797 }; // unbind either a specific callback from a key or all of them (by leaving callback undefined)
31798
31799
31800 _exportFunctions.unbind = function (key, callback, type) {
31801 if (type === undefined) {
31802 type = 'keydown';
31803 }
31804
31805 if (_keys[key] === undefined) {
31806 throw new Error("unsupported key: " + key);
31807 }
31808
31809 if (callback !== undefined) {
31810 var newBindings = [];
31811 var bound = _bound[type][_keys[key].code];
31812
31813 if (bound !== undefined) {
31814 for (var i = 0; i < bound.length; i++) {
31815 if (!(bound[i].fn == callback && bound[i].shift == _keys[key].shift)) {
31816 newBindings.push(_bound[type][_keys[key].code][i]);
31817 }
31818 }
31819 }
31820
31821 _bound[type][_keys[key].code] = newBindings;
31822 } else {
31823 _bound[type][_keys[key].code] = [];
31824 }
31825 }; // reset all bound variables.
31826
31827
31828 _exportFunctions.reset = function () {
31829 _bound = {
31830 keydown: {},
31831 keyup: {}
31832 };
31833 }; // unbind all listeners and reset all variables.
31834
31835
31836 _exportFunctions.destroy = function () {
31837 _bound = {
31838 keydown: {},
31839 keyup: {}
31840 };
31841 container.removeEventListener('keydown', down, true);
31842 container.removeEventListener('keyup', up, true);
31843 }; // create listeners.
31844
31845
31846 container.addEventListener('keydown', down, true);
31847 container.addEventListener('keyup', up, true); // return the public functions.
31848
31849 return _exportFunctions;
31850 }
31851
31852 return keycharm;
31853 });
31854});
31855
31856var util_1 = util;
31857var DOMutil$1 = DOMutil; // data
31858
31859var DataSet$2 = index.DataSet,
31860 DataView$3 = index.DataView,
31861 Queue$1 = index.Queue;
31862var DataSet_1 = DataSet$2;
31863var DataView_1 = DataView$3;
31864var Queue_1 = Queue$1; // Graph3d
31865
31866var Graph3d$1 = Graph3d_1;
31867var graph3d = {
31868 Camera: Camera_1,
31869 Filter: Filter_1,
31870 Point2d: Point2d_1,
31871 Point3d: Point3d_1,
31872 Slider: Slider_1,
31873 StepNumber: StepNumber_1
31874}; // bundled external libraries
31875
31876var moment$4 = moment$3;
31877var Hammer = hammer$1;
31878var keycharm$1 = keycharm;
31879var repo = {
31880 util: util_1,
31881 DOMutil: DOMutil$1,
31882 DataSet: DataSet_1,
31883 DataView: DataView_1,
31884 Queue: Queue_1,
31885 Graph3d: Graph3d$1,
31886 graph3d: graph3d,
31887 moment: moment$4,
31888 Hammer: Hammer,
31889 keycharm: keycharm$1
31890};
31891
31892export default repo;
31893export { DOMutil$1 as DOMutil, DataSet_1 as DataSet, DataView_1 as DataView, Graph3d$1 as Graph3d, Hammer, Queue_1 as Queue, graph3d, keycharm$1 as keycharm, moment$4 as moment, util_1 as util };